简体   繁体   中英

Store variable based on if statement with jQuery selectors

I'm new to both Javascript and the framework jQuery.

Basically I'm trying to say that if the quantity is greater than 1 then don't charge a fee. However if it is equal to 1 charge a fee. But I don't know how to store the variables while using jQuery.

My thought was... (is this correct?)

var qty = $(".qty_item");
var price = $(".price_item");
var fee = "";

if (qyt==1) {
    var fee = 250;
}

else {
    var fee = 0;
}

I've noticed though that in some jQuery plugins they declare variables like so...

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

Any help is much appreciated.

To get values from elements, you need to use the $.val() method (assuming it's an input element).

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

So price would be 5 assuming the following HTML:

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

You could simplify your fee-finding logic by using a ternary operator too:

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

So if the value of our input (having the classname 'element') is greater than 1, fee will be 250. Else, fee will be the value of our input (having the id 'price').

Jquery is library of javascript, you can create variables like you do in javascript:

var qty = $('.element').val();
var price = $('.element').val();
var fee = "";

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

Notice that i have changed the == to >= because you want to charge if quantity is greater than or equal to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM