treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery "this" Help

  • The code below is for a add to cart page, now the code works fine when one item is added to the cart, it changes the input value based on the "if"condition. When a second product gets added though since it is targeting only a class ".cartQty" it not only changes the second input value but it also changes the first one. I need to figure out how to use "this" so each product input is independent.

    Any help would be great!

    Here is my Code:

    			
    <script type="text/javascript">
    if("##iumr##" == "TH"){
    $(".cartQty").val("##IVULP##"*1000);
    } else if("##iumr##" == "EA"){
    $(".cartQty").val("##IVULP##");
    }
    </script>
    <input class="cartQty" type="text" size="8" value="##CLOSQTsell##" name="Qty##BlockCount##_##Zone##">


    Would something like this work?
    	
    <script type="text/javascript">
    if("##iumr##" == "TH"){
    $(this).val("##IVULP##"*1000);
    } else if("##iumr##" == "EA"){
    $(this).val("##IVULP##");
    }
    </script>
    <input class="cartQty" type="text" size="8" value="##CLOSQTsell##" name="Qty##BlockCount##_##Zone##">
  • No, your second solution won't work. In that case $(this) doesn't refer to anything.

    You'll need to use some sort of .each() loop or even better create your own function that fires each time you click add to cart.
  • TheDoc is there a way to target class ".cartQty" and "this"? Your other suggestions I think are over my head.
    Thanks!
  • I think I'd need to see how the whole page is working to advise otherwise.