Getting and setting value of html elements using jQuery
If you have started using jQuery recently and you are used to DOM methods of getting and setting values for form and html elements, this article is for you.
Using jQuery can be confusing in the beginning but it is a lot easier once you get hold of it. In this post I will summarize methods for getting and setting values for html elements using jQuery. I assume that you are familiar with the $ function. Though it can be used in different ways to select elements, we will stick to selecting elements by id for the purpose of this tutorial.
An element can be accessed using its id as follows:
$('#someId')
Textbox, Hidden field and Textarea
All these elements share a common method. val() method is used to get and set values for these elements.
Setting:
$('#someid').val('any value')
will set the value of textbox to “any value”.
Getting:
$('#someid').val()
will get the value of that text box.
Radio Buttons and checkboxes
attr() is used to check/uncheck and select/unselect radios and checkboxes
Setting:
$('#id').attr('checked', true)
will select the control
$('#id').attr('checked', false)
will unselect the control
Getting
$('#id').attr('checked')
This will give true if radio/checkbox is checked/selected, false otherwise.
Select box/ Combo box
A notorious control, jQuery makes it very easy to get and set value of a combo box.
Setting:
$('#selectbox').val('1')
Pass the value of option that you wish to select to val()
Getting:
$('#selectbox').val()
This will give value of currently selected option in combo box
Setting/Getting innerHTML of other elements
Just like innerHTML, jQuery provides a handy function to manipulate innerHTML for all html elements.
Setting:
$('#somediv').html('some html inside a paragraph')
This will set the innerHTML of element with id somediv
Getting:
$('#somediv').html()
This will return the innerHTML of an element.
Thats all to it. Again, a demo can be found at this link (and obviously source code too). You can always shoot me a mail in case your question is not answered here.
Give this article a thumbs up on stumble upon if you liked this
Related Posts
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.



Good post dude hurrahhhh it helped me a lot thanks
Nice post
Nice Post ……
eaiser way to start work on jquery…
demo is quiet enough to understand ..how it’s works..
Thanks for such a nice post
Cheers!!!