Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add / remove input field dynamically with jQuery

Tags:

html

jquery

I would like to use jquery to build a dynamic add/ remove form. IT should look like:

Name Type Required?

The example input :

  • Name Type Required?
  • Tony Admin checked (checkbox) Delete <==press the button will delete the row

What i have got is a example of add/ remove input box how can it convert to my idea? Do i have to use multi coloumn table? Thank you for kindly help

    <html>
<head>
<title>jQuery add / remove textbox example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
    div{
        padding:8px;
    }
</style>

</head>

<body>

<h1>jQuery add / remove textbox example</h1>

<script type="text/javascript">

$(document).ready(function(){

    var counter = 2;

    $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

     $("#getButtonValue").click(function () {

    var msg = '';
    for(i=1; i<counter; i++){
      msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
    }
          alert(msg);
     });
  });
</script>
</head><body>

<div id='TextBoxesGroup'>
    <div id="TextBoxDiv1">
        <label>Textbox #1 : </label><input type='textbox' id='textbox1' >
    </div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

</body>
</html>
like image 883
user782104 Avatar asked Feb 07 '12 08:02

user782104


People also ask

How dynamically add and remove fields in jQuery?

Create an input group and add an input field along with a button. i.e this button will be used to delete this input field. Create a button and on clicking this button we will dynamically add the input fields. Now write the click() function to handle the adding and removing functionality.

How do you create a dynamic input field?

Create new elements by means of document. createElement() , and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input> s if they are to be submitted in a form.

How can create multiple dynamic textbox in button click in jQuery?

The following jQuery code lets you get the approach to create a dynamic textbox and button. jQuery code to handle dynamic textbox creation, <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript">


2 Answers

I took the liberty of putting together a jsFiddle illustrating the functionality of building a custom form using jQuery. Here it is...

EDIT: Updated the jsFiddle to include remove buttons for each field.

EDIT: As per the request in the last comment, code from the jsFiddle is below.

EDIT: As per Abhishek's comment, I have updated the jsFiddle (and code below) to cater for scenarios where duplicate field IDs might arise.

HTML:

<fieldset id="buildyourform">
    <legend>Build your own form!</legend>
</fieldset>
<input type="button" value="Preview form" class="add" id="preview" />
<input type="button" value="Add a field" class="add" id="add" />

JavaScript:

$(document).ready(function() {
    $("#add").click(function() {
        var lastField = $("#buildyourform div:last");
        var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        fieldWrapper.data("idx", intId);
        var fName = $("<input type=\"text\" class=\"fieldname\" />");
        var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(fName);
        fieldWrapper.append(fType);
        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $("#preview").click(function() {
        $("#yourform").remove();
        var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
        $("#buildyourform div").each(function() {
            var id = "input" + $(this).attr("id").replace("field","");
            var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
            var input;
            switch ($(this).find("select.fieldtype").first().val()) {
                case "checkbox":
                    input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textbox":
                    input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textarea":
                    input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
                    break;    
            }
            fieldSet.append(label);
            fieldSet.append(input);
        });
        $("body").append(fieldSet);
    });
});

CSS:

body
{
    font-family:Gill Sans MT;
    padding:10px;
}
fieldset
{
    border: solid 1px #000;
    padding:10px;
    display:block;
    clear:both;
    margin:5px 0px;
}
legend
{
    padding:0px 10px;
    background:black;
    color:#FFF;
}
input.add
{
    float:right;
}
input.fieldname
{
    float:left;
    clear:left;
    display:block;
    margin:5px;
}
select.fieldtype
{
    float:left;
    display:block;
    margin:5px;
}
input.remove
{
    float:left;
    display:block;
    margin:5px;
}
#yourform label
{
    float:left;
    clear:left;
    display:block;
    margin:5px;
}
#yourform input, #yourform textarea
{
    float:left;
    display:block;
    margin:5px;
}
like image 100
FarligOpptreden Avatar answered Oct 16 '22 18:10

FarligOpptreden


You need to create the element.

input = jQuery('<input name="myname">');

and then append it to the form.

jQuery('#formID').append(input);

to remove an input you use the remove functionality.

jQuery('#inputid').remove();

This is the basic idea, you may have feildsets that you append it too instead, or maybe append it after a specific element, but this is how to build anything dynamically really.

like image 36
thenetimp Avatar answered Oct 16 '22 18:10

thenetimp