Reputation: 32778
I have the following select list:
<select id="AccountID">
<option value='0000'>Select Account</option>
<option value='002M'>test1</option>
<option value='002N'>test2</option>
<option value='002P'>test3</option>
</select>
After a user makes a new selection I need to execute the following which will replace the above list with one that does not contain the choice "Select Account"
function SelectAccounts() {
$.ajax({
url: "/Administration/Accounts/GetOptions",
data: { ds: $('#DataSourceID').val(),
ac: '0000'
},
success: function (data) {
$('#AccountID').html(data);
}
});
}
Is there a way that I can change:
$('#AccountID').change(SelectAccounts);
so that it only calls SelectAccounts IF there is an option "0000" in the select list?
Upvotes: 0
Views: 82
Reputation: 298146
Sure, just use an anonymous function:
$('#AccountID').change(function() {
if ($(this).find('option[value="0000"]').length > 0) {
SelectAccounts();
} else {
// Option not present
}
);
Or a selector:
$(document).on('change', '#AccountID:has(option[value="0000"])', SelectAccounts);
// Use a more specific selector for the parent of `#AccountID`.
Upvotes: 3
Reputation: 10887
You can try:
$('#AccountID').change(function() {
if ($(this).find('option[value="0000"]').length > 0) {
SelectAccounts();
}
});
Just curious, do you really need to alter the options using AJAX? If they are pretty simple, maybe prepare them in advance?
Upvotes: 1
Reputation: 150020
In a general sense you can test if the select element has a particular option as follows:
if ($("#AccountID option[value='0000']").length > 0) {
// option exists
}
However, you might be better off just removing the change handler:
// within the success handler of your ajax call:
$("#AccountID").html(data).off("change");
Or, if using an older version of jQuery, use .unbind("change")
.
Upvotes: 2
Reputation: 48476
sure, you just ask:
if(!!$("#AccountID option[value=0000]").length)) {
// code
}
Upvotes: 1