Dynamic adding of fields with jquery - javascript

I have this existing code which I had some help on: http://jsfiddle.net/975VQ/11/
The issue with this code is I also want to allow them to remove the original field. I cannot remove the original text field and still add another.
Could someone please show me how I could approach this problem instead? I would assume it would be by using javascript to add the first entry, and then using javascript to add in the markup each time rather than cloning it.
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})
Any help or input on this would be appreicated.

You are deleting the field with the id=InputsWrapper on the original field, that is the div where you are ataching the news fields.
You need to put the original field in other div.
<div id="InputsWrapper">
<div>
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
</div>

try this fiddle, this is what you need
http://jsfiddle.net/975VQ/20/
HTML:
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be.</p>
<div>
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
<div id="InputsWrapper"></div>
<br />
<button id="addfield">Add question</button>
<br />
JS:
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>').insertBefore(InputsWrapper);
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
console.log(x);
if( x > 1 ) {
console.log(x);
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})

check this jsfiddle
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be.</p>
<div id="InputsWrapper">
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
<br />
<button id="addfield">Add question</button>
<br />
javascript
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x >= 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})

this jsfiddle should be what you want if I understood well,
HTML:
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be.</p>
<div id="InputsWrapper">
<div>
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
</div>
<br />
<button id="addfield">Add question</button>
<br />
Javascript:
var MaxInputs = 8; //maximum input boxes allowed
var InputsWrapper = $("#InputsWrapper"); //Input boxes wrapper ID
var AddButton = $("#addfield"); //Add button ID
var x = InputsWrapper.length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(InputsWrapper).append('<div><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
if(FieldCount == 2 && x > 1)
{
$("#InputsWrapper div").first().remove();
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x >= 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
})

Try This
HTML
<h1>Questions</h1>
<p>Add additional questions. You can select how long you would like the reply to be.</p>
<div class="que">
<div class="InputsWrapper">
<input value="Why do you want this">
<select>
<option value="single">Single line reply</option>
<option value="multi">Paragraph reply</option>
</select>
<button class="removeclass">Delete</button>
</div>
</div>
<br />
<button id="addfield">Add question</button>
<br />
Javascript
var MaxInputs = 8; //maximum input boxes allowed
var AddButton = $("#addfield"); //Add button ID
var x = $(".InputsWrapper").length; //initlal text box count
var FieldCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxInputs) //max input box allowed
{
FieldCount++; //text box added increment
//add input box
$(".que").append('<div class="InputsWrapper"><input type="text" name="mytext[]" id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><button class="removeclass">Delete</button></div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
return false;
})
DEMO

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>

How to generate a input tag above a button

I have a input tag and a link button. I want to click in the button and generate a input tag and an other link button is delete and click in the delete button to delete input tag. But when I click on the button generate input tag under the button. Now I want to generate input tag above the button. How can I do that?
$(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/1.11.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>
You can use "prepend" instead of "append" to accomplish this. Check this snippet.
$(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).prepend('<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>

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.

Validating Dynamic input fields with jquery

Hey guys i'm trying to validate input fields that will be dynamically generated by the user with a link button to make the user add more input fields but the problem i have is that its only the first field that is validated but the input fields generated dynamically doesn't validate.
Here's the html codes:
<form id="testform" method="post">
<div style="margin-top: 10px;" id="within_nigeria1">
<div id="divint1">Address(s) within Nigeria: Add more field
<input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text[]" />
<div class="wn"></div>
</div>
</div>
<input type="submit" value="submit" />
</form>
Here is the jquery codes:
$('#testform').validate({
rules: {
"address_text[]": {
required: true
}
}
});
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#within_nigeria1"); //Fields wrapper
var add_button = $("#add_field_button"); //Add button ID
var wrapper1 = $(".wn");
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
$(wrapper1).append('<input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text[]"/>Remove');
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
jquery.validate requires that every input have a unique name. So instead of having names like
name="address_text[]"
you need to put explicit counters into the brackets. The initial HTML should use name=address_text[0], and the Javascript that adds rows can increment it.
var counter = 0;
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
counter++;
$(wrapper1).append('<input class="form-control" id="address_text" style="width: 100%; margin-bottom: 5px;" type="text" name="address_text['+counter+']"/>Remove');
}
});

Categories

Resources