我想获取表单中字段的名称,值和类型。我正在使用以下代码帮助我获取名称和值,但是对于复选框和单选按钮,我也总是键入=“text”。我想得到确切的字段类型,无论是复选框,广播还是文本。 这是代码
<form action="">
<h1> Try Form</h1>
First name: <input type="text" name="FirstName" value="khan"><br>
Last name: <input type="text" name="LastName" value="wazir"><br>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked="checked"> I have a car<br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
<button>Serialize form values</button>
<div id="results"></div>
这是脚本
<script>
$(document).ready(function(){
$("button").click(function(){
var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " :" + $( "input" ).attr( "type" ) + " ");
});
});
});
</script>
答案 0 :(得分:2)
变化
$( "input" ).attr( "type" )
到
$( "input[name='" + field.name + "']" ).attr( "type" )
您必须选择指定输入才能获得类型正确的
答案 1 :(得分:2)
您可以遍历input
元素并获取prop('type')
以获取输入类型:
prop()
是一个JQuery函数,它为您提供元素的属性:
$(document).ready(function() {
$("button").click(function() {
var x = $("form").serializeArray();
$('input').each(function() {
$("#results").append($(this).val() + " :" + $(this).prop('type') + "<br />");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<h1> Try Form</h1>
First name: <input type="text" name="FirstName" value="khan"><br> Last name: <input type="text" name="LastName" value="wazir"><br>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked="checked"> I have a car<br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
<button>Serialize form values</button>
<div id="results"></div>
答案 2 :(得分:1)
检查
$(document).ready(function(){
$("button").click(function(){
var x = $("form").find("input");
$.each(x, function(i, field){
$("#results").append(field.name + ":" + field.value + " :" + field.type);
});
});
});
演示:fiddle