Dynamically remove field button not working properly - javascript

Here is my code. I am able to add new field and appending the new field and remove button. There is two problem.
Remove button is not appending properly. It should append just after the
strength every time.
It Should remove respected input fields salt field and Strength field of every column.
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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
var y = x - 1;
$(wrapper).append('<div class="input-field col s6"><input class="salt" id="salt' + y + '" name="drugs[' + y + '][salt]" type="text" required><label for="salt' + y + '">Salt/Drugs</label></div><div class="input-field col s6"><input class="strength" id="strength' + y + '" name="drugs[' + y + '][strength]" type="text" required><label for="strength' + y + '">Strength</label></div>'+'</div>'+' <div class="s4"><i class="material-icons">remove_circle</i></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="row input_fields_wrap">
<div class="input-field col s4">
<input class="salt" id="salt" name="drugs[0][salt]" type="text" required>
<label for="salt">Salt/Drugs</label>
</div>
<div class="input-field col s4">
<input class="strength" id="strength" name="drugs[0][strength]" type="text" required>
<label for="strength">Strength</label>
</div>
<div class="s4">
<button class="btn btn-large light-blue add_field_button">Add more salt/drugs</button>
</div>
</div>
I want it to be like this

Based on the link in the comment, it is better to restructure the htmlString.
You can try the following way:
$(document).ready(function() {
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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
var y = x - 1;
$(wrapper).prepend('<div class="input-field col s6"><input placeholder="Salt/Drugs" class="salt" id="salt' + y + '" name="drugs[' + y + '][salt]" type="text" required><input placeholder="Strength" class="strength" id="strength' + y + '" name="drugs[' + y + '][strength]" type="text" required><i class="material-icons">remove_circle</i></div></div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="row input_fields_wrap">
<div class="input-field col s4">
<input placeholder="Salt/Drugs" class="salt" id="salt" name="drugs[0][salt]" type="text" required>
<input placeholder="Strength" class="strength" id="strength" name="drugs[0][strength]" type="text" required>
</div>
<div class="s4">
<button class="btn btn-large light-blue add_field_button">Add more salt/drugs</button>
</div>
</div>

Dynamically generated elements do not respond when listening the event directly, you have to listen to the DOM on them like
$(document).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent().remove();
x--;
})

Related

Delete dynamically generated fields

I am able to generate the dynamic fields but when i am trying to delete the fields rather then deleting the elements in front of the delete button it is deleting from last towards first
<script>
$(document).ready(function(){
var max_fields = 10;
var wrapper = $(".more");
var add_button = $(".add");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if (x < max_fields){
x++;
$(wrapper).append('<div id="box'+x+'" class="row"><div class="col-sm-3 mb-3"><select name="feeType[]" class="form-control shadow-sm" required><option value="" selected disabled>Select Fee</option><option value="Admission">Admission Fee</option><option value="Development">Development Fee</option><option value="Annual">Annual Fee</option><option value="Tuition">Tuition Fee</option></select></div><div class="col-sm-3 mb-3"><input type="number" name="amount[]" class="form-control shadow-sm" placeholder="Amount" required></div><div class="col-sm-3 mb-3"><button class="delete btn btn-danger shadow-sm">Delete Fields</button></div></div>'); //add input box
}else{
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e){
e.preventDefault();
$('#box'+x).remove();
x--;
})
});
</script>
Because x's value will always be just the number of element that were dynamically created.
A possible solution would be to find the 'remove' button that was clicked and remove it's parent. replace $('#box'+x).remove(); with this $(this).parents('.row').remove();
A working fiddle example:
https://jsfiddle.net/3L986nbj/

html Unlimited hierarchy input to form

I want to add form for adding new categories. Categories might have infinitive sub categories.
$(document).ready(function () {
var max_fields = 15; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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="input_fields_wrap_sec"><input type="text" name="mytext[]" placeholder="Sub-Category title"/>\n\
<input type="submit" name="submit1" value="Add Sub-Sub-Category" class="add_field_button" >\n\
Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST">
<div class="input_fields_wrap">
<p>Please enter the Category Title</p>
<input type="text" name="mytext[]" placeholder="Category title">
<input type="submit" name="submit1" value="Add Sub-Category" class="add_field_button" >
</div>
<input type="submit" name="submit" value="submit">
</form>
Now I have form like this and when I press "add sub-sub category" it should appear new "sub-sub category" input with buttons: "add sub-sub-sub category" and "remove"
It should be like this, the deep of categories is infinitive
Labas!
You could try something like this:
function getValueText(level) {
let i = 0
let text = "Add ";
while (i < level) {
text += "sub-"
i++;
}
return text + "category";
}
function appendInnerCategory(level, element) {
var myDiv = document.createElement("div");
myDiv.className = "level-" + level
var btn = document.createElement("input");
btn.type = "button";
btn.value = getValueText(level);
btn.addEventListener("click", function(event) {
appendInnerCategory(level + 1, event.target.parentNode);
});
var textBox = document.createElement("input");
textBox.type = "text";
myDiv.appendChild(textBox);
myDiv.appendChild(btn);
element.appendChild(myDiv);
}
appendInnerCategory(0, document.querySelector('.wrapper'));
HTML:
<div class="wrapper"></div>
Fiddle: http://jsfiddle.net/7L382gow/
Updated fiddle to maintain a structure object, while manipulating the DOM.
Submit will print the resulting hierarchy to console.
http://jsfiddle.net/bqk6pmjg/

How to add/delete 2 or more fields in a form dynamically

I would want to have two or more fields in a form to be dynamically added and deleted as per requirement. Say for, a person can have more than 1 phone numbers and more than 1 email address. The idea is to let the user add more than one phone number and email address if they have
This down below is what I did (only a rough example)
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container2");
var add_button = $(".add_form_field_1");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="text[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
//I repeated the javascript for the first field which was this
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
<div class="container2">
<button class="add_form_field_1">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[]">
</div>
</div>
And the JsFiddle.
I am not a javascript coder hence do not know if this is how you do it or is there a better way.
P.S. I asked the same question an hour ago and had to rephrase it as it was causing confusion.
You can simplyfy so much your code, check this:
$(document).ready(function() {
$("button.add_form_field").click(function(e) {
e.preventDefault();
var name = $(this).closest(".container").find("input:first").attr("class")
var numInputs = $(this).closest(".container").find("input").size()
if (numInputs < 10) {
numInputs++;
if (name=="mytext"){
$(this).closest(".container").append('<div><input type="text" name="mytext[' + numInputs + ']"/>Delete</div>');
}
if (name=="text"){
$(this).closest(".container").append('<div><input type="text" name="text[' + numInputs + ']"/>Delete</div>');
}
} else alert('You Reached the limits')
});
$(document).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[1]" class="mytext">
</div>
</div>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[1]" class="text">
</div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Here is a working example, Hope this will helps you.
This may help you Mecom
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function removeUserDetail(index)
{
var rows=jQuery("#user_info tr").length;
jQuery("#user_info tr:nth-child("+(index+1)+")").remove();
if(index==(rows-1))
{
jQuery("#user_info tr:nth-child("+(index)+")").children().eq(4).append('<a class="mc_plus_button" id="plus_1" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a>');
}
jQuery("#user_info tr").each(function(i,e){
if(i>1)
{
jQuery(this).children().eq(4).children().eq(0).attr("onclick","removeUserDetail("+i+");");
}
});
}
function addUserDetail() {
var row_count1 = jQuery("#user_info tr").length;
var row_count = 0;
jQuery(".tr_clone").each(function(index, value) {
var rowid = jQuery(this).data('rowid');
if (rowid > row_count) {
row_count = rowid;
}
});
row_count = row_count + 1;
jQuery("#user_info tr").eq(row_count1 - 1).find(".mc_plus_button").remove();
var html = '<tr class="tr_clone" data-rowid="' + row_count + '"><td>' + row_count + '</td>';
html += '<td style="text-align: center"><input type="text" name="user_info[name][]" id="name_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[email][]" id="email_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[contact][]" id="contact_'+row_count+'" aria-invalid="false" /></td>';
html += '<td><a class="mc_minus_button" id="minus_' + row_count + '" href="javascript:void();" onclick="removeUserDetail(' + row_count + ');" title="remove"><strong>–</strong></a><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td></tr>';
jQuery("#user_info").append(html);
}
</script>
<table id="user_info">
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<tr class="tr_clone" data-rowid="1">
<td align="center">1</td>
<td style="text-align: center">
<input type="text" name="user_info[name][]" id="name_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[email][]" id="email_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[contact][]" id="contact_1" aria-invalid="false" />
</td>
<td><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td>
</tr>
</table>

JQuery disable button when field is equal to a specific number

I am developing a form that can add specific number of fields when the button is clicked and it will be disabled when the number reached the limit of adding text fields.
the problem is when it reaches the limit the button can still be clicked and will disable when you click on the button twice when the text field reached its maximum input boxes allowed
here is my code.
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#healthcard"); //Fields wrapper
var add_button = $("#add_field"); //Add button ID
var x = 0; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x >= max_fields) { //max input box allowed
e.preventDefault();
$(this).toggleClass("disabled");
} else {
x++; //text box increment
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$('.hmo-add' + x).remove();
x--;
e.preventDefault();
$('#add_field').toggleClass("disabled");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div id="healthcard" class="form-group">
<button id="add_field" class="btn btn-primary" type="button" name="hmo">HMO</button>
</div>
</div>
</div>
I think I am missing something in my code that I can't figure out. Please help me.
sorry for bad english.
Thanks,
Your problem is that you need to click the button 6 times to disable it which is wrong , below is a working snippet using the disabled attribute:
When the user reaches the max, I disable the button.
The button click is register to work on the button that is not disabled using not(':disabled')
When the user removes a div, the button is enabled again
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#healthcard"); //Fields wrapper
var add_button = $("#add_field"); //Add button ID
var x = 0; //initlal text box count
$("#add_field").not(':disabled').click(function(e) { //on add input button click
e.preventDefault();
x++; //text box increment
if (x == max_fields)
{
$(this).attr("disabled", true);
}
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
$('.hmo-add' + x).remove();
x--;
$('#add_field').attr("disabled", false);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12">
<div id="healthcard" class="form-group">
<button id="add_field" class="btn btn-primary" type="button" name="hmo">HMO</button>
</div>
</div>
</div>
Check x right after append:
$(add_button).click(function(e) { //on add input button click
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
if (x == max_fields)
{
$(this).addClass("disabled");
}
}
});
DEMO
Instead of toggleClass use addClass while disabling and removeClass while enabling as below:
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x >= max_fields) { //max input box allowed
e.preventDefault();
$(this).addClass("disabled");//addClass
} else {
x++; //text box increment
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$('.hmo-add' + x).remove();
x--;
e.preventDefault();
$('#add_field').removeClass("disabled"); //removeClass
})
This is what you need:
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#healthcard"); //Fields wrapper
var add_button = $("#add_field"); //Add button ID
var x = 0; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x >= max_fields) { //max input box allowed
$(this).addClass("disabled");
$(this).attr("disabled", "disabled");
} else {
x++; //text box increment
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$('.hmo-add' + x).remove();
x--;
$('#add_field').removeClass("disabled");
$('#add_field').removeAttr("disabled");
})
});
I removed the toggleClass to addClass/removeClass as it makes more sense in this situation. I also disabled the button once the limit is reached using the disabled HTML attribute and the attr() function. If you hit the remove button, the disabled class and attribute is removed. I also removed a couple of duplicate e.PreventDefault() calls as they weren't needed.
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#healthcard"); //Fields wrapper
var add_button = $("#add_field"); //Add button ID
var x = 0; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
//if (x >= max_fields) { //max input box allowed
//e.preventDefault();
// $(this).toggleClass("disabled");
//} else {
if(x < max_fields){
x++; //text box increment
$(wrapper).append('<div class="hmo-add' + x + '""><div class="col-sm-12 col-md-4"><div class="form-group"><label class="card">Healthcard</label><input class="form-control col-md-4" type="text" name="mytext[]"/></div></div><div class="col-sm-12 col-md-8"><div class="form-group"><label class="card">Healthcard No.</label><input class="form-control col-md-8" type="text" />Remove</div></div></div>'); //add input box
if(x === max_fields) {
$(this).toggleClass("disabled");
}
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$('.hmo-add' + x).remove();
x--;
e.preventDefault();
$('#add_field').toggleClass("disabled");
})
});
[http://jsfiddle.net/W4Km8/8153/][1] I just updated your code in jsfiddle please check

Automated numbers?

I'm trying to make a add more field. So when I press add more button it should add a number 1. textfield and a dropdown menu. and if you press once more it should do 2. textfield and a dropdown menu.
I have created this code to make a new field but the counter will not match if I delete an entry in the middle
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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><input type="text" name="mytext[]"/>Ta bort</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Lägg till fler svar</button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
If it is just for displaying purpose, use CSS counter:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //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++;
$(wrapper).append('<div class="count"><input type="text" name="mytext[]"/><select><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>Ta bort</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
.input_fields_wrap {
counter-reset: count;
}
.count:before {
counter-increment: count;
content: counter(count) ".";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Lägg till fler svar</button>
<div>
<input type="text" name="mytext[]">
</div>
</div>

Categories

Resources