increment a variable with javascript - javascript

I have made this script, but there is a problem.
When i click addbutton the variable on console log recieve the update (1, 2 ,3 ,4) for every click.
But var fieldHTML remains 1 forever, why?
var a = 1;
$(addButton).click(function(){ //Once add button is clicked
a++;
console.log(a);
});
var fieldHTML = a;

Because var fieldHTML = a; copies the value of a to fieldHTML.
It doesn't create a reference.
Changing the value of a (after you've set the value of fieldHTML) won't change the value of fieldHTML.

You need to apply an id or class to the selector, wrap it into document ready, and also pass the new value of "a" to a function that can then manipulate the fieldHTML value. Check out the snippet note that I used alerts to demonstrate the increasing count rather thanconsole.log - simply because its in the snippet.
$(document).ready(function(){
var a = 1;
$('#addButton').click(function(){ //Once add button is clicked
a++;
alert("a = " + a);
update_fieldHTML(a);
});
})
function update_fieldHTML(value){
var fieldHTML = value;
alert("fieldHTML =" + fieldHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addButton">Click Me</button>

var addButton = $("#btn");
var viewButton = $("#btn-2");
var setButton = $("#btn-3");
var a = 1;
var fieldHTML = a; // on load, addign a value to fieldHTML variable | fieldHTML = 1
$(addButton).click(function() { //Inc by 1
a++;
console.log('a : '+a);
});
$(viewButton).click(function() { //Show fieldHTML value in console
console.log('fieldHTML : '+fieldHTML);
});
$(setButton).click(function() { // reassign a value to the fieldHTML variable | on click event
fieldHTML = a;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn'>Inc a</button>
<button id='btn-3'>Set fieldHTML</button>
<button id='btn-2'>View fieldHTML</button>

var addButton = $("#btn");
var viewButton = $("#btn-2");
var a = 1;
var fieldHTML = a;
$(addButton).click(function() {
fieldHTML = increment();
alert('a : ' + a);
});
$(viewButton).click(function() {
alert('fieldHTML : '+fieldHTML);
});
function increment(){
return ++a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn'>Inc a</button>
<button id='btn-2'>View fieldHTML</button>

Related

Real time update of interval timer with the use of a slider

I am trying to make it so i can change the value of the interval timer in real time with the use of a slider. I managed to make it so i can show the current value of the slider. Can i use the same variable as the one that i am using in textbox or do i have to create a new one? Pretty sure that the solution is very simple. Appreciate any help. Thanks!
jsfiddle
https://jsfiddle.net/8bdycskp/32/
var quotes = [
"X",
"Y",
"Z"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
let intervalval = setInterval(quoteTimer, interval);
$("#button").on("click", function() {
let v = parseInt($("#interval").val());
clearTimeout(intervalval);
intervalval = setInterval(quoteTimer, v);
})
});
var p = document.getElementById("interval2"),
res = document.getElementById("result");
p.addEventListener("input", function() {
res.innerHTML = p.value + "ms";
}, false);
<body>
<center></br>
<input type="text" name="interval" id="interval" value="" style="height:50px; width:500px; font-size: 25px" placeholder="Czas w ms" /></br></br>
1ms<input name="interval2" id="interval2" type="range" min="1" max="1000" value="" /> 1000ms</br>
<p id="result"></p>
<input type="submit" name="button" id="button" value="Rozpocznij" style="padding: 10px 50px; font-size: 25px"/> </center>
<div class="container">
<h1></h1>
</div>
</body>
It's very simple. You just have to remove your input text and your button and add a range input. Then you bind the "onchange" event to a listener and execute the same function you have in your "click" event
Here it is a jsfiddle with the code: https://jsfiddle.net/8bdycskp/56/
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("range").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
let intervalval = setInterval(quoteTimer, interval);
$("#range").on("change", function() {
let v = parseInt($("#range").val());
clearTimeout(intervalval);
intervalval = setInterval(quoteTimer, v);
})
});
<body>
<input type="range" name="range" id="range" value="1000" min="100" max="5000" step="10"/>
<div class="container">
<h1></h1>
</div>
</body>
Just add an event listener to detect changes and then update your interval
var intervalval = '';
function slider() {
clearTimeout(intervalval);
var v = parseInt($("#interval").val());
intervalval = setInterval(quoteTimer, v);
}
//Listen for changes
$(document).on('input', '#interval', function() {
slider();
})
See working fiddle with range slider

Changing data-value when Clicked not working

value when clicked tried these codes but when i inspect the elements the value is not changing
<div id="foo" data-value="3">Click Here</div>
This is the JavaScript
$("#foo").on('click', function(){
var foo1 = $(this);
var c = foo1.attr('data-value');
var sum = parseInt(c) + parseInt(3);
$("#foo").data("data-value", sum);
});
To set the attribute value you can use attr, like you get the attribute value with attr. Try the following:
$("#foo").on('click', function(){
var foo1 = $(this);
var c = foo1.attr('data-value');
var sum = parseInt(c) + parseInt(3);
a = foo1.attr("data-value", sum);
console.log(foo1.attr("data-value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" data-value="3">Click Here</div>

how to get dynamic id of dynamically created textbox in jquery

i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}

Showing hidden textboxes as they are filled

I have a page of thirty text boxes with Id's roughly correlating to _Q0/_Q1/_Q2/_Q3 etc.
I'm trying to design a JS code that will hide all but the first box, and then will reveal the next textbox as the previous one is filled in.
Here is my code:
$(function () {
for(var i=1;i<30;i++){
var t = i
document.getElementById("_Q" + t).style.visibility = 'hidden';
};
var idNumber = 0
document.getElementById("_Q"+idNumber).onKeyUp(function(){return boxAdder()});
function boxAdder(){
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'block';
document.getElementById("_Q" + idNumber).onKeyUp(function(){return boxAdder()});
};
});
So far all the boxes are hidden excluding the first box. However when I write into the first box nothing happens. I'm not entirely sure where this code is going wrong.
Edit: sample JSFiddle: http://jsfiddle.net/8b7pH/3/
Solved! Here is the final code:
$(function () {
for(var i=1;i<=5;i++){
var t = i;
document.getElementById("_Q" + t).style.visibility = 'hidden';
// document.getElementById("_Q" + idNumber).onkeyup = function(){console.log("hi"); return boxAdder(t+1);};
}
var idNumber = 0;
document.getElementById("_Q0").onkeyup = function(){console.log("hi"); return boxAdder(0);};
function boxAdder(numm){
console.log("ho");
//idNumber = idNumber+1;
document.getElementById("_Q" + numm).style.visibility = 'visible';
document.getElementById("_Q" + numm).onkeyup = function(){return boxAdder(numm+1);};
}
});
This does what you want:
$(function () {
var $boxes = $("[id^=_Q]").hide().keyup(function(){ //Hide all, then attach keyup
var i = $(this).index(); //Index of the box being typed
$boxes.eq(i+1).show(); //Get and show next textbox
});
$boxes.first().show(); //Show next textbox
});
Btw $("[id^=_Q]") selects all elements whose id starts with _Q
Working OK here: http://jsfiddle.net/edgarinvillegas/8b7pH/7/
Cheers
My suggestion is that you assign a function to the onchange event of the text boxes, and give each one an id as follows:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function textChange(){
// Get the number of the caller's id
var inputNumber = $(event.target).attr('id').split("txt")[1];
// Select the next input by increasing the inputNumber and set its "display" attr to block
$("#txt" + ++inputNumber).css("display", "block");
}
</script>
<from>
<input type="text" id="txt1" onchange="textChange()" />
<input type="text" style="display:none;" id="txt2" onchange="textChange()" />
<input type="text" style="display:none;" id="txt3" onchange="textChange()" />
<input type="text" style="display:none;" id="txt4" onchange="textChange()" />
<input type="text" style="display:none;" id="txt5" onchange="textChange()" />
</form>
A working example can be found here:
http://jsfiddle.net/WChd8/
Thanks for the fiddle. I've updated it to a working one.
Here's the code:
$(function () {
for(var i=1;i<=5;i++){
var t = i;
document.getElementById("_Q" + t).style.visibility = 'hidden';
}
var idNumber = 0;
document.getElementById("_Q" + idNumber).onkeyup = function(){console.log("hi"); return boxAdder();};
function boxAdder(){
console.log("ho");
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'visible';
document.getElementById("_Q" + idNumber).onkeyup = function(){return boxAdder();};
}
});
The significant change was the syntax for onkeyup: element.onkeyup = function(). Other than that, there were a bunch of missing semicolons that didn't matter. I added console.logs that can obviously be removed.
EDIT
Edgar found a valid bug, so I put in a fix. Basically, remove the onkeyup event as soon as it's called:
document.getElementById("_Q" + idNumber).onkeyup = function(){this.onkeyup = null; return boxAdder();};
function boxAdder(){
idNumber = idNumber+1;
document.getElementById("_Q" + idNumber).style.visibility = 'visible';
document.getElementById("_Q" + idNumber).onkeyup = function(){this.onkeyup = null; return boxAdder();};
}
Note the new this.onkeyup = null; in two places.
This is a javascript only approach, based on what you already had, that also checks for the content written in the input. If is blank, it hides the next one again.
for(var i=0;i<30;i++){
var element = document.getElementById("_Q" + i);
if(element != null)
{
element.onkeyup = function() {
var next = parseInt(this.id.replace("_Q", "")) + 1;
document.getElementById("_Q" + next).style.visibility = (this.value != "" ? "visible" : "hidden");
}
}
if(i>0)
element.style.visibility = 'hidden';
};

how to use javascript onkeyup for multiple ids at sametime

I have 2 html textbox for users to enter numbers. To sum those numbers, I am passing the values to JavaScript variable and after addition displaying the result to html div section
<div class="input-left"><span><input class="textbox" id="left" name="count" type="text" size="5" value="" /></span></div>
<div class="input-right"><span><input class="textbox" id="right" name="count" type="text" size="5" value="" /></span></div>
<div id="result"> </div>
javascript:
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
But I have an issue with JavaScript. It not displaying the result. How to add both functions in same onkeyup function.
FIDDLE SETUP
Try this:
window.onload = function(){
var left = document.getElementById('left');
var right = document.getElementById('right');
var result = document.getElementById("result");
left.onkeyup = calc;
right.onkeyup = calc;
function calc() {
var a = parseFloat(left.value) || 0;
var b = parseFloat(right.value) || 0;
result.innerHTML = a + b ;
}
}
JSFiddle: http://fiddle.jshell.net/gYV8Z/3/
Update: To hide the result in case the sum equals zero , change the last line like this:
result.innerHTML = ( a + b ) || "";
JSFiddle: http://fiddle.jshell.net/gYV8Z/4/
document.getElementById('left').onkeyup = function() {
var a = parseFloat(this.value);
}
document.getElementById('right').onkeyup = function() {
var b = a + parseFloat(this.value);
document.getElementById("result").innerHTML = b || 0 ;
}
it your code, var a is local variable. make it global variable.
but i would use this code.
function add(){
return parseFloat(document.getElementById('left').value) + parseFloat(document.getElementById('right').value);
}
document.getElementById('left').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}
document.getElementById('right').onkeyup = function() {
document.getElementById("result").innerHTML = add();
}

Categories