Opoe Opoe - 6 months ago 8
Javascript Question

Append a div, depending on which radiobutton is checked

I would like the user to select/check a radiobutton (for this example I used directions). With a button you can append some elements to another div (sidebar).

What I would like to accomplish:
Depending on wich radiobutton is checked, I want another image/div to append. So when 'Left' is checked, I want the '.Left' div to append (instead of the value). How can I accomplish this?

Hope you can help me out. I'm looking for a clear explaination.

HTML

<div>
<input type="text" name="itemtitle" id="itemtitle" value="Title" />
<br/>
<input type="radio" id="up" name="direction" value="Up" /> Up
<input type="radio" id="down" name="direction" value="Down" /> Down
<input type="radio" id="left" name="direction" value="Left" /> Left
<input type="radio" id="right"name="direction" value="Right" /> Right
<button id="addbutton">add it</button>
</div>

<div id="sidebar"><h1>Sidebar</h1>

</div>


JS

$('#addbutton').click(function() {

var $addDiv = $('<div></div>', {
'class': 'bluebox'
}).html($('#itemtitle').val() + ' ' + $('input[name="direction"]:checked').val() + '<input type="button" class="removebtn" value="." id="removebtn"/>');


if ($('input[name="direction"]:checked').val() == 'Left') {

$('.Left').appenTo($addDiv);

}

$('#sidebar').append($addDiv);


$('.removebtn').live('click', function() {
$(this).parent().remove();


});
$('.bluebox').draggable({
revert: true
});


});


JSFIDDLE

Answer

If you want to put something instead of the value, the first thing that comes to mind is this:

$('#addbutton').click(function() {

    var $addDiv = $('<div></div>', {
        'class': 'bluebox'
    }).html('<input type="button" class="removebtn" value="." id="removebtn"/>');

     if ($('input[name="direction"]:checked').val() == 'Left') {

        $('.Left').prependTo($addDiv).fadeIn();

    }
    else{
          $addDiv.prepend($('#itemtitle').val() + ' ' + $('input[name="direction"]:checked').val());
    }


    $('#sidebar').append($addDiv);


    $('.removebtn').live('click', function() {
    $(this).parent().remove();


    });

    $('.bluebox').draggable({
        revert: true
    });


});

I have changed the first $addDiv assignment to add only the remove button. Then, if it's left I add the div and if it's another one I add the input value.

Also, you hadn't a <div class="left"></div>

You can see it working here