Pete_1 Pete_1 - 1 year ago 55
Javascript Question

jQuery, detecting actual input text value

I'm running into an issue where the value grabbed by jQuery, and what's actually in the input text field, are different.

A form with a variety of inputs are populated when the page loads with information from our database. Thus, the input text fields all have a value.

When the form is submitted, I have a function that runs first to check for text inputs. This is a portion of that function:

$("form#accountSettingsForm input").each(function(){
var input = $(this);
var value = input.attr("value");

Lets say the input value is 12 when the page had initially loaded. If I delete the 12 in the textbox and leave the field blank, and submit the form, the above code retrieved "value" is still 12, not empty.
How can I detect what's actually the textbox's value? Thanks in advance.

Answer Source

This is a situation where there's a difference between the value attribute and the value property. The attribute comes from the HTML, the property is from the dynamic state of the DOM. To get the current value of an input after the user has modified it, use the jQuery .val() method.

$("#accountSettingsForm").submit(function() {
  $(this).find("input").each(function() {
    var input = $(this);
    var value = input.val();
    console.log( + " = " + value);
  return false;
<script src=""></script>
<form id="accountSettingsForm">
  Input 1:
  <input name="field1" type="text">
  <br>Input 2:
  <input name="field2" type="text">
  <input name="submit" type="submit">