How can I get the value of an input field in javascript without submitting a form?

BlueCola picture BlueCola · Nov 21, 2012 · Viewed 24.2k times · Source

I'm fairly new to javascript and have a question about how to get a value of an input field without submitting a form. I have the following small piece of code, which I'm using in combination with a realtime-validation script to validate the fields.

<form name="FormName" method="post" />
    <input type="text" id="nameValidation" value="HelloWorld" />
    <script type="text/javascript">
       var NameValue = document.forms["FormName"]["nameValidation"].value;
    </script>
</form>

I want the var NameValue to be the value of what you type into the input field so I can use it in the message which appears after the validation. When I change the value of the input field without submitting the form, the var NameValue is stil set to "HelloWorld". After doing some research I found out I could solve it using jQuery and it's function serialize(). Is there a way to do this without jQuery?

Answer

Denys S&#233;guret picture Denys Séguret · Nov 21, 2012

Without jQuery :

var value = document.getElementById('nameValidation').value;

The syntax you had would be usable to get an input by its name, not its id.

If what you want is to use this value when it changes, you can do that :

var nameValidationInput = document.getElementById('nameValidation');
function useValue() {
    var NameValue = nameValidationInput.value;
    // use it
    alert(NameValue); // just to show the new value
}
nameValidationInput.onchange = useValue;  
nameValidationInput.onblur = useValue;