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
Related
I wanted to add a Character counter to my website. Therefore I have a span with id="counter" and a input type="texture" with id="producttext". I started my Code with a :
document.addEventListener('keyup', function test() {
var textEntered, a;
textEntered = document.getElementById('producttext').value;
a = document.getElementById('counter');
a.innerHTML = textEntered;
});
But the output is not the count of the character. It is the content
How to solve this ?
I'd do something like:
const counter = document.querySelector("#counter");
const textEl = document.querySelector("#foo");
textEl.addEventListener("input", () => {
counter.textContent = textEl.value.length;
});
<input type="text" id="foo" />
<span id="counter">0</span>
I have a counter in javascript right now and a button that adds 1 value to the counter, this is what I have so far:
var counter = 0;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
I need a button to reset the counter back to 0 any help is appreciated.
Add a button, reset function and set values to "0" as shown in code below:
<button width="500" height="500" id ="reset" class="button button1"
onclick="javascript:reset()">Reset Value</button>
<script type="text/javascript">
var reset= function(){
a = 0;
document.getElementById('Value').innerHTML = a;
}
</script>
BTW you declared var count = 0 in your code (question) but not using that (apparently).
Some tips:
You correctly stored a variable to keep track of the counter, all you needed to do in a reset function was to change the value back to 0.
Keep your Javascript away from your HTML. Here's a good article
Your code should be properly formatted when posting on Stack Overflow.
Here's a cleaner solution:
HTML:
Value $<span id="Value">0</span>
<button id="add">Add Value</button>
<button id="reset">Reset</button>
Javascript:
var a = 0;
var add = function(valueToAdd) {
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
var reset = function() {
a = 0;
document.getElementById('Value').innerHTML = 0;
}
var addButton = document.querySelector("#add");
var resetButton = document.querySelector("#reset");
addButton.addEventListener("click", function() {
add(1);
})
resetButton.addEventListener("click", function() {
reset();
})
JSFiddle: https://jsfiddle.net/sfh51odm/
Do not define a out of function as a general variable. Every time set the current value to a and continue. So you can get back to zero:
var counter = 0;
var add = function(valueToAdd){
var a = parseInt(document.getElementById('Value').innerHTML);
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
function reset(){
document.getElementById('Value').innerHTML=0;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
<button width="500" height="500" id = add class="button button1" onclick="javascript:reset()">Reset</button>
var a = 0;
var displayValue = document.getElementById('Value');
var updateValue = function () {
displayValue.innerHTML = a;
};
var add = function (valueToAdd) {
a += valueToAdd;
updateValue();
};
var reset = function () {
a = 0;
updateValue();
};
Value $<span id="Value">0</span>
<button onclick="add(1)">Add 1</button>
<button onclick="reset()">Reset</button>
if you need to do a page refresh (like if you press F5 on the keyboard) this will work for you.
the "location.reload();" will work also.
change '.again' to a btn name you want.
document.querySelector('.again').addEventListener('click', function () { location.reload(); });
Hi friends (Gurus) I would be very glad if someone helps me out. Thank you great people. You always help. Any further tips or explanation would be appreciated.
<script>
function cal() {
var firstNumber = document.getElementById("first").value;
var secondNumber = document.getElementById("second").value;
var total = firstNumber + secondNumber;
document.getElementById("display").innerHTML=total;
}
function ca4l2() {
var firstNumber = document.getElementById("first").value;
var secondNumber = document.getElementById("second").value;
var total = firstNumber + secondNumber;
document.getElementById("display").innerHTML=total;
}
</script>
<input type="number" id="first" onKeyPress="cal()"> +
<input type="number" id="second" onKeyPress="cal2()">
<p id="display"></p
Try this.
DEMO
HTML:
<input type="number" id="first"> +
<input type="number" id="second">
<button id="btn">
Calculate
</button>
<p id="display"></p>
JavaScript:
var first = document.getElementById('first'),
second = document.getElementById('second'),
btn = document.getElementById('btn'),
display = document.getElementById('display');
btn.addEventListener(
"click", CalNum, false);
function CalNum() {
display.innerHTML = parseInt(first.value) + parseInt(second.value);
}
As requested from OP, this is another example of how to calculate
numbers without using a button to fire the function.
HTML:
<input type="number" id="first"> +
<input type="number" id="second">
<p id="display"></p>
CSS
#display {
animation: OpacityBlink 1s linear infinite;
/*You need to use -webkit- and all other properties for this transition to work on all browsers.*/
}
#keyframes OpacityBlink {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
JavaScript
var first = document.getElementById('first'),
second = document.getElementById('second'),
display = document.getElementById('display');
first.addEventListener(
"keyup", CalNum, false); //assigns the keyup event listener
second.addEventListener(
"keyup", CalNum, false); //assigns the keyup event listener
function CalNum() {
if (first.value === "" || second.value === "") {
display.innerHTML = "Calculating.."; //if inputs value is empty display this string
} else {
display.style.animation = "none"; // stops the css3 animation
display.innerHTML = parseInt(first.value) + parseInt(second.value); //displays the final result
}
}
/* Please note that this only work if the user uses his keyboard to type the numbers. The CalNum function only fires if the event detects keyup, otherwise nothing will happen. You can always add another event listener for mouse clicks as well. */
Change to this,
var total = parseInt(firstNumber) + parseInt(secondNumber);
if the number is decimal, then,
var total = parseFloat(firstNumber) + parseFloat(secondNumber);
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);
}
Here is the link to the jsbin.
I was almost finished with my project (I thought I was) and then I tested it out. It is supposed to add buttons with the chosen title of the task and the number of points it awards. Every time the button is clicked the points would be added on to the "Points" section and every 500 points my "Level" would increase.
Upon finishing it, it worked. Then I went to clear the localStorage since that's what I used to save the information, but I wanted to start over. When I did that, the 'Points' section, or 'results' value, keeps returning as "NaN". The code is exactly the same as it was when it worked. Can someone please tell me how to fix this problem, thank you in advance.
Here is the code. (Used bootstrap for CSS)
HTML
<center>
<br>
<h2> Add task </h2>
<div class='well' style='width:500px' id="addc">
<div id="addc">
<input class='form-control' style='width:450px' id="btnName" type="text" placeholder="New Task" /><br>
<input class='form-control' style='width:450px' id="btnPoints" type="text" placeholder="Points" /><br>
<button id="addBtn">Add</button>
</div> </div>
<div class='well' style='width:230px' id="container">
</div>
<hr style="width:400px;">
<h3>Points </h3>
<div id="result">0</div>
</div>
<hr style="width:400px;">
<div style="width:400px;">
<h3>Level
<p id='lvl'>0</p>
</div>
<hr style="width:400px;">
</center>
JavaScript
var res = document.getElementById('result');
res.innerText = localStorage.getItem('myResult');
var level = document.getElementById('lvl');
level.textContent = localStorage.getItem('myLevel');
var btns = document.querySelectorAll('.btn');
for(var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
}
var addBtn = document.getElementById('addBtn');
addBtn.className = "btn btn-default";
addBtn.addEventListener('click', function() {
var container = document.getElementById('container');
var btnName = document.getElementById('btnName').value;
var btnPoints = parseInt(document.getElementById('btnPoints').value);
if(!btnName)
btnName = "Button ?";
if(!btnPoints)
btnPoints = 50;
var newBtn = document.createElement('button');
var newPnt = document.createElement('span');
newBtn.className = 'btn btn-danger';
newBtn.innerText = btnName;
newBtn.setAttribute('data-points', btnPoints);
newBtn.addEventListener('click', function() {
addToResult(this.getAttribute('data-points'));
this.parentNode.removeChild(this.nextElementSibling);
this.parentNode.removeChild(this);
});
newPnt.className = 'label';
newPnt.innerText = "+" + btnPoints;
container.appendChild(newBtn);
container.appendChild(newPnt);
});
function addToResult(pts) {
var result = document.getElementById('result');
result.innerText = parseInt(result.innerText) + parseInt(pts);
var lvl = 0;
var a = 100;
while (result.innerText > 5*a) {
lvl+=1;
a+=100;
}
document.getElementById('lvl').innerText = lvl;
var res = document.getElementById('result');
localStorage.setItem("myResult", res.innerText);
var level = document.getElementById('lvl');
localStorage.setItem("myLevel", level.textContent);
}
You were parsing result.innerText as a number, but its value, initially, was actually either NaN or nothing, both which end up being NaN. One fix is to just check if it parsed to a number, and if it didn't, fall back to 0.
I just basically changed that and removed some getElementByIds that, in my opinion, were redundant, check the addToResult function:
http://jsfiddle.net/owc26a0p/1/
function addToResult(pts) {
// NaN is falsy, so you can just use || to make a fallback to 0
var result = parseInt(resDiv.innerText, 10) || 0,
lvl = 0,
a = 100;
result = result + parseInt(pts, 10) || 0;
while (result > 5 * a) {
lvl += 1;
a += 100;
}
resDiv.innerText = result;
levelDiv.innerText = lvl;
localStorage.setItem("myResult", result);
localStorage.setItem("myLevel", levelDiv.textContent);
}
I ended up using jsFiddle since I couldn't always get jsBin to save my changes. Good luck.