stackemedia

JQuery Set / Get form fields

This was posted in jQuery on August 28th, 2009

Ever wondered how you could use jQuery to get and set form fields?

First of all you will need to get the latest version of the jQuery framework from http://jquery.com/.

Next you will need to reference it in your web page – between the “head” tags (1.3.2 was the latest version of writing this).

< script src='jquery-1.3.2.min.js' type='text/javascript'>< /script >

To set the value of a combo box on you form, add the following script (after the reference to the jquery framework), where 1 is the second item in the combo box.

$('[name=yourlistboxname]')[0].selectedIndex = 1;

To set the value of an text box, use the following code:

$('[name=yourtextboxname]').val('texttoadd');

To set a checkbox to checked, then use the following code:

$('[name=yourcheckboxname]')[0].checked = true;

That’s all there is to it.

To get the form value you could do something like this:

var myvalue;
myvalue = $(‘[name=yourtextboxname]‘).val();
alert(myvalue);

View the Demo here, or download the code.


Tested browsers: firefox, chrome, IE8