Legendary_Hunter
Legendary_Hunter

Reputation: 1080

jquery dynamic creation of html elements

I am trying to generate an html text box on clicking add more new notes but when I click add more notes button instead of creating the html element the button submits the form. Below is the html code

<form action="addnote.php" method="post">
    <div class="input_fields_wrap1">
        <div class="form-group">
            <label class="col-md-3" for="example-text-input">Note</label>
            <div class="col-md-2">
                <input type="text" id="coa" name="notes[]" class="form-control"  >
            </div>
            <button class="add_field_button1">Add More Notes</button>
        </div>
    </div>
    <input type="submit" value="submit">
</form>

JQuery code

    <script>
$(document).ready(function() {
    var max_fields      = 100; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap1"); //Fields wrapper
    var add_button      = $(".add_field_button1"); //Add button ID

    var x = 1; //initlal text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div class="form-group"><label class="col-md-3 control-label" for="example-text-input">Note</label><div class="col-md-3"><input type="text" id="coa" name="notes[]" class="form-control"  ></div><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
</script>

Upvotes: 0

Views: 48

Answers (2)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Put type=button as by default it work as submit button

 <button class="add_field_button1" type="button">Add More Notes</button>

JSFiddle Demo

Upvotes: 3

Tomasz
Tomasz

Reputation: 106

Change this:

<button class="add_field_button1">Add More Notes</button>

to this:

<button class="add_field_button1" type="button">Add More Notes</button>

Becouse your button is a type="submit" at the moment. That's why it's posting the form.

Upvotes: 0

Related Questions