Store variable based on if statement using jQuery selectors

I am new to both Javascript and the jQuery framework.

Basically, I'm trying to say that if the quantity is more than 1, then do not charge. However, if it is 1, charge a fee. But I do not know how to store variables when using jQuery.

My thought was ... (is that right?)

var qty = $(".qty_item"); var price = $(".price_item"); var fee = ""; if (qyt==1) { var fee = 250; } else { var fee = 0; } 

I noticed that in some jQuery plugins they declare such variables ...

 qty: $(".qty_item"), price: $(".price_item") 

Any help is greatly appreciated.

+4
source share
2 answers

To get values ​​from elements, you need to use the $.val() method (suppose this is an input element).

 var price = $(".element").val(); 

Thus, the price will be 5 when using the following HTML:

 <input type="text" value="5" class="element" /> 

You can simplify your data collection logic using the ternary operator as well:

 var fee = ($(".element").val() > 1) ? 250 : 0 ; 

So, if the value of our input (having the "class" element) is more than 1, the board will be 250. Otherwise, the board will be the value of our input (with the identifier "price").

+6
source

JQuery is a javascript library, you can create variables like in javascript:

 var qty = $('.element').val(); var price = $('.element').val(); var fee = ""; if (qyt >= 1) { var fee = 250; } else { var fee = $('#price').val(); } 

Please note that I changed == to >= because you want to charge if the quantity is greater than or equal to 1.

0
source

Source: https://habr.com/ru/post/1302260/


All Articles