[英]Pass variable value from form javascript
假設我有一個像下面這樣的HTML表單,並希望將textfields中的值傳遞給JS變量。
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
我之前只將值傳遞給PHP中的變量。 在javascript中執行此操作時,是否需要方法? 主要問題是,它是如何完成的?
以下是幾個例子:
使用Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery的:
$("#name_of_input_control_id").val();
基本上你是使用Javascript / jQuery從DOM中提取輸入控件的值。
在“提交”中嘗試以下內容:
var input = $("#testfield1").val();
答案都是正確的但你可能會遇到問題,如果你不把你的代碼放入document.ready函數...如果你的代碼塊高於html部分,你將找不到任何帶id的輸入字段,因為在這一刻它不會存在...
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();
});
如果您只是在Javascript中使用文本字段,則實際上不需要method
或action
屬性
submit
表單添加一個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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.