1

I have this generated code:

<select class="generic-widget" id="auth_user_group_id" name="group_id"> <option value=""></option> <option value="2">admin</option> <option value="3">user</option> <option value="1">guest</option> </select> 

I need use JS to delete the guest option and try to set the user option like default...

I tried with this JQuery code to delete the guest option, but something fails:

<script> $('option').each(function(){ if($(this).attr('value') == '1') { $(this).remove(); } }); </script> 

5 Answers 5

1

Removing an item from a select box

Remove an option :

$("#auth_user_group_id option[value='1']").remove(); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Christian_Espinoza: You're saying that if you do nothing more than replace the code in your question with the above code, it suddenly works? That doesn't make sense,.
1

What about:

$('#auth_user_group_id > option[value="1"]').remove(); 

Comments

1

Works fine as long as you run your code after the DOM is ready.

 // v----this handler will run after the DOM has loaded $(function() { $('option').each(function(){ if($(this).attr('value') == '1') { $(this).remove(); } }); }); 

DEMO: http://jsfiddle.net/TTUkS/

If your code placed at the top of the page, then it runs before the elements exist.

2 Comments

this way is more readable in my opinion: if($(this).val() == '1') ...
@Mic: I agree, but the point is that OP's code works correctly the way it's written. So the code itself doesn't need fixing, but (likely) it just needs to run after the DOM is ready.
0

You can put the value condition in the selector:

$('#auth_user_group_id option[value="1"]').remove(); 

Then you can use the val method to select an option:

$('#auth_user_group_id').val('3'); 

Comments

0

You can check the value of an option item with:

$('option').each(function(){ if($(this).val() == '1') { $(this).remove(); } }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.