Reputation: 840
I have to make a shop. Its almost done but I am stuck to let the customer change the amount in the cart of the products and to let the price change dynamically.
I made a select-tag with 10 options, where the chosen amount is selected. I want the user to be able to click the select, choose an other amount and to calculate the price in live preview. But I cant figure out how to select all the select-tags and put a click event on every option.
I tried like this:
<select class="st" name="">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
and my jquery:
var st = $('.st');
st.change(function(){
var str = "";
$( ".st option:selected").each(function() {
str = $(this).text();
console.log(str);
});
})
but with that I am getting the selected one from every select-tag. I want it to just console me the selected one in the select-tag where I have clicked. How can I do that?
Upvotes: 1
Views: 2159
Reputation: 933
In case of getting TEXT instead of VALUE, below code would help:
$('select').on('change', function(e){
console.log($(e.currentTarget).find(":selected").text())
})
Upvotes: 0
Reputation: 6615
You can get the value for the current <select>
directly, by doing this:
var st = $('.st');
st.change(function(){
// $(this) references the current <select>
console.log($(this).val());
})
Upvotes: 4
Reputation: 22395
Your loop re-grabs every .st
, instead of using this
so that it targets the clicked object.
st.change(function(){
var str = "";
$(this).each(function() {
if ($(this).is(":selected")) { //add if check to see if option is selected
str = $(this).text();
console.log(str);
}
});
})
Upvotes: 0