Hello All,

Objective is to manage radio button Dynamically. One should be able to add/delete radio button by ADD and DELETE button in form. To make CLEAR the question, please look at the image "BUTTON". In addition, it should be displayed with updated values (Need to manage from database side also). !! I think one may use JavaScript.

BUTTON

For example, IF one click on ADD in order to add new radio button => FERRARI, Then is should be display 3 items and IF one click on DELETE in order to delete "BMW", result should be 2 items. I Hope i am clear to you.

Thanks a lot in advanced.

Recommended Answers

All 25 Replies

Member Avatar for LastMitch

@PriteshP23

Objective is to manage radio button Dynamically. One should be able to add/delete radio button by ADD and DELETE button in form.

I mean it's good that you post image how you it to look like but where is the code?

You have to post a code of what you have done so far to see what you did.

Member Avatar for diafol

Like LM states - show your code. If you're stuck, here's a few pointers. You can convert php array to json format like this:

<?php
    $json = json_encode(array("bmw","mercedes","mini","land rover"));
?>

So all you have to do is get the data from the DB in a suitable format (array).

Your form is presumably something like this:

<form>
    <div id="radio"></div>
    <button id="btnadd">Add</button>
    <button id="btndel" disabled="disabled">Delete</button>
</form>

I'd use jQuery for this, so just before your </body> tag, place this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

Then under that you can do something like:

<script>
    var json = <?php echo $json;?>;
    //rest of code
</script>    

You need to code for 2 events - the btnadd and the btndel .click
Have a little play with it and come back with some effort.

@diafol

Thanks for the code. I am begginer for JSON. I just would like to have exact flow for one demo for ADD or DELETE button. I need to know the actions behind the screen. I would like to have one complete file to understand the logic from which one can get the result. I have tried one example and i did like this.

@LastMitch
Here is my code. I did what i know.

I would like to know NEXT Steps in order to get the expected results. Please let me know if you have ANY idea.

