For Loop Dependent on Number Input - javascript

I'm trying to repeat a div, the number of times dependent on the number chosen in a number input field, but currently when the number input is changed the values are being multiplied. So if you go from 2 to 3 it repeats the div 6 times instead of just 3. How can I reset the loop so it's using only the current number?
http://jsfiddle.net/deliciouslycheesy/6rb94mry/
$('#numRepeat').on('change keyup input', function () {
var el = $(".repeat-me").get(0);
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();

You need to remove the ones that were added before:
$('#numRepeat').bind('change keyup input', function () {
var el = $(".repeat-me").get(0);
$(".repeat-me:not(:first)").remove();
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="2"/>
<div class="repeat-me">REPEAT</div>
JSFiddle

I'm not sure why you're using three event change keyup input, just input event will detect changes inside input field, check the Updated fiddle.
I suggest to separate the model of repeated div from the result, i think that will make code more clear, and because you're using JQuery you can replace cloneNode() by clone().
Hope this helps.
$('#numRepeat').on('input', function () {
var el = $("#model-div .repeat-me");
var numRepeat = $(this).val();
$('#result-div').empty(); //Clear the result div
for(var i = 0 ; i < numRepeat ; i++)
{
$('#result-div').append( $(el).clone(true) );
}
})
#model-div{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="0"/>
<div id="model-div">
<div class="repeat-me">REPEAT</div>
</div>
<div id="result-div"></div>

Related

How do I edit javascript variables as given by user input?

I want to display an array of numbers, after that if he users wishes to change any of the numbers in array then he/she should write the desired value in its place and click submit button the array gets updated and display the updated array.
I have tried this till now, and gone through numerous articles to find a solution but i couldn't find one which fits here.
This is what my code looks like, it is a bit long but I dont know how much code is adequate so this is it.. please help me get this.
making grid editable
<style>
#container{
display:grid;
grid-template-columns: repeat(9, 8%);
margin-left: 35%;
margin-right:25%;
margin-top:10%;
}
</style>
<body style="background-color:grey">
<div id='container'>
</div>
<input id="someInput" type="text" value=<p id="output"></p>>
<input type="button" value="submit" onClick="doStuff()">
</body>
<script>
var myContainer = document.getElementById('container')
grid=[0,1,4,6,3,0,9,3,2];
for(var i=0;i<9;i++){
var myInput = document.createElement('input')
//we want to add position of an input box as id
myInput.id= `${i}`
var num=grid[i];
myInput.value=num;
myContainer.appendChild(myInput)
}
var x = document.createElement("BUTTON");
function doStuff(){
var nameElement = document.getElementById("someInput");
a = nameElement.value
b = nameElement.id
new_grid=[];
for(var j=0;j<9;j++){
if(j==b){
new_grid[j]=a;
}
else{
new_grid[j]=grid[j];
}
}
for(var i=0;i<9;i++){
var myInput = document.createElement('input')
//we want to add position of an input box as id
myInput.id= `${i}`
var num=new_grid[i];
myInput.value=num;
myContainer.appendChild(myInput)
}
}
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("output").innerHTML=grid[4];
}
</script>
'''
then I tried to add a input box so that i can show the array numbers in value attribute of it and when users updates it and clicks submit button it gets updated but then i wasn't able to get array numbers in value attribute of input tag.
This will update your grid array values with the user inputted values on button click.
var myContainer = document.getElementById('container');
grid = [0,1,4,6,3,0,9,3,2];
for(var i=0; i < grid.length; i++){
var myInput = document.createElement('input')
//we want to add position of an input box as id
myInput.id = `${i}`
myInput.value = grid[i];
myContainer.appendChild(myInput);
}
var x = document.createElement("BUTTON");
x.textContent = "UPDATE";
myContainer.appendChild(x);
x.addEventListener("click", UpdateGridFromUserInput, false);
function UpdateGridFromUserInput() {
var allinputs = document.getElementById('container').getElementsByTagName('input');
for(var j = 0; j < allinputs.length; j++) {
grid[j] = allinputs[j].value;
}
console.log(grid);
}
<div id="container">
</div>
Here's an example. I just use input number fields. You can set the min max and add an onChange event if you want to change the value of the nums array.
const nums = [1, 2, 3, 4, 5];
const container = document.querySelector(".container");
nums.forEach(num => {
const numElm = document.createElement("input");
numElm.classList.add("number");
numElm.type = "number";
numElm.min = 1;
numElm.max = 9;
numElm.value = num;
container.appendChild(numElm);
});
.container {
display: flex;
justify-content: space-between;
}
.number {
padding: .5rem;
width: 2rem;
text-align: center;
border: 2px solid grey;
border-radius: 10px;
}
<div>
<p>Selected numbers</p>
<div class="container" />
</div>
I think you have got relevant solutions already, but I would like to show you "little another way" which save a few rows of code and it is more optimal with larger arrays.
Instead of the iterating array when you want to change a single number, you can add an event listener to it. You save an ID to the element by the index of the array, so it is easy to approach the actual position in the array.
First thing first, I would like to comment on a few things in your code, which could be better (we all learn!)
for(var i=0;i<9;i++){var myInput = document.createElement('input') ...
You want to create an input for each element in the array. As a programmer, you know that there will be 9 elements, but (as a programmer :)) you don't always want to remember and count how many elements the array has. It is better to use grid.length which returns the actual length of the array.
function doStuff(){...}
Always name your functions as what they are really doing. It really helps!
var nameElement = document.getElementById("someInput");
a = nameElement.value
b = nameElement.id
Always name your properties as what they actually mean. You could use "input", "inputValue", "inputId". Helps too :)
In doStuff() function, you are creating other inputs again. I think it is not really necessary when you have already created them.
Second thing second let's look at how it looks like as I described before.
Here is the code (use and learn ES6, it's better, trust me):
let array = [0, 1, 4, 6, 3, 0, 9, 3, 2];
let container = document.getElementById("container");
let output = document.getElementById("arrayResult");
output.innerHTML = array;
//create inputs for the array
for (let i = 0; i < array.length; i++) {
let inputElement = document.createElement("input");
inputElement.type = "number";
inputElement.id = i;
inputElement.value = array[I];
//if an user change the value, update the array at its position
inputElement.addEventListener("input", () => {
let id = inputElement.id;
array[id] = inputElement.value;
})
container.appendChild(inputElement);
}
//create submit button
let submit = document.createElement("input");
submit.type = "submit";
submit.value = "Change";
container.appendChild(submit);
//update output
submit.addEventListener("click", () => {
output.innerHTML = array;
});
<div id="container">
</div>
<div>
<label>Result:</label>
<label id="arrayResult"></label>
</div>

JQuery Append Text Dynamically by Onblur input value

When i give input (1) then its successfully append text. But when i erase then input value and again give input(2) then its increasing with previous value(1+2=3). Where loop count previous and present value
$(document).ready(function(){
var i=0;
$("#flatcount").blur(function() {
var floor = (this).value;
for(i=1;i<=floor;i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});
You need to empty the element.before append like $('#row').empty()
$(document).ready(function() {
var i = 0;
$("#flatcount").blur(function() {
var floor = $(this).val();
$('#row').empty() //empty
for (i = 1; i <= floor; i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="flatcount">
<p id="row"></p>
use this code i think it will work
$(document).ready(function(){
var i=0;
$("#flatcount").blur(function() {
$("#row").empty();
var floor = (this).value;
for(i=1;i<=floor;i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});

Javascript Add Variable and change event

I have the following code
$(document).ready(function () {
$('#big_1').change(function () {
var bigAmt = document.getElementById("big_1").value
+ document.getElementById("big_2").value
+ document.getElementById("big_3").value
+ document.getElementById("big_4").value
+ document.getElementById("big_5").value
+ document.getElementById("big_6").value
+ document.getElementById("big_7").value
+ document.getElementById("big_8").value
+ document.getElementById("big_9").value
+ document.getElementById("big_10").value;
var elem = document.getElementById("totalBig");
elem.value = bigAmt;
});
});
I actually wanted to add the value of big_1 to big_10 on input text value change of "big_1 to big_10" either 1 of the textfield change its value, this should be invoke.
as of now i only run on big_1 change event.
I get an javascript error by adding this way, I think the way I add them up is quite messy.
What should I do to change my code so I can sum up
big_1 to big_10 textfield value, and on change of big_1 to big_10(any of them), it will invoke this and change span id="totalBig" to the value of their sum (big_1 add until big_10)
Below is my edited extra code:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_1" id="big_1" size="6">
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control" name="big_2" id="big_2" size="6">
all the way until big_10
I wanna on change value of any of this big_Identifier(1-10), it will sum it up and change my
<div class="well">
Total Big: <span id="totalbig">0</span> </span>
</div>
I tried the
<script type="text/javascript">
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
$('.big').change(function() {
var bigAmt = "";
$('.big').each(function () {
bigAmt += $(this).val();
})
var elem = document.getElementById("totalBig");
alert(bigAmt);
elem.value = bigAmt;
});
});
</script>
It doesn't run any alert when any of the big_ value was changed.
It would be much better if you added a big class to every single <input id="big_NUMBER">. Then you could do this:
$(document).ready(function() {
$('.big').change(function() {
var bigAmt = 0;
$('.big').each(function () {
bigAmt += Number($(this).val());
})
$("#totalBig").val(bigAmt);
});
});
That's much cleaner and easier to understand than what you had.
In order for this to work, you'll need to add a class to all your inputs:
<input type="number" data-bv-digits-message="true" data-bv-threshold="1" min="0" class="form-control big" name="big_2" id="big_2" size="6"><!-- Notice the big class-->
This is the best way to group all your inputs. They are all related, so they should share a classes. You should not be calling multiple ids for functionality that's so similar.
If you are using jquery, use it properly, it'll make your life a lot easier.
This will work for you in your case exactly
$(document).ready(function() {
$('[id^="big"').change(function(){
var total = (+$('#totalBig').val());
var currentVal = (+$(this).val());
total += currentVal;
$('#totalBig').val(total)
})
});
DEMO
Add class="bigs" to all inputs and then try this:
$(document).ready(function () {
var intTotalBig;
$('.bigs').change(function () {
intTotalBig = 0;
$('.bigs').each(function(){
$thisVal = $(this).val();
if ($.isNumeric($thisVal)){
intTotalBig += parseInt($thisVal, 10);
}
});
$("#totalBig").val(intTotalBig);
});
});
This code check all inputs on every change and sum all of them that has a number value and ignore empty or no number values.
Check JSFiddle Demo
You monitor the change event on all the input type text as follows:
$('input:text').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
Or...
If you want add the monitor to any selected text boxes then you will have to add any css class to those selected text boxes and then monitor those text boxes through class as follows:
$('.yourclass').change(
function () {
alert('text changed of any text box.');
//You can doo your code here.
});
this change event will fire when you lose focus from the text box after changing the text....
but if you want with loosing the focus (means if you want to update the count while typing) then you should use keyup event as stated in this answer.
$(document).ready(function() {
$('#big_1').change(function() {
var divArray = ["big_1","big_2","big_3","big_4","big_5","big_6","big_7","big_8","big_9","big_9","big_10"];
var bigAmt = 0;
for(var i = 0, n = divArray.length;i<n;i++)
{
bigAmt += parseInt($("#" + divArray[i]).val(),10);
}
$("#totalBig").val(bigAmt);
});
});
Try the above, it should do what you're looking for. You'll probably want to use parseInt as well incase the input isn't of "number" type.
*edit, forgot the # for the id.
*edit, removed comment about considering using jquery functions because people are really sensitive.

Get total of all data attribute values

I am dynamically loading some of the content within my page and would like to get a total of all the data-attributes.
First the elements are cloned and appended
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
});
Then I have written a function that should get the totals
function chipsBet() {
var redchip = $('.chipPlacement .chipValue.r').data() || 0;
var bluechip = $('.chipPlacement .chipValue.b').data() || 0;
var orangechip = $('.chipPlacement .chipValue.o').data() || 0;
var total = redchip.chipValue + bluechip.chipValue + orangechip.chipValue;
return total;
}
Before I append the elements the HTML looks like
<div class="chipPlacement"></div>
and once appended the HTML structure is
<div class="chipPlacement">
<div class="chip red">
<div class="chipValue r" data-chip-value="1">1</div>
</div>
</div>
I need to listen for the DOM structure the change and then fire the chipsBet() function, but I'm not sure how to get this to work. I can't use .on('change') as that only applies to input, textarea and select.
I have tried firing the chipsBet function within the .chip.on('click') but I get NaN returned.
How can I get the data-attribute-values for the new elements in the DOM?
If you don't have a blue or orange chip, you're effectively trying to get .chipValue from 0 which is undefined and adding it to another number gives you NaN.
You can simply iterate over all .chipValue elements within the placement element like so:
function chipsBet()
{
var total = 0;
$('.chipPlacement .chipValue').each(function() {
total += $(this).data('chipValue');
});
return total;
}
Nevermind, you altered your initial question.. carrying on.
<div class='chipPlacement'>
<div class='chip red'>
<div class='chipValue' data-chip-value='1'></div>
</div>
</div>
Then to read your data attributes, you could do something like this.
$('.chip').on('click', function () {
$(this).clone().appendTo('.chipPlacement');
chipsBet();
});
function chipsBet() {
var redchipVal = parseInt($('.chipValue .r').data('chip-value')) || 0;
var bluechipVal = parseInt($('.chipValue .b').data('chip-value')) || 0;
var orangechipVal = parseInt($('.chipValue .o').data('chip-value')) || 0;
var total = redchipVal + bluechipVal + orangechipVal;
return total;
}
I think you want something like bellow. It will call the function every time any change will in div .chipPlacement.
$('.chipPlacement').bind("DOMSubtreeModified",function(){
console.log('Div modified');
});
You can say for your problem
$('.chipPlacement').bind("DOMSubtreeModified",function(){
chipsBet();
});
DEMO

Change div on input (live & pass variable)

I want a div that shows your input, but for example * 2.
I also want it to happen as you type. So it has to be 'live'.
I found a lot of 'on keyup' jquery functions but I need to change the 'variable' that is typed in the input field.
So for example:
<input id="input" /> (types 4)
<div class="showinputhere"> (shows 8) </div>
How do I do this, it has to happen immediately when you type.
Use this
$(document).ready(function()
$('input').keyup(function(){
$('.showinputhere').html(parseInt($(this).val(),10) *2);
});
});
JSFiddle -> http://jsfiddle.net/gLExt/
try the following code:
<script>
function calVal(inputVal){
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
div.innerHTML = inputVal * 2 == 0 ? "" : inputVal * 2;
}
</script>
And call the function "onkeyup" event of input like this:
<input id="input" onkeyup="calVal(this.value);"/>
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("change", function() {
div.innerHTML = this.value * 2;
})
That's untested, but might work.
Here's an edited version using keyup, because I've been informed that change does not auto-update.
var input = document.getElementById("input");
var div = document.getElementsByClassName("showinputhere");
div = div[0];
input.addEventListener("keyup", function() {
div.innerHTML = this.value * 2;
})

Categories