Batman
Batman

Reputation: 6373

Checking if a selected element contains an attribute

I have two types of lists appended to my select element.

a list of users: <option value="domain\davidr" userid="108">David</option>

a list of groups: <option value="Test Group" groupid="10">Test Group</option>

This is my select html:

    <select id="groupOwner">
      <option value="default" disabled>Select a Group Owner</option>
      <optgroup label="---Users---"></optgroup>
    </select>

I need to set a variable as either "user" or "group" based on the selected list item type.

I tried doing this: var ownerType = $("#groupOwner[groupid]") ? "group" : "user"; but it keeps returning "group"

Upvotes: 1

Views: 134

Answers (3)

Maen
Maen

Reputation: 10698

Your selector will always be evaluated to true: if there's no match for your selector, jQuery returns an empty array, which will be evaluated to true in your ternary test.

You should test the length of the array returned by jQuery to determine whether your element is on the DOM or not.

Example :

// Will print No, foo isn't an HTML element present on the DOM
$('foo').length ? console.log('Yes') : console.log('No');

// Will print Yes, $('foo') = []
$('foo') ? console.log('Yes') : console.log('No');

Upvotes: 0

learner
learner

Reputation: 86

$("selector").get(0).hasAttributes("attributes");

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337733

Firstly, groupid and userid are not valid attributes for the option element and will render your page invalid. Use data-* attributes instead:

<!-- Example user item -->
<option value="domain\davidr" data-userid="108">David</option>

<!-- Example group item -->
<option value="Test Group" data-groupid="10">Test Group</option>

Secondly, #groupOwner is the select, whereas you need to check the data attribute of the selected option. Try this:

var ownerType = $("#groupOwner option:selected").data('groupid') ? "group" : "user";

Example fiddle

Upvotes: 1

Related Questions