-
val( ) returns String, Array
Get the content of the value attribute of the first matched element.
In jQuery 1.2, a value is now returned for all elements, including selects. For multiple selects an array of values is returned.
For older versions of jQuery use the [http://www.malsup.com/jquery/form/#fields fieldValue function of the Form Plugin].Example:
Get the single value from a single select and an array of values from a multiple select and display their values.
function displayVals() { var singleValues = $("#single").val(); var multipleValues = $("#multiple").val() || []; $("p").html("<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.join(", ")); } $("select").change(displayVals); displayVals();HTML:
<p></p> <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select>Example:
Find the value of an input box.
$("input").keyup(function () { var value = $(this).val(); $("p").text(value); }).keyup();HTML:
<input type="text" value="some text"/> <p></p> -
val( String val ) returns jQuery
Set the value attribute of every matched element.
In jQuery 1.2, this is also able to set the value of select elements, but selecting the appropriate options.Example:
Set the value of an input box.
$("button").click(function () { var text = $(this).text(); $("input").val(text); });HTML:
<div> <button>Feed</button> <button>the</button> <button>Input</button> </div> <input type="text" value="click a button" /> -
val( Array<String> val ) returns jQuery
Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
Example:
Get the single value from a single select and an array of values from a multiple select and display their values.
$("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check2", "radio1"]);HTML:
<select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" value="check1"/> check1 <input type="checkbox" value="check2"/> check2 <input type="radio" name="r" value="radio1"/> radio1 <input type="radio" name="r" value="radio2"/> radio2 -
visible( ) returns Array<Element>
Matches all elements that are visible.
Example:
Make all visible divs turn yellow on click.
$("div:visible").click(function () { $(this).css("background", "yellow"); }); $("button").click(function () { $("div:hidden").show("fast"); });HTML:
<button>Show hidden to see they don't change</button> <div></div> <div class="starthidden"></div> <div></div> <div></div> <div style="display:none;"></div>