这是我用于 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>
最佳答案
您可以修改 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>
希望这对您有所帮助。
关于javascript - POST 动态创建的必填输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882005/