Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

I have the following markup:

<select onchange="jsFunction()">     <option value="1">1</option>     <option value="2">2</option>     <option value="3">3</option> </select> 

When a user pulls down the combobox and selects the same option that was previously selected (or doesn't change the selection at all), JavaScript doesn't regard it as an onchange event. So, the jsFunction() is not called. But I want the jsFunction() called even in this case. How can I achieve this?

like image 660
Dilip Raj Baral Avatar asked Aug 09 '12 05:08

Dilip Raj Baral


People also ask

Which event occurs when the value of element is changed?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

How do you use change event?

Definition and UsageThe onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

What is change event Dom?

The HTML DOM onchange event occurs when the value of an element has been changed. It also works with radio buttons and checkboxes when the checked state has been changed.


2 Answers

I'd do it like this:

<select onchange="jsFunction()">   <option value="" disabled selected style="display:none;">Label</option>   <option value="1">1</option>   <option value="2">2</option>   <option value="3">3</option> </select> 

If you want you could have the same label as the first option, which in this case is 1. Even better: put a label in there for the choices in the box.

like image 155
simme Avatar answered Sep 25 '22 03:09

simme


You have to add empty option to solve it,

I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.

<select onChange="jsFunction()" id="selectOpt">     <option value="1" onclick="jsFunction()">1</option>     <option value="2">2</option>     <option value="3">3</option> </select>  function jsFunction(){   var myselect = document.getElementById("selectOpt");   alert(myselect.options[myselect.selectedIndex].value); } 
like image 43
gaurang171 Avatar answered Sep 24 '22 03:09

gaurang171