add and delete divs created in JS - javascript

So I got this working almost perfectly but for some reason deleteInput() won't delete 2 div's in a row and I can not figure it out. The function still works but it won't delete. can someone explain why this is?
https://codepen.io/kScheid/pen/pLYXwE?editors=1010
HTML:
<div id="parent" class="first-div">
<label for="email">Email</label><input type="email" id="mail" name="usermail"> <div class="line-left shrinkM-underline"></div>
<div id="child" class="showE flex-it">
<div>
<input type="email"><div class="line-left shrinkM-underline"></div>
</div>
<span type="button" value="Remove Element" onClick="removeElement('parent','child');" class="remove"> <strong>Remove</strong></span>
</div>
<input onclick="addElement('parent', 'child');" class="input-button" type="button" value="+Add another email">
</div>
Javascript:
var counter = 1;
var limit = 5;
var newdiv = document.createElement('div');
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function deleteInput() {
for (var x = 0; x < counter; x++){
newdiv.removeChild(newdiv.childNodes[0]);
}
counter--;
}
Base format before JS
Added another Div w/JS

This may solve your problem if I understood what you are trying to do correctly. I've added an email class to your divs to remove the emails more easily.
var counter = 1;
var limit = 5;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.className = "email"
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function deleteInput(divName) {
var emails = document.getElementsByClassName("email");
if (emails.length) {
document.getElementById(divName).removeChild(emails[emails.length - 1]);
counter--;
}
}
<div id="parent" class="first-div">
<label for="email">Email</label><input type="email" id="mail" name="usermail">
<div class="line-left shrinkM-underline"></div>
<div id="child" class="showE flex-it">
<div>
<input type="email">
<div class="line-left shrinkM-underline"></div>
</div>
<span type="button" value="Remove Element" onClick="deleteInput('parent','child');" class="remove"> <strong>Remove</strong></span>
</div>
<input onclick="addInput('parent', 'child');" class="input-button" type="button" value="+Add another email">
</div>

Related

Is there anyway to clear a textarea without using an onclick function?

I want to achieve an automatic clear and display another value corresponds to new inputted data
This is my html code for input data and text area
function getInputValue(){
var integer = document.getElementById("integer").value;
var text = document.getElementById("answer");
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0){
text.append( i, "= ","fizzbuzz\n")
}
else if (i % 3 == 0){
text.append( i, "= ","fizz \n")
}
else if (i % 5 == 0){
text.append( i, "= ","buzz \n")
}
else{
text.append(i, "= \n")
}
}
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" onChange="getInputValue()" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
If you will try to run the snippet you can see that if you will change the value in the input tag the textarea will just stack all the outputs
Because you are using append() always it is always adding to content. Just clear it everytime onChange is triggered so it resets. You can use :
text.innerHTML = '';
function getInputValue(){
var integer = document.getElementById("integer").value;
var text = document.getElementById("answer");
text.innerHTML = '';
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0){
msg = i + "fizzbuzz";
text.append( i, "= ","fizzbuzz\n")
}
else if (i % 3 == 0){
text.append( i, "= ","fizz \n")
}
else if (i % 5 == 0){
text.append( i, "= ","buzz \n")
}
else{
text.append(i, "= \n")
}
}
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" onChange="getInputValue()" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
Here is the solution:
let inputEl = document.querySelector('#integer')
let answerEl = document.querySelector('#answer')
inputEl.addEventListener('input', () => {
answerEl.value = ''
if (inputEl.value !== '') {
answerEl.value = getInputValue()
}
})
function getInputValue() {
var integer = inputEl.value;
var text = '';
for (var i = 1; i <= integer; i++) {
if (i % 15 == 0) {
text += i +"= fizzbuzz\n"
} else if (i % 3 == 0) {
text += i +" = fizz \n"
} else if (i % 5 == 0) {
text += i +" = buzz \n"
} else {
text += i +" = \n"
}
}
return text
}
<div class="form-floating mb-3">
<input class="form-control" id="integer" type="text" placeholder="Input an Integer for N" data-sb-validations="required" />
<label for="integer">Input an Integer for N</label>
</div>
<div class="col-lg-6 form-floating answer mb-3">
<textarea disabled class="form-control" id="answer" type="text" placeholder="Answer" style="height: 20rem"></textarea>
</div>
For context.
Remove the inline onChange="getInputValue()"
Setup getInputValue as a return type
Check if input is empty else run function
As far as I can see here, there isn't a way to clear a textarea without using an onclick function.
Try using the oninput event instead of the onchange event.

