这是我用来POST数据的代码,它可以工作,我添加了一个必需参数后出现问题,现在代码强制填充所有字段,即使它们不可见。我想问题出现在jQuery的hide()
函数中,因为它只隐藏了字段。应该进行哪些更改才能使此代码仅需要可见字段?
$('#product_type').change(refresh_inputs);
refresh_inputs();
function refresh_inputs() {
var name = $('#product_type').attr('name');
var val = $('#product_type').val();
$('#'+name+' div').hide();
$('#'+val).show();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="add.php" method="post" name="form1" >
<table width="25%" border="0">
<tr>
<td>SKU</td>
<td><input type="text" name="sku" required></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="price" required></td>
</tr>
<tr>
<td>Select product type</td>
<td>
<select id="product_type" name="products" required>
<option style="display: none;" selected>Select product type</option>
<option value="book">Book</option>
<option value="dvd">Dvd</option>
<option value="furniture">Furniture</option>
</select>
</td>
</tr>
<tr>
<td>
<div id="products">
<div id="book">
<input type="text" name="weight" placeholder="Weight" required/>
</div>
<div id="dvd">
<input type="text" name="capacity" placeholder="Capacity" required/>
</div>
<div id="furniture">
<input type="text" name="height" placeholder="Height" required/>
<input type="text" name="width" placeholder="Width" required/>
<input type="text" name="length" placeholder="Length" required/>
</div>
</div>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
&#13;
答案 0 :(得分:1)
<script type="text/javascript">
$('#product_type').change(refresh_inputs);
refresh_inputs();
function refresh_inputs() {
var name = $('#product_type').attr('name');
var val = $('#product_type').val();
$('#'+name+' div').attr("required", false); // add this line only
$('#'+name+' div').hide();
$('#'+val).show();
}
</script>
它会隐藏元素,而不会根据需要删除自己设置的属性。
答案 1 :(得分:1)
您可以修改refresh_inputs函数,如下所示:
<script type="text/javascript">
$('#product_type').change(refresh_inputs);
refresh_inputs();
function refresh_inputs() {
var name = $('#product_type').attr('name');
var val = $('#product_type').val();
$('#'+name+' div').hide();
$('#'+name+' div').find('input').removeAttr('required');
$('#'+val).show();
$('#'+val).find('input').attr('required', 'required');
}
</script>
希望这有帮助。