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>
Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
chespinoza
  • 2,638
  • 1
  • 23
  • 46

5 Answers5

1

What about:

$('#auth_user_group_id > option[value="1"]').remove();
Lloyd
  • 29,197
  • 4
  • 84
  • 98
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.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • this way is more readable in my opinion: `if($(this).val() == '1') ...` – Mic Nov 15 '12 at 16:37
  • @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. – I Hate Lazy Nov 15 '12 at 16:42
1

Removing an item from a select box

Remove an option :

$("#auth_user_group_id option[value='1']").remove();
Community
  • 1
  • 1
Fireblaze
  • 242
  • 3
  • 5
  • @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,. – I Hate Lazy Nov 15 '12 at 17:40
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');
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You can check the value of an option item with:

$('option').each(function(){
if($(this).val() == '1') {
    $(this).remove();
    }
});
erwin_smit
  • 680
  • 6
  • 12