I have a button that creates 4 input elements inside a DIV after click:
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+i+"' type='text'><br>");
}
});
</script>
But the problem is I want input id number continues the enumeration (like this example) instead of return to zero:
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text">
...and continues
</div>
How can I fix it?
You can check the id of the last input. Here I am calculating start and end of for loop based on the total number of elements in #container.
var num = 4;
$(".check").click(function() {
var start = $("#content input").length;
var end = start + num;
for (i = start; i < end; i++) {
var id = 'input' + i;
$("#content").append("<input id='"+id+"' type='text' value='"+id+"'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
PS: Here input value is just to demonstrate the id setting to input.
You need some kind of global variable here, or use that simple one:
var getID = (function () {
var id = 0;
return function () { return ++id; }
})();
So whenever you call getID() the »internal« id will be incremented, so each call will yield an new ID.
$(".check").click(function() {
for(var i = 0; i < 4; i++) {
$('<input type="text">') //create a new input
.attr('id', 'input' + $('#content input').length) //id based on number of inputs
.appendTo('#content'); //append it to the container
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>
<button class="check">Check</button>
If you're asking how to have a stack of elements to begin with, and then continue enumeration from there, you simply need to set a variable to the ID of the latest element.
All you need to do is count the number of elements. This can be done with a combination of .querySelectorAll() and .length.
Then simply have your loop start at this new value instead of 0.
This can be seen in the following:
var total_desired = 20;
var start = document.querySelectorAll('#content > input').length;
console.log(start + " elements to start with");
$(".check").click(function() {
for (i = start; i < total_desired; i++) {
$("#content").append("<input id='input" + i + "' type='text'><br>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="check">Check</button>
<div id="content">
<input id="input0" type="text">
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
<input id="input7" type="text"> ...and continues
</div>
Having said that, it's unlikely that you actually need simultaneous ID <input> elements, and you may benefit from classes instead.
You can create this object:
var MyId = {
a: 0,
toString() {
return this.a++;
}
}
And concatenate it into the string. Automatically will increase the counter.
<div id="content"></div>
<button class="check">Check</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var GetID = {
a: 0,
toString() {
return this.a++;
}
}
var num = 4;
$(".check").click(function(){
for(i=0; i<num;i++){
$("#content").append("<input id='input"+GetID+"' type='text'><br>");
}
});
</script>
Related
this is my code but add button is coming of first field but i want that whenever a new input field came the add button shift next to the new input field.
function add(){
var new_chq_no = parseInt($('#total_chq').val())+1;
var new_input="<input type='text' id='new_"+new_chq_no+"'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no)
}
function remove(){
var last_chq_no = $('#total_chq').val();
if(last_chq_no>1){
$('#new_'+last_chq_no).remove();
$('#total_chq').val(last_chq_no-1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
Try This
var new_id = 0;
function add() {
new_id += 1;
var inp_div = document.getElementById("inputs");
var new_inp = document.createElement("input");
new_inp.setAttribute("id", new_id);
inp_div.appendChild(new_inp);
}
function remove() {
if (new_id >= 1) {
document.getElementById(new_id).remove();
new_id -= 1;
}
}
<div id="inputs">
<input type="text">
</div>
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
Try wrapping the button and the input in a div with css attribute display: inline-block
HTML code:
<input type='text' id='element1' />
<button id='addNew'>Add New</button>
I want each time on clicking the button a new input is created but with number increasing like :
<input type='text' id='element2' />
<input type='text' id='element3' />
..
..
<input type='text' id='element8' />
Until number 8 , each time I click the button an input is created with increased number.
$('#addNew').click(function(){
//Create new element if it's not greater than 8
});
Assuming some inputs exist in the current DOM:
The function count increments +1 in every call.
The function count starts with the existing inputs $('[type="text"]').length.
var count = function() {
return (count.i = (count.i || $('[type="text"]').length) + 1);
}
$('#addNew').click(function(){
var i = count();
if (i > 8) return;
$('body').append($(`<input type='text' id='element${i}' value="${i}"/><p>`));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='element1' value="1" />
<p>
<button id='addNew'>Add New</button>
$('#addNew').click((function(){
var count = 0;
return function() {
if(count < 8) {
//Create new element
}
count++
}
})());
See JavaScript closures: https://www.w3schools.com/js/js_function_closures.asp
I wouldn't recomment creating id's like this.
var count =1;
$('#addNew').click(function(){
if(count<8){
$("<input type='text' id='element"+(count+1)+"'/>").insertAfter('#element'+(count++));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='element1' />
<button id='addNew'>Add New</button>
$('#addNew').click(function(){
var last_element = $(document).find('.element').last();
var new_element = last_element.clone();
var new_element_id = 'element' +(parseInt(last_element.attr('id').replace('element', ''))+1);
new_element.
attr('id', new_element_id).
insertAfter(last_element);
//for display purposes
new_element.val(new_element_id);
});
.element{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="element1" class="element" />
<button type="button" id="addNew">Add New</button>
Try this one:
HTML:
<ul class="jsEleList">
<li><input type='text' id='element1' /></li>
</ul>
<button class="jsAddNewBtn">Add New</button>
JS:
$(document).ready(function(){
var index = 2;
$(".jsAddNewBtn").on('click', function(){
if(index <= 8) {
var data = $(".jsEleList li").first().find('input').clone();
data.attr('id', 'element' + index);
var li = $('<li>').append(data);
$(".jsEleList").append(li);
}
index++;
});
});
Also follow the naming conventions of class names that specifically used for only js operations
Hope this may help you.
Please help me figure out why only the last input id gets its value added to the input id= #attr3 with keyup.
I need both inputs in the div to have their values put into the input outside the div separated with a comma(,). i made a fiddle https://jsfiddle.net/dc6v6gjd/1/. Thanks
<div id ="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
$(document).ready(function () {
var text = $("#candy :input").map(function () {
return this.id;
}).get();
var attr = [];
for (i=0; i<text.length; i++) {
attr.push('#'+ text[i]);
}
var mat = attr.join(", ");
$(mat).keyup(function(){
update();
function update() {
attr.forEach(function(index, i){
// alert(i);
$("#attr3").val( $(attr[i]).val() + "," );
});
}
});
});
The reason is you're overriding the value of attr3 on each iteration of forEach. You could instead use join to get the value.
e.g.
function update() {
var val = attr
.map(function(a) {
return $(a).val();
})
.join(",");
$("#attr3").val(val);
}
That being said I'd probably go with a simpler solution like this.
// set the keyup event handler and add all inputs to an array.
var inputs = $("#candy :input").keyup(function() {
update();
}).get();
// read all input values into comma separated string and update attr3
function update() {
var val = inputs.map(function(i) {
return $(i).val();
}).join(",");
$("#attr3").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attr3" name="username" value="">
Update: Support dynamically added inputs.
$(document).on("keyup", "#candy :input", function() {
update();
});
function update() {
var val = $("#candy :input").get().map(function(i) {
return $(i).val();
}).join(",");
$("#attrFinal").val(val);
}
var count = 3;
$("#add").click(function() {
$("#candy").append("<input type='text' id='attr" + count++ + "' name='emailAddress' />");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="candy">
<input type="text" id="attr1" name="emailAddress" value="">
<input type="text" id="attr2" name="emailAddress" value="">
</div>
<input type="text" id="attrFinal" name="username" value="">
<button id="add">Add New</button>
I try to loop over few input elements in order to get each value, but for some reason I only get the last one:
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>
<script>
function loop() {
var element = document.querySelectorAll('[data-loop="true"]');
for(var i = 0; i < element.length; i++) {
console.log(element[i].length);
// or:
// document.getElementById('output').innerHTML = element[i].value + '<br>';
}
}
</script>
The console shows undefined and when I try to output the values, I only get it from the last element and not from all of them. What am I doing wrong?
Thank you very much (and please excuse my english)
You are trying to get the length of the element itself:
console.log(element[i].length);
Elements don't have a length.
I suspect you are trying to get the length of the value of the elements:
console.log(element[i].value.length);
function loop() {
// elements will be a "node list" containing any/all elements
// that match the query.
var elements = document.querySelectorAll('[data-loop="true"]');
// Because it is a node list, which is an array-like object,
// it has a "length" property:
console.log("There were " + elements.length + " elements found.");
// ...And, it can be looped through
for(var i = 0; i < elements.length; i++) {
// It's contained elements are indexed and when you do that,
// you may access properties of the elements themselves
console.log(elements[i].value);
// or:
document.getElementById('output').innerHTML += elements[i].value + '<br>';
}
}
<p>Type some text in the textboxes and then click the button:</p>
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<input type="text" name="input-loop" data-loop="true" />
<button type="button" onclick="loop()">loop</button>
<div id="output"></div>
try to console.log(element[i]); This is because here element will be a collection of DOM elements.
There is no length property for these elements.
Since they are input and if you want to get their value you need to log
element[i].value
What am I doing wrong?
console.log(element[i].length);
element[i] refers to an HTMLInputElement. It and non of its parent classes have a length property. Assuming you want to display the length of the value of the input element, the following would work.
var output = document.getElementById('output');
function loop() {
var element = document.querySelectorAll('[data-loop="true"]');
element.forEach( (e) => {
output.innerHTML += `${e.value}: ${e.value.length}<br>`;
});
}
function clearOutput(){
output.innerHTML = '';
}
<input type="text" name="input-loop" data-loop="true" value="one" />
<input type="text" name="input-loop" data-loop="true" value="two" />
<input type="text" name="input-loop" data-loop="true" value="three" />
<button type="button" onclick="loop()">loop</button>
<button type="button" onclick="clearOutput()">clear</button>
<div id="output"></div>
I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle