jQuery - Forms
In the previous section we learned how to work with different types of form fields with Javascript. Let's see how to do it with jQuery.
.val()
The val() method is used to get or change the value of form fields.
var contentInput = $("#name_field").val();
console.log(contentInput);
Nome:
$("#name_field").val("Peter Green");
contentInput = $("#name_field").val();
console.log(contentInput);
Working with other field types
Select Box
The val() method returns the value attribute of a selected option in a select box.
var selectedValue = $('#options').val();
console.log(selectedValue);
Getting the text of the selected value is also easy by using the selecting capability of jQuery:
var selectedText = $("#options option:selected").text();
console.log(selectedText);
selected text to the console everytime a new option is selected by using the change event:
$("#options").change(function(){
var newValue = $("#options option:selected").text();
console.log(newValue);
});
Radio Buttons
Working with radio buttons in jQuery is similar to working with the selected box, we just need to adjust the selector.
var radioSelected = $("input[name='gender']:checked").val();
console.log(radioSelected);
To get the text of the selected value is a little more complicated because this kind of field does not have content inside. But we can do the trick by wrapping it inside a <span> element.
<span><input type="radio" name="gender" value="M" checked> Male</span><br>
<span><input type="radio" name="gender" value="F"> Female</span><br>
<span><input type="radio" name="gender" value="NONE"> Not informed</span>
Now since the radio buttons are wrapped inside span elements, getting the text of the selected option is pretty simple by using the parent() method and then the text() method, which ignores all html content.
var textRadio = $("input[name='gender']:checked").parent('span').text();;
console.log(textRadio);
Now let's get the updated value everytime the field changes:
$("input[name='gender']").change(function() {
var newRadioValue = $("input[name='gender']:checked").parent('span').text();;
console.log(newRadioValue);
});
CheckBoxes
Woring with select boxes is similar to working with radio buttons, but since multiple options can be selected at the same time, we need to work with arrays.
Fortunately, jQuery also has its own loops.
$("input[name='interest']").change(function() {
var selectedCheckboxes = $("input[name='interest']:checked");
var texts = [];
$.each(selectedCheckboxes, function( index, value ) {
texts.push($(value).parent("span").text());
});
console.log(texts);
});