Eslam Hamdy
Eslam Hamdy

Reputation: 7396

Remove radio buttons dynamically using jQuery

i have a problem in removing radio buttons using, i have used the (.remove) function, but when i use it it deletes all the radio buttons, i want to delete them separetly: see a demo here http://jsfiddle.net/HaBhk/10/ thanks

Upvotes: 2

Views: 13663

Answers (7)

sandeep
sandeep

Reputation: 2234

It removes all of them because all radio buttons have same ID if they have the same label ...and $('#after').children().remove(); removes all the children, which means all radio buttons in that div.. change code according to your functionality

Upvotes: 3

Jared Farrish
Jared Farrish

Reputation: 49208

I put together a variation to demonstrate several techniques. Unfortunately, I'm late for work and have a toilet that ran over all over the place, so leave a comment under this answer if you have any questions.

HTML

I made some changes to the names/ids and how the add/remove works. I think these names/ids are more consistent and descriptive, but your mileage may vary.

<input type="text" name="option" id="option" value="test"/>
<button id="add-option" data-role="button" data-inline="true">Add Option</button>
<div data-role="fieldcontain">
    <fieldset data-role="controlgroup">
        <legend>Choose an Option:</legend>
        <div id="options"></div>
    </fieldset>
</div>

CSS

Some changes to the styling, I just think it looks better.

#options label {
    display: block;
}
#options label span {
    padding-left: 5px;
    padding-right: 5px;
}
#options label button {
    border: 1px solid #aaa;
    border-left: 1px solid #9b9b9b;
    border-bottom: 1px solid #9b9b9b;
    background: #ddd;
    font-size: 8px;
    font-weight: bold;
    padding: 2px 1px;
    position: relative;
    top: -5px;
}

Javascript/jQuery

Lots of goodies, including caching, variable functions, more natural handlers, cloning elements instead of making a new one for every function call, etc. I also added a check to make sure the radio we're adding/creating doesn't already exist in the DOM.

$(document).ready(function(){

    var $radio = $('<input type="radio" name="options[]">'),
        $remove = $('<button>x</button>'),
        $label = $('<label>'),
        $span = $('<span>'),
        $option = $('input[name=option]'),
        $addbutton = $('#add-option'),
        $options = $('#options'),
        aregex = new RegExp(/[^a-zA-Z0-9 ]+/g),
        spregex = new RegExp(/[ ]+/g),
        optpre = 'option_';

    var addRadioOption = function(){

        var checkRadioExists = function(){
            var text = $option.val(),
                id = text.replace(aregex,'').replace(spregex,'_').toLowerCase(),
                id = optpre + id,
                opt = document.getElementById(id);

            if (!opt && id != '' && text != '') {
                return createRadioElement(id, text);
            }

            return false;
        };

        var createRadioElement = function(id, text) {
            var $label_clone = $label.clone(),
                $span_clone = $span.clone(),
                $radio_clone = $radio.clone(),
                $remove_clone = $remove.clone();

            var removeRadioOption = function(){
                $label_clone.remove();
            };

            $remove_clone.click(removeRadioOption);

            $radio_clone.val(text).attr('id', id);
            $span_clone.text(text);
            $label_clone.append($radio_clone, $span_clone, $remove_clone);

            return $options.append($label_clone).has($label_clone);
        };

        return checkRadioExists();
    };

    $addbutton.click(addRadioOption);

});

http://jsfiddle.net/EMqa6/

Upvotes: 3

Matt Esch
Matt Esch

Reputation: 22956

Thought I would have a go at the problem. I don't particularly like relying on ids as they should in theory be unique but you can't always guarantee it. I like to keep a reference to elements that I've added to the page because it's likely that I will want to remove them at some point. Here's an example which doesn't allow duplicate options and doesn't rely on ids (although I kept your label-input association).

http://jsfiddle.net/z8dRJ/1/

The benefits are that you can quickly rebuild the option list (say if you wanted to sort them) and you can easily test if an option exists without having to look it up. Other than your label association you don't actually need to use any id values. I've preserved your passing of elem even though I don't see you using it.

Note that I am careful to ensure I don't hold onto any elements after removing them to avoid memory leaks.

Upvotes: 2

MatuDuke
MatuDuke

Reputation: 5008

If you want to delete the selected radio:

function createRadioElement(elem, label, checked) {
    var id = 'option1_' + label;
    $('#after').append($('<div><input type="radio" name="option1" id="' + id + '" value="1" /><label for="' + id + '">' + label + '</label></div>'));
 }

$('#AddButton').click(function(){
    var x = document.getElementById('option').value;
    createRadioElement(this,$('#option').val());
}); 
$('#RemoveButton').click(function(){
   $('#after').children().children("input[checked='checked']").parent().remove();
}); 

Upvotes: 2

linuxeasy
linuxeasy

Reputation: 6499

You can seperate your radio buttons either by id or 'class' or specific tag names and then select them appropriately and delete them.

like :

$('input[type=radio].class_name').remove(); // delete with class_name
// or 
$('input[type=radio]#id_name').remove();  // delete with id_name
// or
$('input[type=radio][name=your_specific_name]').remove(); // delete with your radio button's specific name attribute.

$('input[type=radio]:eq(1)').remove(); //to remove your elements if they would occur in fixed specific order, or in case dynamic order deletion is fine.

Update on OP's comment

If they are dynamically generated, its still can be done, dunno what's your dynamic language is, but consider in php, you can do it this way:

$('input[type=radio]#<?php echo $dynamic_id_variable; ?>').remove();

//or for javascript
$('input[type=radio]#'+ dynamic_id_variable ).remove();

Upvotes: 5

MatuDuke
MatuDuke

Reputation: 5008

To remove the last radio button, you can do:

$('#RemoveButton').click(function(){
   $('#after').children().last().remove();
   $('#after').children().last().remove();
   $('#after').children().last().remove();
}); 

I added 3 lines, because you insert one radio-button, one label and one line-break. You could put all inside a div like this:

function createRadioElement(elem, label, checked) {
    var id = 'option1_' + label;
    $('#after').append($('<div><input type="radio" name="option1" id="' + id + '" value="1" /><label for="' + id + '">' + label + '</label></div>'));
 }

$('#AddButton').click(function(){
    var x = document.getElementById('option').value;
    createRadioElement(this,$('#option').val());
}); 
$('#RemoveButton').click(function(){
   $('#after').children().last().remove();
}); 

Upvotes: 2

Misam
Misam

Reputation: 4389

 $('input:radio:last').remove();

This should do the trick. This will remove only the last added radio button one by one

Upvotes: 4

Related Questions