[jQuery] How do I select only options with values in a particular select?

Asked 1 years ago, Updated 1 years ago, 95 views

I'm a beginner developer.

I received a request for development, but I'm posting a question because I thought there's a better way.

<select id="selectid">
    <option value=">Select</option>
    <option value="choose1">Select 1</option>
    <option value="choose2">Select 2</option>
</select>

Each individual can have multiple or one option selection. You want to automatically select one of them when there is only one of them except 'Select'.

If it is impossible to implement, you can choose the second one if the number of select is two, or you can find it using each, but I wonder if there is a way to find it by selecting only one selector.

I've done it up to here

$('#selectid :not([value=""])')

If you do this,

<select id="selectid">
    <option>Select</option>
</select>

He found something like this, too. Is there any way?

jquery javascript selector

2022-09-21 15:23

1 Answers

If:

<select id="selectid">
    <option value=">Select</option>
    <option value="choose1">Select 1</option>
</select>

If this is the case, selector you created:

$('#selectid :not([value=""])')

As an example,

<select id="selectid">
    <option>Select</option>
    <option value="choose1">Select 1</option>
</select>

It doesn't have any value attribute, right? So

$('#selectid [value])')

This will only select the option with the value property.

If you don't have any value property or want to remove the option that is empty even if it exists, you can apply both of the above examples, right?

$('#selectid [value]:not([value=""])')
// as below
$('select#selectid').find('option[value]').not('option[value=""]')


2022-09-21 15:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.