2011-12-21 145 views
0

完全披露:我是一个java/jquery新手,但这个好像就像一个简单的解决方案的问题。我环顾四周,找不到类似的情况,但如果已经有一篇关于此的帖子,请让我知道。更改基于复选框数量的表单文本框

我已经创建了产品清单和折扣代码框。我怎样想的东西的工作,当你点击提交:

  1. 如果你点击任何3个或更少,你如果点击任何4获得不打折
  2. ,适用“折扣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。

+0

我可能会在服务器端处理这一点,以防止客户端创建虚假折扣;无视我会说看看[jQuery的表单方法](http://api.jquery.com/category/forms/),特别是'$(form).submit()'。你可以使用'$(textInput).val(newValue)'来设置字段。 – sczizzo 2011-12-21 21:59:00

+0

我修改了代码以获得所需的(请求的)效果:http://jsfiddle.net/JkjUc/只能在用户界面上使用此代码进行快速响应,而不是*作为唯一的验证机制。 – 2011-12-21 22:01:20

回答

1

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

顺便说一句,Java is not JavaScript,每<形式>需要< /形式>和输入 - 标签对内容数据无能为力,因此您应该关闭它们,如< input/>!

相关问题