Search code examples
javascriptjqueryhtmlonloadonblur

Executing Javascript function with first option of select element as soon as select element populates


I have a following select element:

<select id="options" title="prd_name" name="options">
  <option id='option1' value='Prdt1'>Product1</option>
  <option id='option2' value='Prdt2'>Product2</option>
  <option id='option3' value='Prdt3'>Product3</option>
  <option id='option4' value='Prdt4'>Product4</option>
</select>

I populate this select element using JQuery with some data from the database. I want to run a few Javascript functions as soon as this select element is populated with a options and I want those functions to run using the first option value. I am currently only able to run functions by adding onblur and onchange attributes in the select tag.

The problem arises, when I have only one option element, i.e. one product. By this I am unable to onblur or onchange and I used onload in the select element, which is not working aswell.

Anyone has any idea what am I missing or doing wrong?


Solution

  • You might want to consider calling the methods immediately after you populate the options , rather than triggering onblur / onchange.

    Here is the code :

        $(document).ready(function(){
          //Consider this as success callback
          populateOptions();
    
        });
    
        function populateOptions(){
          var options = [1,2,3];
          var optionsHtml = "";
          for(var idx = 0; idx < options.length; idx++){
            var val = options[idx];
            optionsHtml += "<option id=option"+val+" value='Prdt"+val+"'>Product"+val+"</option>"
          }
    
          $("#firstDropdown").html(optionsHtml);
    
          executeMethods();
        }
    
        function executeMethods(){
          // find the first element
          var firstValue = $("#firstDropdown").find('option:eq(0)').val();
          if(firstValue === undefined){
            return;
          }
    
          console.log("Call Method with first Value : " + firstValue);
        }
    

    jsbin : Code Sample