2012-12-02 90 views
5

假設我得到了一個如下所示的HTML表單,並且希望將文本字段中的值傳遞給JS變量。從窗體傳遞變量值javascript

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

我只在PHP中將值傳遞給變量。在javascript中執行時,我需要一個方法嗎?主要問題,它是如何完成的?

回答

3

這裏有幾個例子:

的Javascript:

document.getElementById('name_of_input_control_id').value; 

的jQuery:

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

基本上你是從使用Javascript的DOM中提取輸入控件的值/ jQuery的。

+1

注意如何在OP的示例中的控件沒有一個ID,雖然... –

+1

確實。 OP將不得不爲他/她的輸入控件添加一個ID。 – Lowkase

+0

我的觀點是:不一定。使用名稱就好了,因爲表單元素無論如何都需要一個名字(至少當他們還通過表單與服務器進行通信時),爲什麼不使用它呢? –

0

嘗試在「提交」下面:

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

的答案是正確的,但如果你不把你的代碼放到一個的document.ready功能......如果你的代碼塊上面你可能會面臨的問題你不會找到ID爲任何輸入欄,因爲在這一刻它不存在於HTML部分...

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(); 
}); 
0

如果你只是使用文本字段在Javascript中你並不真的需要一個methodaction屬性

添加submit按鈕和onsubmit處理程序,以這樣的形式,

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

然後,在JavaScript你可以有這個processForm功能

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 
}