Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a Select change event if changing between two options with the same value?

<select>
   <option value="">Select</option>
   <option value="10000">Minimum Coverage</option>
   <option value="25000">Average Coverage</option>
   <option value="">Other</option>
</select>

I have to have both the "Select" and "Other" have empty values because the validation rules on the field do not allow for anything other than an empty string or a numeric value.

Bottom line, is I need to be able to detect when the user is on "Select" and clicks "Other". Is it possible?

EDIT: onChange does not seem to fire.

like image 774
antonpug Avatar asked Apr 01 '14 20:04

antonpug


2 Answers

You can check the selectedIndex property. If you want something to happend each time the item changes, use the onchange event binding.

document.getElementsByTagName('select')[0].onchange = function() {
  var index = this.selectedIndex;
  var inputText = this.children[index].innerHTML.trim();
  console.log(inputText);
}

FIDDLE

like image 173
sabof Avatar answered Oct 21 '22 14:10

sabof


The change event most certainly fires, even if the changed option has the same value:

jsfiddle.net/kyw2E

In the change event handler, you can examine the this.selectedIndex property to determine which <option> is selected. You can then examine the text property of the selected option, if that's helpful:

coverageSelector.onchange = function (e) {
    var selectedOption = this[this.selectedIndex];
    var selectedText = selectedOption.text;
}
like image 32
gilly3 Avatar answered Oct 21 '22 13:10

gilly3