.val()

.val() Method

  • Method is mainly used to get or set the current value of the HTML form elements such as <input>, <select> and <textarea>

Example of Getting (Reading) values from form elements

  • To Get (Read) text of an element use .val() with nothing inside the parentheses
$(() => {
  $("#getName").click(() => {
    // read value of text field
    const name = $("#name").val()
    alert(name)
  })


  $("#getComment").click(() => {
    // read value of the text area
    const comment = $("#comment").val()
    alert(comment)
  })


  $("#getCity").click(() => {
    // read value from select dropdown
    const city = $("#city").val()
    alert(city)
  })
})

JS Bin on jsbin.com


Example of Setting (writing) values to form elements

  • To Set (Write) text of an element use .val(newVal) with the new value inside the parentheses
$(() => {

  $("#setName").click(() => {
    // set value of text field
    $("#name").val("Jill Scott")
  })


  $("#setComment").click(() => {
    // set value of the text area
    $("#comment").val("She's awesome!")
  })


  $("#setCity").click(() => {
    // set value of select dropdown
    $("#city").val("Philadelphia")
  })
})

JS Bin on jsbin.com