2011-12-21 47 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/>!

相關問題