admin管理员组

文章数量:1278886

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.

<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>

I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.

<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>

I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?

Share Improve this question asked Dec 2, 2012 at 20:31 Simon CarlsonSimon Carlson 1,9895 gold badges24 silver badges36 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Here are a couple of examples:

Javascript:

document.getElementById('name_of_input_control_id').value;

jQuery:

$("#name_of_input_control_id").val();

Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.

the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...

document.addEventListener('DOMContentLoaded', function() {
   var input = document.getElementById('name_of_input_control_id').value;
}, false);

jQuery

jQuery(document).ready(function($){
    var input = $("#name_of_input_control_id").val();
});

You don't really need a method or an action attribute if you're simply using the text fields in Javascript

Add a submit button and an onsubmit handler to the form like this,

<form name="testform" onsubmit="return processForm(this)">
    <input type="text" name="testfield1"/>
    <input type="text" name="testfield2"/>
    <input type="submit"/>
</form>

Then in your Javascript you could have this processForm function

function processForm(form) {
    var inputs = form.getElementsByTagName("input");
    // parse text field values into an object
    var textValues = {};
    for(var x = 0; x < inputs.length; x++) {
        if(inputs[x].type != "text") {
            // ignore anything which is NOT a text field
            continue;
        }

        textValues[inputs[x].name] = inputs[x].value;
    }

    // textValues['testfield1'] contains value of first input
    // textValues['testfield2'] contains value of second input

    return false;  // this causes form to NOT 'refresh' the page
}

Try the following in your "submit":

var input = $("#testfield1").val();

本文标签: htmlPass variable value from form javascriptStack Overflow