hatemjapo
hatemjapo

Reputation: 840

Get the selected value on change in select tag

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

Answers (3)

Kushal Jayswal
Kushal Jayswal

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

Reinder Wit
Reinder Wit

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

Sterling Archer
Sterling Archer

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

Related Questions