繁体   English   中英

根据选中的复选框数更改表单的文本字段

[英]Change text field of form based on number of check boxes checked

完全公开:我是Java / jquery新手,但这似乎是一个简单解决方案的问题。 我环顾四周,找不到类似的情况,但是如果已经有关于此的帖子,请告诉我。

我创建了一个带有产品清单和折扣代码框的表单。 当您单击“提交”时,我希望事情如何进行:

  1. 如果您单击3或更少,则没有折扣
  2. 如果单击任意4,则应用“折扣1”
  3. 如果您单击任意5,则应用“折扣2”
  4. 如果您单击任意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()" />

-j

将输入存储在变量中。 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( function(){
    jQuery( '#f_coupon' ).val( 'Discount ' + jQuery( '.styled:checked' ).length );
} );

顺便说一句, Java不是JavaScript ,每个<form>都需要一个</ form>,并且input-tags不能对内容数据做任何事情,因此您应该像<input />一样关闭它们!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM