Page 1 of 1

Autofill a textbox without refreshing the page

Posted: Fri Apr 15, 2011 1:25 pm
by adige
Hi.

I would like to automatically fill in the textbox labeled "Amount 2" after choosing the value of Amount without refreshing the page. I guess it requires javascript or AJAX but i don't know how to do it. Any help please?

http://i55.tinypic.com/29crpdz.jpg

Code: Select all

$options_amount = array("0","1","2","3","4","5","6","7","8","9","10+");

$metabox = array();

$metabox[] = array(   "name" => "amount",
                            "label" => "Amount",
                            "desc" => "Choose the amount.",
                            "std" => "0",
                             "type" => "select",
                            "options" => $options_amount);

$metabox[] = array(   "name" => "amount2",
                            "label" => "Amount 2",
                            "desc" => "No need to enter it.",
                            "std" => "",
                            "type" => "text"); 

Re: Autofill a textbox without refreshing the page

Posted: Fri Apr 15, 2011 3:38 pm
by McInfo
This is one way to do it.

example.html

Code: Select all

<!DOCTYPE html>
<html>
    <head>
        <title>example</title>
        <script type="text/javascript" src="example.js"></script>
    </head>
    <body>
        <form method="post" action="">
            <p>
                <select name="a" id="a">
                    <option value="0">0</option>
                    <option value="15">15</option>
                    <option value="30">30</option>
                    <option value="45">45</option>
                </select>
                <input type="text" name="b" id="b" value="0" />
            </p>
        </form>
    </body>
</html>
example.js

Code: Select all

window.onload = function () {
    var a = document.getElementById('a');
    var b = document.getElementById('b');
    a.onchange = function () {
        b.value = this.options[this.selectedIndex].value;
    }
}
The example uses the HTMLSelectElement.selectedIndex property to look up the selected HTMLOptionElement in the options array. It gets the HTMLOptionElement.value property and assigns that value to the HTMLInputElement.value property.

Note that within a JavaScript function, the this keyword refers to the object to which the function belongs.

Re: Autofill a textbox without refreshing the page

Posted: Fri Apr 15, 2011 6:07 pm
by adige
Hey, thanks for the reply.

How can i embed this html codes into a php file? Or is it possible?

Re: Autofill a textbox without refreshing the page

Posted: Fri Apr 15, 2011 6:19 pm
by McInfo
Just change the file extension, and the HTML file (example.html) will be a PHP file (example.php). Read "What is PHP?"