-1

I want to trigger function when I press an option in the select element. I thought that .click() would be preferable but the thing is, it is executing too fast, so much that it is not allowing me to choose the option from the select. Instead, it's taking the first option's value when I open the drop down list. Could someone suggest me a method of handling this?

HTML:

<select name="year2" id="year1" style="width:200px;">
    <option value="none"> none </option>
    <option value="2015"> 2015 </option>
    <option value="2014"> 2014 </option>
    <option value="2013"> 2013 </option>
</select>

JavaScript:

$( "#year1" ).click(function() {
   var year=$("#year1").val();
   var stream=$("#stream").val();
   $.ajax({
      url:"checkonserver.jsp",
PhilTrep
  • 1,521
  • 1
  • 10
  • 23
Vasu
  • 265
  • 1
  • 10
  • 18

3 Answers3

5

Question to you: do you need to use the selected option's value in your function?

If:

Yes: -> Use .change()
No: -> Use .click()

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • yes, your absolutely correct. but .change() is not working when i press select the same item at next time. why ? – Vasu Oct 16 '13 at 19:17
  • @user2773010, change fires on change.You need the values for your ajax call. – Sergio Oct 16 '13 at 19:19
  • i mean to say, when i press 2012 at fist time , then its calling the value, but its not calling the function when i select the same value 2012 second time with out refreshing the browser. why it is, how can i fix this ? – Vasu Oct 16 '13 at 19:19
  • @user2773010, you mean you want to call your function on click also? in case the value is already the right one? – Sergio Oct 16 '13 at 19:21
  • @user2773010, I see no good solution. The best would be this event: http://stackoverflow.com/questions/6207929/is-there-a-dom-event-that-fires-when-an-html-select-element-is-closed – Sergio Oct 16 '13 at 19:29
0

As per the documentation:

"The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released"

"The change event is sent to an element when its value changes."

As mentioned already, pick up the event according to the trigger and element you are working with.

HTH.

Portu
  • 542
  • 2
  • 4
  • 16
0

Use change

$('#year1').on('change',function()
 {
    var year=$('#year1').val();
  }
);

if you want the value again in case you select the same year say "2012"(or any year) use this

$('#year1').on('change',function()
 {
    var year=$('#year1').val();
    $('#year1').val(" ")
  }
);

this will make the value of #year1 null

Udit Bhardwaj
  • 1,761
  • 1
  • 19
  • 29