<HTML>
<HEAD>
<SCRIPT language="javascript">
function add(type) 
{
    var element = document.createElement("input");
    element.setAttribute("type", type);
    element.setAttribute("value", type);
    element.setAttribute("name", type);
    var foo = document.getElementById("fooBar");
    foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<SELECT name="element">
    <OPTION value="button">Button</OPTION>
    <OPTION value="text">Textbox</OPTION>
    <OPTION value="radio">Radio</OPTION>
</SELECT> 
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>
<span id="fooBar">&nbsp;</span>
</FORM>
</BODY>
</HTML>
Member Avatar for LastMitch
<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>

What results did you get when you onclick=add()?

It is creating only textbox with value undefined. Please let me know by example the next steps IF you have ANY idea.

@diafol

If possible, Please let me know it by one example. I do not know JSON. Thanking you so much in advanced.

I need help in order to get the result soon.

Member Avatar for diafol

If possible, Please let me know it by one example. I do not know JSON. Thanking you so much in advanced.

Try researching it. Google. Try coding it. If you get stuck, ask in the javascript forum.

It is giving name for radio button all time "add". How one can enter the button value from user ? I need to do like at a time ONLY one button can be selected and then able to edit name/delete selected one. Any help would be great..!

//js
function add() 
{
    var foo = document.getElementById("fooBar");
    var id="add";
    var radio1 = document.createElement("input");
    radio1.setAttribute("value","ADD");
    radio1.setAttribute("type","radio");
    radio1.setAttribute("id","radio");
    var newL = document.createElement("label");
    var newT = document.createTextNode("add");
    newL.appendChild(newT);
    newL.htmlFor = "id";    
    var br = document.createElement("br");

    foo.appendChild(radio1);
    foo.appendChild(newL);
    foo.appendChild(br);
}
// php form
<!--  Add -->
<input type="hidden" name="Add" value="Add_btn" />
<input type="button"  onclick="add()"/>  
&nbsp;
<!--  Delete -->
<input type="hidden" name="Delete" value="Delete_btn" />
<input type="button" value="Delete" onclick="delete()" />
<div id="fooBar"></div> 
Member Avatar for diafol

You could do something like this:

<?php
    $json = json_encode(array("bmw","mercedes","mini","land rover"));
?>

<form>
    <div id="radio"></div>
    <button id="btnadd">Add</button>
    <button id="btndel" disabled="disabled">Delete</button>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
    var json = <?php echo $json;?>;
    var num = json.length;
    var displayed = 0;
    $('#btnadd').click(function(e){
        e.preventDefault();
        addItem();
    });
    $('#btndel').click(function(e){
        e.preventDefault();
        delItem();
    });

    function addItem(){
        $('#radio').append('<input type="radio" name="cars" value="' + json[displayed] + '" checked="checked" /><label class="rad">' + json[displayed] + '</label>');
        displayed++;
        if($('#btndel').attr('disabled')) $('#btndel').removeAttr("disabled");
        if(displayed == num) $('#btnadd').attr('disabled','disabled');
    }

    function delItem(){
        $('#radio input').last().remove();
        $('#radio label').last().remove();
        displayed--;
        if($('#btnadd').attr('disabled')) $('#btnadd').removeAttr("disabled");
        if(displayed == 0)$('#btndel').attr('disabled','disabled'); 
    }
</script>

Thank you so much.

Now, I did like this. Only problem is that it is not displaying after REFRESHING the page.

<!-- PriteshP23 -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
.marginTop{margin-top:20px;width:350px;text-align:left;}
#xxx_add_r{width:350px;text-align:left;}
</style>
<title>PriteshP23</title>
</head>
<body id="page_bg">

<div class="center" align="center">

    <div id="wrapper_r">

        <div class="fullWidth header">

            <table>
                <tr>
                    <td colspan="2">Add radio buttons...</td>
                </tr>
                <tr>
                    <td><input type="button" name="add" id="add" value="Add" /></td>
                    <td><input type="button" name="delete" id="delete" value="Delete" /></td>
                </tr>
            </table>
            <div id="main">

            </div>

        </div>

    </div>

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function(){
    jQuery('#add').click(function(){

        if(jQuery('#xxx_add_e').length){
            return false;
        }else{
            //var name = jQuery.trim(jQuery('#radio').val());

            var elem = '<input type="radio" name="" id="xxx_add_e" />';
            var row = '<div id="xxx_add_r"><span>'+elem+'</span><span id="xxx_add_label"><input type="text" value="" placeholder="enter value" id="xxx_add_t" /></span> <span id="xxx_add_btns"><span><input type="button" value="okay" id="xxx_add_y" onclick="xaddElement();" /></span> <span><input type="button" value="cancel" id="xxx_add_n" onclick="xcancelElement();" /></span></span></div>';
            jQuery('#main').prepend(row);

        }

    });
    jQuery('#delete').click(function(){

        for(var i=0; i<jQuery(':radio').length; i++){
            var rad = jQuery(':radio')[i];
            if(jQuery(rad).is(':checked')){
                //make an ajax call here to delete record from database
                jQuery('#'+jQuery(rad).attr('id')+'_r').remove();
            }
        }
    });

});
function xaddElement(){
        var val = jQuery('#xxx_add_t').val();

        ////Make an ajax call to add element data in database
        jQuery('#xxx_add_btns').remove();
        jQuery('#xxx_add_label').text(val);
        jQuery('#xxx_add_label').attr('id',val+'_label');
        jQuery('#xxx_add_r').attr('class','marginTop');
        jQuery('#xxx_add_r').attr('id',val+'_r');
        jQuery('#xxx_add_e').attr('name',val);
        jQuery('#xxx_add_e').attr('id',val);
}
function xcancelElement(){
    jQuery('#xxx_add_r').remove();
}

</script>
</body>
</html>

It is user form. In my project, user can add/edit/delete radio button items on the form. I have three forms on same page. It should be display AFTER REFRESH the page.

Any help or correction will be great.

Member Avatar for LastMitch

I have three forms on same page

I thought you have 1 form with 3 radio button option?

Member Avatar for diafol

It is user form. In my project, user can add/edit/delete radio button items on the form.

Why??

