Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loading options to select using jquery

Tags:

jquery

ajax

I am using JqueryAjax to load options in Select element.

<div>
    <select id="roleType" name="roleType" 
             onclick="loadRoleTypes();">
               <option value="s">Select</option>
     </select>
</div>

JqueryAjax

function loadRoleTypes()
{           
    $('#roleType').empty().append('<option>select</option>');        
    $.ajax({
            url: '/ci/ajaxcall/loadRoles.php',
            dataType: 'json',
            type: 'POST',
            data: {"userCode": userCode},
            success: function(response) {
              var array = response.value;
              if (array != '')
              {
                for (i in array) {                        
                 $("#roleType").append("<option>"+array[i].ROLE_TYPE+"</option>");
               }

              }

            },
            error: function(x, e) {

            }

        });
}

here i am getting option values as drop down when i click select element.but i cant select a particular option.how to solve this

like image 204
shahanas sulthan Avatar asked Jan 12 '15 05:01

shahanas sulthan


People also ask

How to load select option in jQuery?

To populate select list with jQuery, use for loop along with append() and append the options to the already created select.

How to create select element in jQuery?

var select = $("<select></select>"); var opt = $("<option></option"); opt. val("1"); opt. html("Option 1"); select.

How to add dropdown in jQuery?

Add options to a drop-down list using jQuery. JavaScript Code: var myOptions = { val1 : 'Blue', val2 : 'Orange' }; var mySelect = $('#myColors'); $. each(myOptions, function(val, text) { mySelect.


1 Answers

The problem you can't select an option is that every time you click the selectbox(Including the option set) the function called loadRoleTypes() is being called.You can try checking the number of options in your selectbox.Or you could check on any other conditions.

function loadRoleTypes()
{           
if ($('#roleType').find("option").size() == 1) {  //Check condition here
    $('#roleType').empty().append('<option>select</option>');        
    $.ajax({
            url: '/ci/ajaxcall/loadRoles.php',
            dataType: 'json',
            type: 'POST',
            data: {"userCode": userCode},
            success: function(response) {
              var array = response.value;
              if (array != '')
              {
                for (i in array) {                        
                 $("#roleType").append("<option>"+array[i].ROLE_TYPE+"</option>");
               }

              }

            },
            error: function(x, e) {

            }

        });
}
}
like image 127
Outlooker Avatar answered Oct 28 '22 20:10

Outlooker