Vignesh Gopalakrishnan
Vignesh Gopalakrishnan

Reputation: 1992

How to bring a dropdown (Chosen) with selected value on page loads.?

I am using Chosen plugin for Select box. I am replacing these both boxes on an ajax request. I want the check box to be pre filled when it comes. I tried something and it fails. I read the documentation of this and unable to accomplish. Here is what i have tried after reading the docs. Once ajax response came i am doing these things.

var city = $('#hdnCity').val();
//**Ajax Request Goes and the response is here**//
$('#searchParams').html(responseText);
var value = $("#favCities1 option:contains("+city+")").attr('selected', 'selected');
$("#chzn-select").val(value).trigger("liszt:updated");

I am unable to accomplish this. Helpers are appreciable. Thankyou in Advance!!!

Upvotes: 2

Views: 13644

Answers (3)

Michael Lawson
Michael Lawson

Reputation: 1

Chrome requires that you fire a different event now, http://harvesthq.github.io/chosen/. Without firing this event, the multiple select box wont get updated.

$('#chzn-select').trigger('chosen:updated')

You can see it in action with this jsfiddle, http://jsfiddle.net/LjtVa/

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388436

In the absence of any further information, I guess it is a problem with how you are handling the ajax reponse

Updation of searchParams should happen within the ajax success callback

var city = $('#hdnCity').val();

$.ajax({
    url: '',
    ...
}).done(function(responseText){
    //**Ajax Request Goes and the response is here**//
    $('#searchParams').html(responseText);
    var value = $("#favCities1 option:contains("+city+")").attr('selected', 'selected').val();
    $("#chzn-select").val(value).trigger("liszt:updated");
})

Upvotes: 3

Amy
Amy

Reputation: 7496

The problem is with the last line: $("#chzn-select").val(value).trigger("liszt:updated");

You will have to separate because $("#chzn-select").val(value) only returns jQuery object, but not the <select> element. Therefore, Chosen can't pick up the liszt:updated event since it's only listening to the <select>.

So you will have to do this:

$("#chzn-select").val(city);
$("#chzn-select").trigger("liszt:updated");

See working example: http://jsfiddle.net/amyamy86/qQCw8/

Upvotes: 4

Related Questions