Paramjeet
Paramjeet

Reputation: 316

Using Jquery chosen in jquery ajax

I am using jquery chosen and calling ajax on change drop down but records are not displaying. This code which I am using after changing drop down.

    $.ajax({
        type: "POST",
        url: "MY URL",
        data: {
            sno: $(this).val()
        },

        success: function (resp) {
            var resp = jQuery.parseJSON(resp);
            if (resp.length == 0) {
                $("#site").html('<option value="0" selected>Select Site</option>');

            } else {
                $.each(resp, function (i, item) {
                    $('#site').append($('<option>', {
                        value: item.siteNameID + '-' + item.siteName,
                        text: item.siteName
                    }));
                });
            }
        },
        error: function (resp) {

            console.log('error');
        }
    });

One thing I have noticed jquery chosen applying on my select box but data which I am fetching from server side is not adding in that select box

Upvotes: 0

Views: 1867

Answers (2)

Nate32
Nate32

Reputation: 251

You will need to call the chosen update trigger after you add items to your select list dynamically in order for them to show up. Use the following line after you have appended items and they should be displayed in your list.

$('#site').trigger("chosen:updated");

Upvotes: 1

netto
netto

Reputation: 135

I think my code is not the answer for your question, but this mimics adding options to select... just click the add button...

<!DOCTYPE html>
<html>
<head>
	<title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="add()">Add</button>
<select id="select"></select>
<script>
   var json = [{title:"lorem",value:1},
               {title:"john doe",value:2},
               {title:"foo",value:3},
                ];
   function add(){
   		$("#select").empty();
   		for(var x = 0; x<json.length; x++){
   			var option = '<option value="'+json[x].value+'"> '+json[x].value+'-'+json[x].title+'</option>';
   			$("#select").append($(option));
		}
   }
</script>
</body>
</html>

Upvotes: 1

Related Questions