Skip to content Skip to sidebar Skip to footer

Event Handling When Option Is Selected From Dropdown Menu

I have a form wherein I have to select an item from the drop down menu and display the selected value on the form. The values in the dropdown menu come from the database. Here is m

Solution 1:

Say you have the following html

<selectid="mySel"><optionvalue="a">a</option><optionvalue="b">b</option><optionvalue="c">c</option><optionvalue="d">d</option><optionvalue="e">e</option><optionvalue="f">f</option></select><labelfor="mySel"></label>

And you use jQuery, then you should be able to listen to selections by

// attach a ready listener to the document
$(document).ready(function(){ // ran when the document is fully loaded// retrieve the jQuery wrapped dom object identified by the selector '#mySel'var sel = $('#mySel');
  // assign a change listener to it
  sel.change(function(){ //inside the listener// retrieve the value of the object firing the event (referenced by this)var value = $(this).val();
    // print it in the logsconsole.log(value); // crashes in IE, if console not open// make the text of all label elements be the value 
    $('label').text(value);
  }); // close the change listener
}); // close the ready listener 

Working example: http://jsbin.com/edamuh/3/edit

Or you could also do it with basic javascript, by putting the following after the generated select & label:

<scripttype="text/javascript">var sel = document.getElementById('mySel');
  var lbl = document.getElementById('myLbl');
  sel.onchange = function(){
     lbl.innerHTML = this.options[this.selectedIndex].value;
  };
</script>

Working example here: http://jsbin.com/edamuh/7/edit

Note: The latter might not work equally in all browsers. Eg. Works in Firefox(Windows) but might not in others. Thus I'd suggest opting for using jQuery.

EDIT

In your case the markup should be something like (no onChange):

<aui:selectid="empName"name="empName" ><!-- options --></aui:select><labelid="myUniqueLabelId"></label><scripttype="text/javascript">
  $(document).ready(function(){ 
    // assigns a listener to 1 or more select elements that contains empName in their id
    $('select[id*=empName]').change(function(){
      // when the change event fires, we take the value of the selected element(s)var value = $(this).val();
      // take an element with the exact id of "myUniqueLabelId" and make its text be value
      $('#myUniqueLabelId').text(value);
      // take the reference to a radio inputvar radio = $('#radioId');
      // make it enabled
      radio.prop('checked', true);
    });
  });
</script>

Working example with radio buttons: http://jsbin.com/edamuh/12/edit

It is important to notice, that when the document loads the select must have been already rendered, otherwise the script won't work.

Post a Comment for "Event Handling When Option Is Selected From Dropdown Menu"