Javascript 迭代N个输入框,将每个框更新为其最大值
是否有一种方法可以为一组输入提供相同的ID,然后在选中复选框时对它们进行迭代,并将它们各自的值更新为MAX属性?例如,使用以下HTML:Javascript 迭代N个输入框,将每个框更新为其最大值,javascript,jquery,Javascript,Jquery,是否有一种方法可以为一组输入提供相同的ID,然后在选中复选框时对它们进行迭代,并将它们各自的值更新为MAX属性?例如,使用以下HTML: CHECK ALL: <input type="checkbox" id="someIDname"> <input type="number" max="80" id="anotherIDname"> <input type="number" max="90" id="anotherIDname"> <input ty
CHECK ALL: <input type="checkbox" id="someIDname">
<input type="number" max="80" id="anotherIDname">
<input type="number" max="90" id="anotherIDname">
<input type="number" max="99" id="anotherIDname">
<input type="number" max="65" id="unrelated">
<input type="number" max="75" id="unrelated">
全部选中:
。。。JS是这样的:
<script type="text/javascript">
$(document).ready(function() {
$('#someIDname').click(function(event) {
if(this.checked) {
$('#anotherIDname').each( function() {
var maxValue = $("#anotherIDname").attr("max");
document.getElementById("anotherIDname").value = maxValue;
});
}
});
});
</script>
$(文档).ready(函数(){
$('#someIDname')。单击(函数(事件){
如果(选中此项){
$('#anotherIDname')。每个(函数(){
var maxValue=$(“#另一个名称”).attr(“max”);
document.getElementById(“anotherIDname”).value=maxValue;
});
}
});
});
我想,当复选框被选中时,让它填充所有具有“anotherIDname”ID的所有MAX属性(然后我会有三个框,一个是80,一个是90,一个是99。另外两个是不同的ID,所以它不会去管它们。)
在这里使用JS/jQuery的初学者。。。上面的脚本在第一个框中工作,但不会用“anotherIDname”ID更新其他框。(我想可能是这样的)。每个“都会让它完成所有任务,一次一个,但是……我想这不是它的工作方式。(通常,我更喜欢PHP,如果是服务器端的话,这可能就是这样的工作方式。)任何想法都值得赞赏。添加了一个类名并使用querySelectorAll。这是否符合您的要求
$(文档).ready(函数(){
$('#someIDname')。单击(函数(事件){
如果(选中此项){
document.querySelectorAll('.max').forEach(a=>{
a、 值=a.max;
});
}
});
});
全部选中:
页面中的id
必须是唯一的。因此,您不能在多个位置使用相同的id。但是,您可以在多个位置使用相同的类
因此,您需要将id更改为class,例如:
<input type="number" max="80" class="maxinput" />
但是,我建议使用data-*
而不是简单的属性:
$('.maxinput').val(function() {
return $(this).attr('max')
});
<input type="number" data-max="80" class="maxinput" />
但我仍然感到惊讶,为什么你不只是一开始就设定他们的价值观
<input type="number" class="maxinput" value="80" />
几乎没有什么不对的地方
id
在页面中始终是唯一的。相同的class
被分配给具有相同特征的元素$(this).val()
来设置值$(文档).ready(函数(){
$('#someIDname')。单击(函数(事件){
如果(选中此项){
$('.anotherIDname')。每个(函数(){
var maxValue=$(this.attr(“max”);
console.log(maxValue);
$(此).val(最大值)
});
}
});
});
id
应该是唯一的;如果您想为多个元素指定相同的标识符,请使用class
。元素也可以有多个类,例如class=“foo bar”
太棒了,谢谢!所有伟大的答案/解决方案!我接受这个答案只是因为它对现有代码的修改最少。(我实际上是想用类而不是ID…只是一时糊涂。)我很感激你的回答。我真的希望它只适用于一个特定的ID(或者,实际上是一个类).但是,我也很高兴知道这种方法。谢谢!没问题,您希望它做什么,我们可以解决?不用担心,Bibberty。我已经有了它的功能。谢谢!:-)感谢您的回复!我将把这段代码改装成一个已经有普通max属性的旧脚本。因此,我将坚持使用这些属性。但是,感谢您的想法!:-)让我有点惊讶!如何将这些ID更改为类?
<input type="number" class="maxinput" value="80" />