Some time back I posted how to get and set form element values with jQuery just showing the HTML and Javascript needed to do so but without an actual demo. Someone asked for some demos of these yesterday so I present these here.
Getting a form value with jQuery – Example 1
The first example gets the value from the text box and displays it in an alert dialog. Type some text into the input and then click the button to see the value. If you are reading this in a feed reader then click through to view this post in a web browser otherwise it will not work.
The full HTML from the example above is this:
<form> Type something in here: <input id="example1" type="text" /> <input type="button" value="Show Value" onclick="alert( $('#example1').val() )" /> </form>
Getting a form value with jQuery – Example 2
The second example gets the value from the select box. Change the selection below and then click the button. The actual value will display in an alert dialog. In this select “one” = 1, “two” = 2 and “three” = 3.
And here’s the full HTML behind the example:
<form> <select id="example2"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> <input type="button" value="Show Value" onclick="alert( $('#example2').val() )" /> </form>
Setting a form value with jQuery – Example
This last example allows you to type some text into the first text box, click the button and then copy it across to the second box. This in effect demonstrates both getting and setting at the same time. Try it:
<form> Type something in here: <input id="example3a" type="text" /> <input type="button" value="Set Value" onclick="$('#example3b').val( $('#example3a').val() )" /> <input id="example3b" type="text" /> </form>
Further examples
For some further examples which include working demos on the page, read my how to check and uncheck a checkbox with jQuery and clear a form with jQuery posts.