discerninc
discerninc

Reputation: 1

Change text field of form based on number of check boxes checked

Full disclosure: I'm a java/jquery newbie, but this seems like a problem with an easy solution. I've looked around and couldn't find an analogous situation, but if there's already a post about this let me know.

I have created a form with a checklist of products and a discount code box. How I'd like things to work when you click submit:

  1. If you click any 3 or less, you get no discount
  2. If you click any 4, applies "Discount 1"
  3. If you click any 5, applies "Discount 2"
  4. If you click any 6, applies "Discount 3"

I've gotten it to work with an alert box, but it seems like I need a different bit of code to change the value of the text box to the discount?

Thanks for your help!

Here's the stripped down code I have so far:

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.

Upvotes: 0

Views: 338

Answers (2)

Matteo B.
Matteo B.

Reputation: 4074

jQuery( '#form1' ).submit( function(){
    jQuery( '#f_coupon' ).val( 'Discount ' + jQuery( '.styled:checked' ).length );
} );

Btw, Java is not JavaScript, every <form> needs a </form> and input-tags can't do anything with content data, so you should close them like <input />!

Upvotes: 0

mreq
mreq

Reputation: 6542

Store the inputs in a variable, ie. var inputs = $('input[type="checkbox"]); then you can check the number of checked inputs by inputs.filter(':checked').length and do stuff based on that

for instance

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); 
  }
}); 

Upvotes: 1

Related Questions