Samantha J T Star
Samantha J T Star

Reputation: 32778

Can I use jQuery to check if a list item is present or not?

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

Answers (4)

Blender
Blender

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

moey
moey

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

nnnnnn
nnnnnn

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

bevacqua
bevacqua

Reputation: 48476

sure, you just ask:

if(!!$("#AccountID option[value=0000]").length)) {
    // code
}

Upvotes: 1

Related Questions