ANyway, you need to save it server-side (or to a cookie) for it to show on page refresh. You can either save it to SESSION, DB or cookie, or even XML or JSON. Your choice.
You also need to decide whether you want ajax to update after each addition and deletion. or a one-off save at the end. Loads of ways to do this.

It is part of the project. So, i would like to know only one way to get the output that should be easy and less time consuming.

Correction in the code or one example would be great.

Member Avatar for diafol

from what I can see, the code should work to add elements - doesn't it?
I'm afraid I don't have the time to create an update script. Have you created one that we could look at?

Well, it is working perfectly to add and delete both. Only two things are remaining: 1.Save on page after REFRESH & 2. Save in database.

I have put whatever i have in my last post. Please take your time. Thanks a lot in advanced.

Member Avatar for diafol

OK, so research ajax saving (jQuery makes it easy - loads of tuorials out there). In a nutshell you can use $.post or $.ajax to pass data to a php file which updates the DB and then get the php to pass a msg back to js to say whether it was successful or not.

I just need to save the data on page after REFRESH and save in DB. Any example of CODE would be great.

Member Avatar for diafol

I just need to save the data on page after REFRESH and save in DB.

Yes I know, that's why I discussed your options. ANyway you need to save BEFORE refresh.

Any example of CODE would be great.

I've already said:

I'm afraid I don't have the time to create an update script.

It's your job to do that. If you get stuck with it, by all means post a question.

It is not working AFTER refresh anymore:

// php
<div style="padding-left:280px;">
                            <!--  Add -->
                            <input type="button" class="btnAjouterConfigure" id="add" value="Ajouter" style="text-decoration:none; width:100px; height:41px; line-height:34px; font-weight:bold;" onclick="addnature()"/>    
                            &nbsp;
                            <!--  Delete -->
                            <input type="button" class="btnSupprimerConfigure" id="delete" value="Supprimer" style="text-decoration:none; width:100px; height:41px; line-height:34px; font-weight:bold;" onSubmit="return deleteRadioButton();">
                            <div id="fooBar"></div> 
                        </div>
                        <br />

                        <div style="height:auto; padding-left:280px;" id="mainRadio">
                        <?php if(mysql_num_rows($rs)){ ?>
                            <?php while($row = mysql_fetch_assoc($rs)){ ?>
                            <div id="<?php echo $row['libelle']?>_r" class="marginTop">
                                <span><input type="radio" name="<?php echo $row['libelle']?>" id="<?php echo $row['libelle']?>"></span> 
                                <span id="<?php echo $row['libelle']?>_label"><?php echo $row['libelle']?></span>
                            </div>
                            <?php }?>
                        <?php }?>

                        </div>
<script type="text/javascript">
jQuery(function(){
    jQuery('#add').click(function(){

        if(jQuery('#xxx_add_e').length){
            return false;
        }else{
            //var name = jQuery.trim(jQuery('#radio').val());

            var elem = '<input type="radio" name="" id="xxx_add_e" />';
            var row = '<div id="xxx_add_r"><span>'+elem+'</span><span id="xxx_add_label"><input type="text" value="" placeholder="enter value" id="xxx_add_t" /></span> <span id="xxx_add_btns"><span><input type="button" value="okay" id="xxx_add_y" onclick="xaddElement();" /></span> <span><input type="button" value="cancel" id="xxx_add_n" onclick="xcancelElement();" /></span></span></div>';
            jQuery('#mainRadio').prepend(row);

        }

    });
    jQuery('#delete').click(function(){

        for(var i=0; i<jQuery(':radio').length; i++){
            var rad = jQuery(':radio')[i];
            if(jQuery(rad).is(':checked')){
                //make an ajax call here to delete record from database
                jQuery.ajax({
                    url:'radio.php?delete=1&name='+jQuery(rad).attr('name'),
                    success: function(){

                    },
                    complete: function(){
                        jQuery('#loading').hide();
                    }
                });
                jQuery('#'+jQuery(rad).attr('id')+'_r').remove();
            }
        }
    });

});
function xaddElement(){
        var val = jQuery('#xxx_add_t').val();

        jQuery('#loading').show();
        ////Make an ajax call to add element data in database
        jQuery.ajax({
            url:'radio.php?add=1&name='+val,
            success: function(html){

            },
            complete: function(){
                jQuery('#loading').hide();
            }
        });

        jQuery('#xxx_add_btns').remove();
        jQuery('#xxx_add_label').text(val);
        jQuery('#xxx_add_label').attr('id',val+'_label');
        jQuery('#xxx_add_r').attr('class','marginTop');
        jQuery('#xxx_add_r').attr('id',val+'_r');
        jQuery('#xxx_add_e').attr('name',val);
        jQuery('#xxx_add_e').attr('id',val);
}
function xcancelElement(){
    jQuery('#xxx_add_r').remove();
}