How should I put limit inside for loop using if condition using javascript

My goal is that only 15 quantities of input elements can be accepted, once the user enters 16 it should say that only 15 input elements is allowed. However I don't know how will I do this. I tried putting condition inside for but it is not not working. I am a little bit confused on this
Here is my HTML code
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem"
required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
Here is my JS code
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
var parent = $(document.getElementById("parent"));
var value = $('#sel_control_num').val();
functionPopulate(parent);
if (isNaN(element)) {
return;
}
for (var i = 0; i < element; i++) {
if(should I do it here??){
}
value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text"
value="' + value +
'" class="form-control" name="get_Input_show[]" required>'
}
});
You can check if the element value is < 16 if yes then only add html else show error message.
Demo Code :
$(document).on('click', '#sb_add_ctrl', function() {
var element = $('#get_Elem').val();
var input;
//var value = $('#sel_control_num').val();
var value = 12;
//functionPopulate(parent);
if (isNaN(element)) {
return;
}
//check if elemnt value if < 16
if (element < 16) {
$("#parent").empty() //empty div
for (var i = 0; i < element; i++) {
/* value = value.replace(/(\d+)$/, function(match, element) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});*/
document.getElementById("parent").style.padding = "5px 0px 0px 0px";
document.getElementById("parent").innerHTML += '<br><input type="text" value = "' + value + '" class="form-control" name="get_Input_show[]" required>';
}
} else {
alert("only 15") //show error
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label> Quantity: </label>
<input class="form-control" name="quantity" type="number" id="get_Elem" required>
<br>
<input type="button" id="sb_add_ctrl" name="is_Sub" class="btn btn-
primary" value="Add Control Number">
</div>
<div class="form-group" name="parent" id="parent"></div>
There are two ways in which you can restrict it
You can use maxLength property of an input tag, which will restrict the user to input the 16th character.
You can keep checking the value in the input field and show error if the length is more than 15 character. To do this you can use onkeypress event on input, like
HTML
<input type="text" id="test" onkeypress="test()" />
JS:
<script>
function test() {
alert('Hi')
}
</script>

using single input textfield how to create functions like addidtion & substraction and display result in it?

i have created a calculator. Now i want to add which can do operation like addition and multiplication.
I'm new to Javascript please anyone can hep me out. I have provided my code here, i'm trying it with event handler. I wanna make it as simple as possible. Please someone help me thanks.
I'm trying this from week please do help with proper examples. Thanks a lot in advance.
if it is possible then please give me an example. Simply i wanna create two functions which can do operations of multiplication and addition using event handlers but not with the two text field my calculator contain one text field so only with one and displays in that same text field.
Refer code:
/*var temp;
function onload() {
temp = document.getElementById('new');
}
function ce(){
var tempo = temp.slice(0, -1);
document.getElementById("new").innerHTML = tempo;
}
*/
/*$(document).ready(function()
{
var temp = $('#new');
var ce = $('#ce');
ce.click(function() {
alert(temp.val());
});
}); */
//var input1=0;
//var input2=0;
// textInputVal= parseInt(document.getElementById('new').value);
function one() {
document.getElementById('new').value += 1;
}
function two() {
document.getElementById('new').value += 2;
}
function three() {
document.getElementById('new').value += 3;
}
function four() {
document.getElementById('new').value += 4;
}
function five() {
document.getElementById('new').value += 5;
}
function six() {
document.getElementById('new').value += 6;
}
function seven() {
document.getElementById('new').value += 7;
}
function eight() {
document.getElementById('new').value += 8;
}
function nine() {
document.getElementById('new').value += 9;
}
function zero() {
document.getElementById('new').value += 0;
}
function actionevent() {
var btn = document.getElementById("plu");
onclick.btn = function() {
textInputVal =
}
}
function ce() {
var textInputVal = 0,
temp = 0;
textInputVal = document.getElementById('new').value;
//console.log(textInputVal);
temp = textInputVal.slice(0, -1);
//console.log(temp);
document.getElementById('new').value = temp;
}
var demo = 0;
function mplus() {
var textInputVal = 0;
textInputVal = parseInt(document.getElementById('new').value);
console.log(textInputVal);
demo += textInputVal;
console.log(demo);
}
var temp = 0;
//var textInputval;
function plus() {
//var textInputval=0;
//var textInputval1=0;
var textInputval = parseInt(document.getElementById('new').value);
console.log(textInputval);
return textInputval;
//document.getElementById("new").value=" ";
//var temp = parseInt(document.getElementById('new').value);
//textInputval1 = parseInt(document.getElementById('new').value);
//temp = textInputval + textInputval1;
//console.log(temp);
//textInputval = $(this).val();
//$(this).val('');
//console.log(textInputval1);
}
function mminus() {
var textInputVal = 0;
textInputVal = parseInt(document.getElementById('new').value);
console.log(textInputVal);
demo -= textInputVal;
console.log(demo);
}
function mr() {
document.getElementById('new').value = demo;
}
/* $(document).ready (function(){
$("#clear_li").click(function(){
$("li:last").remove();
});
}); */
//var inputval=innerHTML - substring;
//var inputval=input.innerHTML;
//var sillyString = inputval.slice(0, -1);
<body>
<div id="cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" id="plu" value=" + " onclick="plus()" />
<br>
<input type="button" value=" 4 " onclick="four()" />
<input type="button" value=" 5 " onclick="five()" />
<input type="button" value=" 6 " onclick="six()" />
<input type="button" value=" - " onclick="minus()" />
<br>
<input type="button" value=" 7 " onclick="seven()" />
<input type="button" value=" 8 " onclick="eight()" />
<input type="button" value=" 9 " onclick="nine()" />
<input type="button" value=" * " onclick="multi()" />
<br>
<input type="button" value=" c " onclick="calculator.answer.value = ''" />
<input type="button" value=" 0 " onclick="zero()" />
<input type="button" value=" = " onclick="equal()" />
<input type="button" value=" / " onclick="div()" />
<br>
<input type="button" value="CE" onclick="ce()" />
<input type="button" value="M+" onclick="mplus()" />
<input type="button" value="M-" onclick="mminus()" />
<input type="button" value="mr" onclick="mr()" />
</form>
</div>
</body>
There were few errors in your code I changed them.I have only created for addition,subtraction,multiplication and division.Rest of them you can follow the same way I have done and get the result.
FIDDLE
Here is the code.
var one = function() {
document.getElementById('new').value += 1;
}
var two = function() {
document.getElementById('new').value += 2;
}
var three = function() {
document.getElementById('new').value += 3;
}
var four = function() {
document.getElementById('new').value += 4;
}
var five = function() {
document.getElementById('new').value += 5;
}
var six = function() {
document.getElementById('new').value += 6;
}
var seven = function() {
document.getElementById('new').value += 7;
}
var one = function() {
document.getElementById('new').value += 1;
}
var two = function() {
document.getElementById('new').value += 2;
}
var three = function() {
document.getElementById('new').value += 3;
}
var four = function() {
document.getElementById('new').value += 4;
}
var five = function() {
document.getElementById('new').value += 5;
}
var six = function() {
document.getElementById('new').value += 6;
}
var seven = function() {
document.getElementById('new').value += 7;
}
var eight = function() {
document.getElementById('new').value += 8;
}
var nine = function() {
document.getElementById('new').value += 9;
}
var zero = function() {
document.getElementById('new').value += 0;
}
var plus = function() {
document.getElementById('new').value += "+";
}
var minus = function() {
document.getElementById('new').value += "-";
}
var multi = function() {
document.getElementById('new').value += "*";
}
var div = function() {
document.getElementById('new').value += "/";
}
var equal = function() {
document.getElementById('new').value = eval(document.getElementById('new').value);
}
<body>
<div id="cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" id="plu" value=" + " onclick="plus()" />
<br>
<input type="button" value=" 4 " onclick="four()" />
<input type="button" value=" 5 " onclick="five()" />
<input type="button" value=" 6 " onclick="six()" />
<input type="button" value=" - " onclick="minus()" />
<br>
<input type="button" value=" 7 " onclick="seven()" />
<input type="button" value=" 8 " onclick="eight()" />
<input type="button" value=" 9 " onclick="nine()" />
<input type="button" value=" * " onclick="multi()" />
<br>
<input type="button" value=" c " onclick="calculator.answer.value = ''" />
<input type="button" value=" 0 " onclick="zero()" />
<input type="button" value=" = " onclick="equal()" />
<input type="button" value=" / " onclick="div()" />
</form>
</div>
</body>
I am not sure why are you looking for eventListeners however if you want to do by that method then in HTML you have to assign ID to each button and remove onClick event.
<input type="button" value=" 1 id="one" />
And in JavaScript you have to write as follows for each button id
document.getElementById("one").addEventListener("click", one_func);
var one_func= function() {
document.getElementById('new').value += 1;
}
As you see this code is longer then the previous and is not a good practice.So I recommend you to do by the method I have done before.

Can not create multiple text area after deleting using Javascript/Jquery

I need some help. I am creating multiple texareas using + button and deleting using - button but I am running into some issues.
This is my code:
<div class="col-md-3">
<div class="form-group">
<label for="ques">No of questions</label>
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="" type="text">
<div id="err_msg_name" style="font-size:12px; color:#FF0000; text-align: center;"></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Questions</label>
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
</div>
</div>
<div id="container">
<div class="col-md-4">
<div class="form-group">
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
</div>
</div>
<script>
function addQuestionField() {
var get = $("#ques").val();
console.log('ques', get);
for (var i = 1; i < get; i++) {
$('#container').append('<div class="col-md-4 dyn"><div class="form-group"><textarea class="form-control" name="questions' + i + '" id="questions' + i + '" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>')
}
}
function deleteQuestionField() {
var textareas = $('#container .dyn');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
</script>
Basically what I need to do is to add new textareas with a unique id, and ordered by this id, to the page according to the number entered in the first textbox. One Default textarea should always be in the page.
So for example if I entered 3 in the textbox, 2 textareas should be added, if I enter 5- 4 textareas should be added etc.
But the above code is not working properly: For example I entered 2 in the first textbox and clicked on the + button- 1 textarea is being created and added to the page (what is good), the same thing in the second time, but on the third time it's not working anymore, an extra textbox is being created.
(For example: I entered the 3 digit, and 3 new textareas are being added + the default one = 4 ,but I only need 3- as entered in the textbox)
My full plunker code here.
As the OP claimed he also needs to keep the id and the name of the textareas serially.
Before adding the new textarea, we remove all the textareas that were added before.
function addQuestionField() {
var get = $("#ques").val();
var count=$('textarea').length -1 ;
for (var i = 0; i < count; i++) {
$('#container').find('.col-md-4').last().remove();
}
for (var i = 1; i < get; i++) {
$('#container').append('<div class="col-md-4 dyn"><div class="form-group"><textarea class="form-control" name="questions' + i + '" id="questions' + i + '" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>')
}
}
I also noticed that it messed up the deleteQuestionField function, you should correct it as bellow:
function deleteQuestionField() {
var textareas = $('textarea');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
A working plunker code here.
Make a small change, It will add same text area mention in the input field (including the existing one) .
function addQuestionField() {
var get = $("#ques").val();
var noOfTextArea = $('textarea').length;
if(get > noOfTextArea){
get = get - noOfTextArea;
for (var i = 1; i <= get; i++) {
$('#container').append('<div class="col-md-4 dyn"><div class="form-group"><textarea class="form-control" name="questions' + i + '" id="questions' + i + '" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>')
}
}else{
get = noOfTextArea - get;
for (var i = 1; i <= get; i++) {
$('#container').find('.col-md-4').last().remove();
}
}
}
you are using for loop by starting index at 1 so you should use "<="
for (var i = 1; i <=get; i++) {
$('#container').append('<div class="col-md-4 dyn"><div class="form-group"><textarea class="form-control" name="questions' + i + '" id="questions' + i + '" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>')
}
Your Code is perfect.The reason that that more boxes are getting created is because in your code there is already a form-area present,in addition to that one text area the number of text areas you have specified gets created.
So for example there is already one text area present on load of the screen,when you enter 5 into the text box for creation.5+1 text areas are seen on the screen.
If you remove the existing text area you will be able to see the exact number of text areas you specified on the screen.
Furthermore if your change the limit to <=limit then <=5 will be created else else less than 5 that is 4 will be created
Try with below code....
function addQuestionField() {
var get = $("#ques").val();
var textlen = $('textarea').length;
get = get - textlen;
//console.log('ques', get);
for (var i = 0; i < get; i++) {
$('#container').append('<div class=col-md-4 dyn><div class=form-group><textarea class=form-control name=questions"+i+" id=questions"+i+" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>')
}
}
function deleteQuestionField() {
var textareas = $('textarea');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
make some way to get new id always,
var idGernator = (function (){
var id = 10;
return function(){
return id++;
}
})();
function addQuestionField() {
var get = $("#ques").val();
// console.log('ques', get);
// var textareas = $('#container .dyn');
// console.log('text',textareas);
// var get = $("#ques").val() - 1;
for (var i = 1; i <= get; i++) {
var id = idGernator();
$('#container').append('<div class="col-md-4 dyn"><div class="form-group"><textarea class="form-control" name="questions' + id + '" id="questions' + id + '" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea></div></div>');
console.log("new id: "+ id);
}
}
function deleteQuestionField() {
var textareas = $('#container .dyn');
if (textareas.length !== 0) {
textareas.last().remove();
$('#ques').val(textareas.length - 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello</h1>
<div class="col-md-3">
<div class="form-group">
<label for="ques">No of questions</label>
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="" type="text">
<div id="err_msg_name" style="font-size:12px; color:#FF0000; text-align: center;"></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="form-group">
<label>Questions</label>
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();">
<input type="button" style="line-height:13px; margin-right:2px;" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>
</div>
</div>
<div id="container">
<div class="col-md-4">
<div class="form-group">
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
</div>
</div>

jQuery Dynamic Add Form Field, Remove Form Field

Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
Thanks
Try:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
DEMO FIDDLE
In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.
var counter = 0
jQuery(function () {
$(".newDog").click(function(){
counter ++;
if (counter < 4) {
var elem = $("<input/>",{
type: "text",
name: `dogname${counter}`
});
} else {
alert("You can only add 4 Dog Names")
}
var removeLink = $("<span/>").html("X").click(function(){
$(elem).remove();
$(this).remove();
counter --;
});
$(".dogname-inputs").append(elem).append(removeLink);
});
})
Full credit as mentioned to https://stackoverflow.com/users/714969/kevin-bowersox

Categories