jquery 动态创建 html 元素
2015-07-29
46
我尝试在单击“添加更多新注释”时生成一个 html 文本框,但当我单击“添加更多注释”按钮而不是创建 html 元素时,该按钮会提交表单。以下是 html 代码
<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 代码
<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>
2个回答
将
type=button
设置为默认,它可用作提交按钮
<button class="add_field_button1" type="button">Add More Notes</button>
Bhushan Kawadkar
2015-07-29
将此:
<button class="add_field_button1">Add More Notes</button>
更改为:
<button class="add_field_button1" type="button">Add More Notes</button>
因为您的按钮目前是 type="submit"。 这就是它发布表单的原因。
Tomasz
2015-07-29