Jquery dynamic elements remove all input fields - javascript

I am working on a form that can handle dynamically added fields, it also styles them according to mobile jquery.
But my problem is that when I set up the remove it removes all the input fields.
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; //initial 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
$('<div class="ui-grid-a">'+
'<div class="ui-block-a">'+
'<div data-role="fieldcontain">'+
'<label for="hozzavalo">Hozzavalo: </label>'+
'<input name="hozzavalo[]" id="hozzavalo" type="text">'+
'</div>'+
'</div>'+
'<div class="ui-block-b">'+
'<div data-role="fieldcontain">'+
'<label for="mennyiseg">Mennyiseg: </label>'+
'<input name="mennyiseg[]" type="number"> <span style="margin-left:10px;">lb</span>'+
'</div>'+
'</div>'+
'</div>Remove').appendTo('.input_fields_wrap');//add input box
$(".input_fields_wrap").trigger("create");
}
});
$(wrapper).on("click",".remove_field", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
I need the $(".input_fields_wrap").trigger("create"); to style the fields, but when I apply it I lose all the fields when I try to remove one.

$(this).parent('div').remove();
this in this case is your .remove_field element. With your code you remove the parent div of this element which is the whole container. You have to either correctly nest the remove element so it just selects the corresponding field or fix your jquery selector.

To Remove current input fields data
Change the structure HTML Add remove link inside the div .
HTML :
<div class="ui-grid-a">
<div class="ui-block-a">
<div data-role="fieldcontain">
<label for="hozzavalo">Hozzavalo: </label>
<input name="hozzavalo[]" id="hozzavalo" type="text">
</div>
</div>
<div class="ui-block-b">
<div data-role="fieldcontain">
<label for="mennyiseg">Mennyiseg: </label>
<input name="mennyiseg[]" type="number"> <span style="margin-left:10px;">lb</span>
</div>
</div>
Remove
</div>
Jquery Section:
$(document).on("click",".remove_field", function(e){
e.preventDefault();
$(this).parent().remove();
})

Related

Dynamically Carry Values from inputs to Dynamically added new inputs

Currently it only adds the value once. I have a list of dropdowns(per this example its just input values that u can manually change) that I change from time to time. When clicking 'add' button, it should carry those values over to the field_wrapper, while dynamically adding new input fields to carry each value.
Meaning, I want it to add each new value selected from "text" and append to each new input text field!
I set the global variables above the function. But not sure why the value only shows up one time, and doesn't add new values each time I click 'add'
I hope this makes sense!
Javascript
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" id="test" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartD+ cartP;
$(wrapper).append(field)
$('#test').val(text)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
HTML
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
</div>
Nothing to do more simply interpolate the html and add text variable as value of id="test" but it is better to use class instead of id.
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartd + cartP;
$(wrapper).append(`<div><input type="text" id="test" value="${text}"/><img src="remove-icon.png"/></div>`)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
<button class="add_button">Add</button>
</div>

To Create re-usable java script code

Form sample,Error sample My Scenario is when clicking ADD VEHICLE button means it will generate new input boxes,i tried to reuse a same java script to generate the input text boxes,i
tried using ID,
var wrapper = $("#vehiclegroupid"); //Fields wrapper
var add_button = $("#addvehicleBtnid"); //Add button ID
it will supports only for the particular place,
if i tried to use class name
var wrapper = $(".summa"); //Fields wrapper
var add_button = $(".summa2"); //Add button ID
it will disturbs other related components..Here is sources
HTML
<!-- Two Wheeler -->
<div class="form-group" id="vehiclegroup">
<label for="vehicleid">Add Two Wheeler(s) Details</label>
<div id="vehiclegroupid" class="summa"></div>
<input type="button" id="addvehicleBtnid" value="Add Vehicle" class="form-control col-md-2 summa2"></input>
</div>
<!-- Four Wheeler -->
<div class="form-group" id="fourvehiclegroup">
<label for="vehicleid">Add Four Wheeler(s) Details</label>
<div id="vehiclegroupid2" class="summa"></div>
<input type="button" id="addvehicleBtnid2" value="Add Vehicle" class="form-control col-md-2 summa2"></input>
</div>
JavaScript
/**
* This is especially for adding input fields for entering co-owner details
*/
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
// var wrapper = $("#vehiclegroupid","#vehiclegroupid2"); //Fields wrapper
// var add_button = $("#addvehicleBtnid","#addvehicleBtnid2"); //Add button ID
var wrapper = $(".summa"); //Fields wrapper
var add_button = $(".summa2"); //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
x++; //text box increment now x=1 after x++ x=2,so next code 2%2==0 is true
$(wrapper).append('<div class="form-row">'
+'<!-- Vehicle Name -->'
+'<div id="TextBoxDiv'+x+'" class="form-group col-md-4">'
+'<label for="cowner'+x+'">Vehicle Name</label>'
+'<input id="cowner'+x+'" type="text" value="" class="form-control" placeholder="Enter Name"></input>'
+'</div>'
+'<!-- Vehicle Registration Number -->'
+'<div class="form-group col-md-4">'
+'<label for="oph'+x+'">Vehicle Registration Number</label>'
+'<input id="oph'+x+'" type="text" value="" class="form-control" placeholder="Ex (TN 99 AD 9999)"></input>'
+'</div>'
+' X '
+'</div>');
}
else{
alert("Sorry..!You Cannot Add More Than 5 Vehicles");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Please help me to make reusable script code...Thanks in advance
If I'm understanding correctly, what you have is a repeated group of elements which includes a button and you're attempting to have a single click handler which, when clicking a button, it affects only that local group and not all of the repeated groups.
You can achieve this by combining your selectors with some DOM traversal. You can still have a single handler, it just needs to more specifically identify the target based on what was clicked.
Currently your logic within your handler is:
Find all matching .summa elements. Append the new HTML.
Instead, you want this:
From this, find the nearest .summa element. Append the new HTML.
this of course is the button which was clicked. One way to find the "nearest" in this case is to traverse up to the closest common parent element and then find the target element within that.
Something like this:
$('.summa2').click(function(e){
var wrapper = $(this).closest('div.form-group').find('.summa');
// the rest of your click handler code
});
So starting from this (which is the button that gets clicked) the selector traverses "up" to the closest div.form-group (which is the overall repeated container) and then traverses back "down" to the target .summa (which is the target div within that group).
Update: And, of course, since your later click handler was relying on the wrapper variable it can now no longer do that. Just use the selector directly instead of the variable:
$('.summa').on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})

