For your example (elements of whole_sell_qty
are sorted and values are evenly spaced out) you can get the index of the element in whole_sell_price
like this:
let qty = $(".quantity").val();
let index = Math.floor( (qty-1)/10 );
if(index < 0) {
index = 0;
} else if(index > whole_sell_qty.length-1) {
index = whole_sell_qty.length - 1;
}
If the elements in whole_sell_qty
were not spaced out evenly then you could make a function to figure out the correct price for the given quantity:
function setPrice() {
let qty = $(".quantity").val();
let length = whole_sell_qty.length;
for(let i=0; i < length; i++) {
if(qty > whole_sell_qty[i])
continue;
$("#total").text(qty * whole_sell_price[i]);
return;
}
$("#total").text(qty * whole_sell_price[length-1]);
}
Note: Both of these solutions assume your two arrays whole_sell_qty
and whole_sell_price
have matching elements in the same indexes. If that is not the case you could consider using an object to represent the different quantities and their respective prices.
Try it out:
Note: I added the min
attribute to the input[type="number"]
element so you can't click your way to a value less than 0. But you can still enter a negative number manually in the text field. For that I didn't provide a solution here but you can see how to deal with that here.
var whole_sell_qty = [10, 20, 30];
var whole_sell_price = [10, 9, 8];
$(".quantity").on('click', function () {
let qty = $(".quantity").val();
// this will get the correct price index for whole_sell_price based on qty
let index = Math.floor( (qty-1)/10 );
if(index < 0) {
index = 0;
} else if(index > whole_sell_qty.length-1) {
index = whole_sell_qty.length - 1;
}
$("#total").text(qty * whole_sell_price[index]);
});
table, th, td, tr {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<label>Product name : shoe</label><br>
<label>Product price : </label><input type="number" id="price" value="10" disabled><span>$</span><br>
<label>Qty : </label> <input type="number" name="quantity" min="0" class="quantity" value="0"/><br>
<label>Total : <span id="total">0</span></label>
<table>
<thead>
<tr>
<th>qty range</th>
<th>unit price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1-10</td>
<td>$ 10</td>
</tr>
<tr>
<td>11-20</td>
<td>$ 9</td>
</tr>
<tr>
<td>21-30</td>
<td>$ 8</td>
</tr>
</tbody>
</table>