gpt4 book ai didi

javascript - 使用 javascript 返回表单的值

转载 作者:行者123 更新时间:2023-12-03 12:34:34 25 4
gpt4 key购买 nike

我有一个带有下拉框、复选框和文本字段的 HTML 表单。

我正在寻找一种使用 JavaScript 返回表单值的解决方案。

换句话说,javascript 必须读取表单并返回输入的字段名称和值。

返回字符串应类似于以下内容:

ans00441, 908, txt00441, "我还不知道", ans00442, "国家 2", ans00442, "国家 3", ans00442, "国家 4", ans00444, "非常多", txt00444, "太多”

下面的 FORM1 已作为示例提交。

如有任何建议,我们将不胜感激。

表格1

<SCRIPT LANGUAGE="JavaScript">


function showResult(frm){
alert('Display field names and values');
}

</SCRIPT>


<table>
<tr>
<td>
<h2 id="qst00441">For who will you vote</h2>
<br>
<input type="radio" name="ans00441" value="908 ">Party 1<br>
<input type="radio" name="ans00441" value="909 ">Party 2<br>
<input type="radio" name="ans00441" value="910 ">Party 3<br>
<input type="radio" name="ans00441" value="911 ">Party 4<br>
<br>Other Party<input type="text" name="txt00441" size="45" value="" ><br>
</td>
</tr>
<tr>
<td>
<h2 id="qst00442">Where do you live</h2>
<br>
<input type="checkbox" name="ans00442" value="912 ">Country 1<br>
<input type="checkbox" name="ans00442" value="913 ">Country 2<br>
<input type="checkbox" name="ans00442" value="914 ">Country 3<br>
<input type="checkbox" name="ans00442" value="915 ">Country 4<br>
<br>Other country <input type="text" name="txt00442" size="45" value="" ><br>
</td>
</tr>
<tr>
<td>
<h2 id="qst00444">How much do you earn</h2>
<br>
<input type="radio" name="ans00444" value="921 ">Not to much<br>
<input type="radio" name="ans00444" value="922 ">ok<br>
<input type="radio" name="ans00444" value="923 ">Very Much<br>
<br>Income <input type="text" name="txt00444" size="45" value="" ><br>
</td>
</tr>
</table>

<INPUT TYPE="Button" VALUE="Submit" name="btnSubmit1" onClick="showResult(this.form);"

最佳答案

我还建议您在表单中使用 onSubmit 事件,但按钮中的 onClick 除外,因为您可能会遇到问题:用户可以在 input-text 中按 Enter 键 并且函数不会被处理。

这是代码(但您需要 jQuery),它会遍历 #form 中的每个输入并执行一些安全操作。

function showResult() {
var result = '';
$('#form input').each(function() {
var self = $(this),
type = self.attr('type'),
name = self.attr('name'),
value = self.val(),
checked = self.is(':checked');

if( value.length > 0 && type == 'text' || ( (type == 'radio' || type == 'checkbox') && checked) ) {
result += name + ', ';
result += value + ', ';
}
});
$('#form').html(result);
}

这是 fiddle DEMO .

关于javascript - 使用 javascript 返回表单的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23789269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com