Append then focus on child input query

I am trying to append a div with a child input (this is working fine) however I cannot get the newly appended input to 'focus'.
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_ex1"); //Fields wrapper
var add_button = $(".add_field_button_ex1"); //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
$(this).parent().parent().append('<div id="setsdiv" class="col-xs-12 text-center"><div class="col-xs-8"><input id="set" class="form-control input-sm setinput text-center" type="text" name="ex1[]" placeholder="W / R" pattern="\\d*"></div><div class="col-xs-4"><a class="btn btn-xs btn-default remove_field pull-right">Remove</a></div></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').parent('div').remove(); x--;
})
});
The 'setsdiv' is appending but I cannot focus the input with ID 'set'.
Keep in mind that I cannot just set .focus('set') because I may have multiple the more I append.
As others have alluded to, it'd be simpler to employ classes here instead of ids. Then you can just use something like .find('.set:last').focus(); to set focus on the last element with that class which will be the one you just added.
Without knowing quite how your HTML is structured, here is an example that should illustrate the concept:
$(document).ready(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_ex1"); //Fields wrapper
var add_button = $(".add_field_button_ex1"); //Add button
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if ($('.setsdiv').length < max_fields) { //max input box allowed
$container=$(this).parent().parent();
$container.append('<div class="col-xs-12 text-center setsdiv"><div class="col-xs-8"><input class="form-control input-sm setinput text-center set" type="text" name="ex1[]" placeholder="W / R" pattern="\\d*"></div><div class="col-xs-4"><a class="btn btn-xs btn-default remove_field pull-right">Remove</a></div></div>'); //add input box
$container.find('.set:last').focus();
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).closest('.setsdiv').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap_ex1">
<div>
<button class="add_field_button_ex1">Add</button>
</div>
</div>
Try using variable x to concatenate to id of appended div , input elements to avoid duplicate ids ; call .focus() on appended input element having id ending with variable x ; increment variable
var x = 1;
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
$(this).parent().parent()
.append('<div id="setsdiv"'+x+' class="col-xs-12 text-center"><div class="col-xs-8"><input id="set"'+x+' class="form-control input-sm setinput text-center" type="text" name="ex1[]" placeholder="W / R" pattern="\\d*"></div><div class="col-xs-4"><a class="btn btn-xs btn-default remove_field pull-right">Remove</a></div></div>') //add input box
.find("input[type=text][id$="+x+"]").focus();
x++; //text box increment;
}
});
var x = 1, html = "<div id=abc"+x+"><input type=text id=def"+x+" /></div>";
$("body").append(html).find("input[type=text][id$="+x+"]").focus()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">
</script>

