Reputation: 100
I've created a scripts that makes requests to the server and gets a json response with some data that is used to create dropdown dinamically, in some cases the server returns one single value and, of course, the dropdown generated has only one option (as follow)
<div id="wrap">
<select class="click_me">
<option value="1">foo</option> --> this value comes from a json response.
</select>
</div>
This is my jQuery script (I think that it is self explanatory)
$('#wrap').on('change', 'select', function() {
var container = $('#wrap');
var self = $(this);
self.nextAll().remove();
$.ajax({
type: 'GET',
url: 'server/stuff?id=' + self.val(),
dataType: 'json',
success: function(data) {
if (data) {
var options = self.clone().empty().appendTo(container); //clone current dropdown.
$.each(data, function(key, value) {
$.each(value, function(key, value) {
options.append($("<option />").val(key).text(value)); //fill cloned element with new data
});
});
} else {
console.log('Nothing more');
}
}
});
});
If user gets a dropdown with one option, the script above doesn't work. I think that event onchange is not triggered at all, I tried onclick event but it fires when user just want to open the dropdown.
Please, any advice is appreciate.
Thanks
Upvotes: 0
Views: 4332
Reputation: 11475
You can have a workaround for this like the following way. When clicking on the select list and if it has only one option we can call the change event by our self. So try
$('#wrap').on('change', 'select', function() {
//your stuff
}).click(function(){
if($('#wrap select option').length == 1) {
$('#wrap select').change();
}
});
Working fiddle is here. Test it by adding some more options to dropdown to ensure that, it is also working for more than one options.
Upvotes: 4
Reputation: 4288
Try,
$("dropdownId").blur(function(){
// here goes your code
}
Upvotes: 0
Reputation: 16468
after your json response
make a check like this:
if($('#wrap .click_me option').length == 1) {
$('#wrap .click_me').change();
}
Upvotes: 0