[英]Add or remove the required attribute of an input field based on which option is selected
Basically I have a form in which a certain amount of input fields and selections (ingredient, quantity, unit of measure) are generated by a loop.基本上我有一个表单,其中一定数量的输入字段和选择(成分、数量、度量单位)由循环生成。 Now I would like to remove the attribute required from the quantity field only when the associated selected unit of measure is 'je'
现在我只想在关联的选定计量单位为“je”时从数量字段中删除所需的属性
<form method="post">
<?php
for ($n = 0; $n < $num; $n++) {
$data = $DB->query("SELECT * FROM ingredient"); ?>
<select name="list_ingr[]" required> <?php
while ($ingrs = $data->fetch()) { ?>
<option value="<?php echo $ingrs['id_ingr'] ?>"><?php echo $ingrs['name'] ?></option> - <?php
} ?>
</select>
Qt. <input type="number" name="list_quant[]" step="1" min="1" required>
<select name="measure[]">
<option value="none"></option>
<option value="gr">gr</option>
<option value="ml">ml</option>
<option value="j.e.">j.e.</option>
</select><br>
<?php
}
?>
<br>
<input type="submit" name="confirm" value="Confirm">
</form>
I have little to no experience when it comes to client side programming so I have no idea how to implement this;我在客户端编程方面几乎没有经验,所以我不知道如何实现它; I tried looking for a bunch of JS/jQuery codes but none seem to work:/
我试着寻找一堆 JS/jQuery 代码,但似乎都不起作用:/
Any help is appreciated!任何帮助表示赞赏!
Add a change event listener to the form to handle changing the required attribute of the input element beside the select element whose value changed.向表单添加更改事件侦听器,以处理更改值已更改的 select 元素旁边的 input 元素的 required 属性。
document.querySelector('form').addEventListener('change', e => {
if (e.target.matches('select')) {
e.target.previousElementSibling.required = e.target.value !== 'j.e.';
}
});
If I understand correctly, This is my working solution:如果我理解正确,这是我的工作解决方案:
I set id
for your Qt inputs.我为您的 Qt 输入设置了
id
。 And I removed one with jQuery.我用 jQuery 删除了一个。
<form method="post">
<?php
for ($n = 0; $n < $num; $n++) {
$data = $DB->query("SELECT * FROM ingredient"); ?>
<select name="list_ingr[]" required> <?php
while ($ingrs = $data->fetch()) { ?>
<option value="<?php echo $ingrs['id_ingr'] ?>"><?php echo $ingrs['name'] ?></option> - <?php
} ?>
</select>
Qt. <input id="qt_<?php echo $ingrs['id_ingr'] ?>" type="number" name="list_quant[]" step="1" min="1" required>
<select name="measure[]">
<option value="none"></option>
<option value="gr">gr</option>
<option value="ml">ml</option>
<option value="j.e.">j.e.</option>
</select><br>
<?php
}
?>
<br>
<input type="submit" name="confirm" value="Confirm">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#qt_2').remove(); //For example, to remove qt_2
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.