Using javascript on new element created by jquery

I have a field location and with that I have a button add new location.On clicking that button a new textbox for that field opens.Now what I have done is I am using autofill address on that location field but autofill works for only first textbox not those textboxes which I am creating using jquery
Below is the html code
<div class="input_fields_wrap">
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Work_Location[]" class="form-control" >
</div>
<button class="add_field_button">Add More Locations</button>
</div>
</div>
and below is the code to create new textboxes
<script>
$(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 class="form-group"><label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label><div class="col-md-3"> <input type="text" id="loc" name="Work_Location[]" class="form-control" ></div>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>
and Below is the autofill code
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>
<script>
var autocomplete = new google.maps.places.Autocomplete($("#loc")[0], {});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
console.log(place.address_components);
});
</script>
What the above code does is gives suggestions while filling location
Jquery on mathod attach event to every single element selected in selector part separatly. If you add new one you need to reaatach the event there.
<script>
$(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
container = $('<div class="form-group"></div>');
container.append('<label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label><div class="col-md-3"> <input type="text" id="loc" name="Work_Location[]" class="form-control" ></div>');
remove_box = $('Remove').on('click', remove_field);
container.append(remove_box);
$(wrapper).append(container); //add input box
}
});
function remove_field(e) {//user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
}
$(wrapper).on("click",".remove_field", remove_field);
});
</script>
Something like this. I didn't check the syntax so fix what is necesary.

Ajax Auto fill not working on dynamic fields but static fields

I had 4 static fields that inserts into Mysql db, when i fill in the first field the other 3 fields gets populated automatically, this works well, but now i had moved over to dynamic fields[] that gets populated by javascript. since the javascript function work with 'id' to autocomplete and fill, it seems that the javascript dynamic fields does not autofill and populate.
Here is the javascript for the dynamic fields:
$(document).ready(function() {
var max_fields = 30; //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('<table class="table table-bordered"><td><input class="form-control" id="state" type="text" name="name[]" required /></td><td><input class="form-control" type="text" name="surname[]" /></td><td><input class="form-control" type="text" name="idnumber[]" required/></td><td><input class="form-control" type="text" name="uniquenumber[]" required/></td><td><input class="form-control" type="text" name="nominee_photo[]" required/></td></table></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Here is the form
<form method="post" name="form1" action="ajax.php">
<div class="input_fields_wrap">
<button class="add_field_button btn btn-primary btn-flat">Add More users</button>
</div>
<div>
<input class="btn btn-success btn-flat" name="submit" type="submit">
</div>
<input type="hidden" name="insert" value="form1">
</form>
Here is the ajax function to autocomplete fields
$(function() {
$('#uniquenumber').val("");
$('#name').val("");
$('#surname').val("");
$('idnumber').autocomplete({
source: "ajaxpage.php",
minLength: 4,
select: function(event, ui) {
$('#id').val(ui.item.id);
$('#uniquenumber').val(ui.item.uniquenumber);
$('#name').val(ui.item.name);
$('#surname').val(ui.item.surname);
},
response: function(event, ui) {
// ui.content is the array that's about to be sent to the response callback.
if (ui.content.length === 0) {
alert("please insert a valid ID Number");
$("#empty-message").text("No results found");
}
}
});
});
You can use a common class as your dummy class instead of id.
then call autocomplete on that :)
i hope this will help you.

Categories

Resources