user3574492
user3574492

Reputation: 6435

jQuery remove an element if radio button is not checked

I have the following code that append elements to the document if the corresponding radio button is checked. This works fine, however I need a way to remove the elements if the radio button is NOT checked.

Here is what I have so far?

// for each radio button
$('input[type=radio]').each(function(){ 

    // if it is checked
    if($(this).is(":checked")) 
        {
        var cur = $(this).val();
        // append an input text element only if it does not already exist
      if(!$('#characterList input:text').is(function(i,e){ return e.value==cur && e.name=='data['+cur+']'; }))
      {
        $('#characterList').append('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');
      }
    }
   else
   {
    // otherwise remove element if radio button not checked
    $('#characterList').remove('<input type="text" name="data[' + $(this).val() + ']" value="' + $(this).val() + '" />');   
   }

   });
 });

The .remove(...) does nothing at all. What am I doing wrong here?

Upvotes: 0

Views: 1157

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

remove() doesn't work like that. You have to provide a selector to select the element you wish to remove. This can be done like so:

$('#characterList').remove('input[value="' + $(this).val() + '"]');

Or, alternatively:

$('#characterList').find('input[value="' + $(this).val() + '"]').remove();

Furthermore, instead of using $(this).is(":checked") and $(this).val(), you can simply use:

if ( this.checked )

And:

var cur = this.value;

Upvotes: 4

Related Questions