</script>

// radio.php
<?php
if($_REQUEST['add'] == 1){
    $name = trim($_REQUEST['name']);
    $sql = "insert into user_nature set ref_user=1, libelle='$name'";
    mysql_query($sql);
}
if($_REQUEST['delete'] == 1){
    $name = trim($_REQUEST['name']);
    $sql = "delete from user_nature where libelle='$name'";
    mysql_query($sql);
}

?>
Member Avatar for diafol

Ok, this seems to be js/jQuery as opposed to php - how about moving it to that forum?

I did. I hope i will get the expected result.

Member Avatar for diafol

I did. I hope i will get the expected result.

?? this is still in the php forum.

Finally,i got it.. :)

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    jQuery(function(){
        jQuery('#add').click(function(){

            if(jQuery('#xxx_add_e').length){
                return false;           
            }

            else{
                //var name = jQuery.trim(jQuery('#radio').val());

                var elem = '<input type="radio" name="" id="xxx_add_e" />';
                var row = '<div id="xxx_add_r"><span>'+elem+'</span><span id="xxx_add_label"><input type="text" placeholder="enter value" id="xxx_add_t"/></span> <span id="xxx_add_btns"><span><input type="button" value="OK" id="xxx_add_y" onclick="xaddElement();" /></span> <span><input type="button" value="Cancel" id="xxx_add_n" onclick="xcancelElement();" /></span></span></div>';

                jQuery('#mainRadio').prepend(row);
            }

        } );
        jQuery('#delete').click(function(){

            for(var i=0; i<jQuery(':radio').length; i++){
                var rad = jQuery(':radio')[i];
                if(jQuery(rad).is(':checked')){
                    //make an ajax call here to delete record from database
                    jQuery.ajax({

                        //url:'radio.php?action=delete&name='+jQuery(rad).attr('name'),
                        url:'radio.php?action=delete&name='+jQuery(rad).val(),
                        success: function(){
                            window.location = window.location.href;
                        },
                        complete: function(){
                            jQuery('#loading').hide();
                        }
                    });
                    jQuery('#'+jQuery(rad).attr('id')+'_r').remove();
                }
            }
        });

    });
    function xaddElement(){
            var val = jQuery('#xxx_add_t').val();
            //alert(val);
            jQuery('#loading').show();
            ////Make an ajax call to add element data in database 
            var myurl = 'radio.php?action=add&name='+val;
            //alert(myurl);
            jQuery.ajax({
                  url:myurl,

                success: function(html){
    //alert(html);
                },
                complete: function(){
                    jQuery('#loading').hide();
                },
                onError:function(xhr){
                alert(html);
                }
            });

            jQuery('#xxx_add_btns').remove();
            jQuery('#xxx_add_label').text(val);
            jQuery('#xxx_add_label').attr('id',val+'_label');
            jQuery('#xxx_add_r').attr('class','marginTop');
            jQuery('#xxx_add_r').attr('id',val+'_r');
            jQuery('#xxx_add_e').attr('name',val);
            jQuery('#xxx_add_e').attr('id',val);
    }
    function xcancelElement(){
        jQuery('#xxx_add_r').remove();
    }

    </script>
    <div id="loading" style="position: fixed;width:100%;top:0;left:0;right:0;bottom:0;background:#f7f7f7;opacity:0.4;display:none;">
        <div id="" style="text-align:center;width:100%;position:relative;top:100px;color:#fff">
        Loading...
        </div>
    </div>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.