user2170246
user2170246

Reputation: 17

Selecting an option in a dropdown that has no value using jquery

I am trying to change the option selected in a dropdown using jQuery. So far nothing has worked here is my code that I have right now.

function clear_plus_group(){
$('#plus_group_id').html('');
$('#plus_group_href').html('');
$('#plus_group_remove').html('');
$('#securityGroup[1]').first().attr('selected');

Here is the select that I am working with.

<td>
<select size="1" name="securityGroup[1]" id="securityGroup[1]"
onchange="get_plus_group(this.value);">
<option></option>
<option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>            
</select>

We don't add a value to the first option since we treat that as a null when information is sent to the database. So I am trying to select the first which is the no value in the . So far nothing has worked.

Upvotes: 0

Views: 129

Answers (3)

tymeJV
tymeJV

Reputation: 104795

How about

$('#securityGroup\\[1\\] option:eq(0)').prop("selected", true);

Demo: http://jsfiddle.net/H5UBd/

Upvotes: 1

Liam
Liam

Reputation: 1768

Your object's name and ID both have square brackets. You must escape these in order for jQuery to get the proper string name for what you're looking for. This will do what you want:

 $('#securityGroup\\[1\\] option:empty').prop('selected','selected');

I also made a JSFiddle example showing this working here: http://jsfiddle.net/QWMnL/

Click the button (once you run the code) and it will select the empty item within the select dropdown. The empty item is the second item in the dropdown, so we know that it's not just selecting the first item in the dropdown (that has a value of 0 and is not empty).

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try this,

$('#securityGroup[1] option:empty').prop("selected", true);

Read this for your reference. Basically :empty selector would select the elements which is empty, Technically, Elements which don't have children/textnodes in it.

Edit:

I just realised that the ID of the select element in your HTML is having two meta-characters. So we need to escape it, in order to make that selector work.

$('#securityGroup\\[1\\] option:empty').prop("selected", true);

Upvotes: 0

Related Questions