Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trigger change() even on selecting the same value for select field

I've options like this

<select name="hall" id="hall">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
</select>

I'm using jquery function to submit my form

 $('#hall').change(

But when the same value is selected again, I want it to to be triggered. How can i do this?

like image 266
Anil Kumar Avatar asked Aug 11 '15 06:08

Anil Kumar


People also ask

What is the difference between change and Onchange?

Definition and Usage 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, after the content has been changed.

How is Onchange triggered?

The 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. Tip: This event is similar to the oninput event.

What is trigger change in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

Does jQuery Val trigger change event?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.


3 Answers

Do it on click

$('#hall').on('click',function(){

   if(this.selectedIndex == -1) {
      alert('select one answer');
   }
   else{
      // do whatever you want!
   }        
});
like image 83
PsyLogic Avatar answered Oct 20 '22 00:10

PsyLogic


Try this:

var prevVal;
$('#hall').on('focus', function (){
     prevVal=$( "#hall:selected" ).text();
});

$('#hall').on('change', function (){
     if(prevVal=$( "#hall:selected" ).text()){
          alert('same val selected');
     }
});
like image 44
dpanshu Avatar answered Oct 20 '22 00:10

dpanshu


DEMO

You can do as below:

$("#hall option").on('click',function(){
    $("#hall").trigger('change');
});
$("#hall").on('change',function(){
   alert('changed'); 
});

Note : As per comment here this works well in FF but not in chrome. You can use it at your own risk

like image 41
Guruprasad J Rao Avatar answered Oct 20 '22 00:10

Guruprasad J Rao