问题描述:

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?

网友答案:

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();
相关阅读:
Top