Code has been added to clipboard!

jQuery .val(): Set or Get the Attribute Value of Form Elements

Reading time 1 min
Published Jan 24, 2018
Updated Sep 27, 2019

jQuery val: Main Tips

  • jQuery .val() sets or returns the attribute value of the matched HTML elements.
  • Usually, the jQuery .val() method deals with the values of form elements.

Using .val()

The jQuery .val() function assigns or returns the attribute value of specified elements. Check the example below to see a jQuery input value assigned to a text field upon clicking a button:

Example
$("button").click(() => {
    $("input:text").val("Ben Johnson");
});

Note: when the collection is empty, jQuery input value is returned as undefined.

To make jQuery get input value, you don't need to define any arguments:

$(selector).val();

Now, to make jQuery set input value, either a new value or a function that returns it must be specified:

$(selector).val(value);

$(selector).val(function);

Note: if you choose to add a function, remember that since jQuery 1.4, it receives two arguments - the position of the element and its value before the change.

Learn jQuery
Introduction
Selectors
Events
Event Methods
Download
Callback
Chaining
Get and Set
Add Element
Remove Element
Traverse
Parent
Children
Sibling Traverse
Filtering
jQuery AJAX
Effects
Show and Hide
Fade Effect
Slide Effect
Animate Effect
Manipulate CSS
Width and Height
.addClass()
.after()
.animate()
.append()
.appendTo()
.attr()
.before()
.bind() (deprecated)
.blur()
.change()
.click()
.clone()
.css()
.dblclick()
.delay()
.delegate() and .undelegate() (deprecated)
.detach()
.empty()
.end()
.error() (deprecated)
.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()
.finish()
.focus()
.focusIn()
.focusOut()
.hasClass()
.height()
.hide()
.hover()
.html()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.keypress()
.keyup()
.live() and .die() (deprecated)
.load() (deprecated)
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseout()
.mouseover()
.mouseup()
.off()
.offset()
.offsetParent()
.on()
.one()
.outerHeight()
.outerWidth()
.position()
.prepend()
.prependTo()
.prop()
.proxy()
.queue()
.ready()
.remove()
.removeAttr()
.removeClass()
.removeProp()
.replaceAll()
.replaceWith()
.resize()
.scroll()
.scrollLeft()
.scrollTop()
.show()
.slideDown()
.slideToggle()
.slideUp()
.stop()
.submit()
.text()
.toggle()
.toggleClass()
.trigger()
.triggerHandler()
.unbind() (deprecated)
.unload() (deprecated)
.unwrap()
.val()
.width()
.wrap()
Event Properties
event.currentTarget
event.preventDefault()
event.relatedTarget
event.stopImmediatePropagation()
event.stopPropagation()
event.target
event.timeStamp
event.type
event.which
jQuery .find()
jQuery .keydown()
jQuery.noConflict()
pageY and pageX