1

I am trying to get the selected value from an event.

I don't know which method to get this value. Any suggestions ?

//update item quantity
cartList.on('change', 'select', function (event) {
   var row = $(event.target).parents('.product');
   updateItemQuantity(row.data('row_id'), QUANTITY_IS_SELECTED_VALUE);
   quickUpdateCart();
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ahmad Elkenany
  • 575
  • 5
  • 23

5 Answers5

4

event.target is the element that triggered the event. You can read its value using jQuery by doing $(event.target).val(). You can also use the this keyword, which holds the same element ($(this).val()).

Instead of using jQuery, you could also retrieve the value through the vanilla DOM method of this.options[this.selectedIndex].text.

Hydrothermal
  • 4,851
  • 7
  • 26
  • 45
  • `event.target.value` and `this.value` avoids a jQuery instantiation and a `val()` method invocation. If you already have the variable, direct property access can be more performant. – Taplar Dec 28 '18 at 23:34
  • @Taplar True, and I would normally use vanilla `.value` instead, but it doesn't work everywhere for selects - in older browsers you would have to use the selectedIndex workaround. I'll update my answer to mention it however. – Hydrothermal Dec 28 '18 at 23:36
2

try this

event.target.options[event.target.options.selectedIndex].text
YouBee
  • 1,981
  • 1
  • 15
  • 16
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/25649492) – veben Mar 20 '20 at 10:33
  • I was looking for the same and didn't found here the solution without jquery. so thought to share how i got it without jquery. – YouBee Mar 20 '20 at 11:32
0

The .val() method in jQuery returns or sets the value attribute of the selected elements.This method returns the value of the value attribute of the FIRST matched element.

 $(selector).off('change').on('change', function () {
    var selectedValue = $(this).val();
    alert(selectedValue);
    //Your other logic here
  });
Sushil
  • 1,111
  • 1
  • 10
  • 23
0

With pure javascript you can find selected option and all related information:

console.log(event.target.selectedOptions[0].value);
console.log(event.target.selectedOptions[0].label);
Pavlo Hryza
  • 627
  • 1
  • 11
  • 18
0

you could target the Select by class, then add an onChange handler, and get the value

var selectItem = document.querySelector("select.cartList");
selectItem.addEventListener("change", function(event) {
    var newChangedValue = event.target.value;
    console.log(newChangedValue);
});