Javascript 根据选中的复选框数更改表单的文本字段
充分披露:我是java/jquery新手,但这似乎是一个简单解决方案的问题。我环顾四周,找不到类似的情况,但如果已经有关于这方面的帖子,请让我知道 我创建了一个表单,其中包含产品清单和折扣代码框。当您单击“提交”时,我希望事情如何进行:Javascript 根据选中的复选框数更改表单的文本字段,javascript,jquery,forms,Javascript,Jquery,Forms,充分披露:我是java/jquery新手,但这似乎是一个简单解决方案的问题。我环顾四周,找不到类似的情况,但如果已经有关于这方面的帖子,请让我知道 我创建了一个表单,其中包含产品清单和折扣代码框。当您单击“提交”时,我希望事情如何进行: 如果您单击任意3个或更少,则不会获得折扣 如果单击任意4,则应用“折扣1” 如果单击任意5,则应用“折扣2” 如果单击任意6,则应用“折扣3” 我已经让它与一个警报框一起工作,但似乎我需要一个不同的代码来将文本框的值更改为折扣 谢谢你的帮助 以下是我到目前为止的
function check(){
count = 0;
for(x=0; x<document.signup.getElementsByClassName("styled").length; x++){
if(document.signup.getElementsByClassName("styled")[x].checked==true){
count++
}
}
if(count<3){
alert("No Discount");
}
else if(count==3){
alert("Discount1");
}
else if(count==4){
alert("Discount2");
}
else if(count==5){
alert("Discount3");
}
else if(count==6){
alert("Discount4");
}
}
<form name="signup" id="form1" method="post" action="">
<input type="checkbox" id="product1" name="product_id[]" value="1" class="styled">
<input type="checkbox" id="product2" name="product_id[] "value="3" class="styled">
<input type="checkbox" id="product3" name="product_id[]" value="2" class="styled">
<input type="checkbox" id="product4" name="product_id[]" value="4" class="styled">
<input type="checkbox" id="product5" name="product_id[]" value="44" class="styled">
<input type="checkbox" id="product6" name="product_id[]" value="45" class="styled">
<input type="text" name="coupon" id="f_coupon" value="" size="15" />
<input type="button" name="Button" value="Click Me" onclick="check()" />
函数检查(){
计数=0;
对于(x=0;x将输入存储在一个变量中,即var inputs=$('input[type=“checkbox”]);
则可以通过inputs.filter(':checked').length检查选中输入的数量,并基于此执行操作
比如说
var inputs = $('input[type="checkbox"]');
var textField = $('input#f_coupon');
$('form').submit(function(){
var count = inputs.filter(':checked').length;
if (count > 3) {
// do stuff
// ie.
textField.val(count);
}
});
jQuery('#form1').submit(函数(){
jQuery('f#u优惠券').val('Discount'+jQuery('styled:checked').length);
} );
顺便说一句,every needs a和input标记不能对内容数据做任何处理,因此您应该像关闭它们一样关闭它们!我可能会在服务器端处理此操作,以防止客户端创建虚假折扣;忽略这一点,我会说查看,特别是$(form).submit()
。您可以使用类似$(textInput).val的内容(newValue)
设置字段。我修改了您的代码以获得所需的(请求的)效果:仅使用此代码在用户界面上快速响应,而不是作为唯一的验证机制。