
Using jQuery,how do you get the value of a form input?
How do you get the value depends on what type of input it is.
See related:
Checkboxes
Here is the HTML for the text input box and the "show selection" link:
<fieldset id="checkbox_input">
<legend>Sample checkbox inputs</legend>
<input type="checkbox" name="sample-checkbox" id="cbx_country1" value="India" />India
<input type="checkbox" name="sample-checkbox" id="cbx_country2" value="America" />America
<input type="checkbox" name="sample-checkbox" id="cbx_country3" value="Africa" />Africa
<input type="checkbox" name="sample-checkbox" id="cbx_country4" value="Srilanka" />Srilanka
<a href="javascript:getCheckBoxValues('sample-checkbox');">show selection</a>
</fieldset>
For a checkbox input, because there may be multiple selections chosen, you need to
- Locate all checkboxes that are checked, using $('input:checkbox[name='CheckboxName']:checked')
- Loop through the checked checkboxes, using .each
- Append the values of each checked checkbox to each other, using .push
In this example, I pass the name of the checkbox group into the function and "alert" the result. You could easily change this to "return" the value or assign the value to a variable.
function getCheckBoxValues(checkboxName) {
var checkboxVals = [];
$('input:checkbox[name='+checkboxName+']:checked').each(function(index){
checkboxVals.push($(this).val());
})
alert('You selected check boxes "' + checkboxVals + '"');
}