jQuery: changed input value is not used for new addition - javascript

I have a hidden input field, wich has the value 0:
<input type="hidden" class="test" value="0" />
Now I added a button with some JS to add 0.5 to the value each time the button is clicked:
<a class="addition-input">Click me</a>
Here is the JS part:
$('a.addition-input').click(function(event) {
event.preventDefault();
var currentValue = parseInt($('input.test').val());
var step = 0.5;
var newValue = currentValue + step;
$('input.test').val(newValue);
});
So, the first time i click the link/button, the value gets from "0" to "0.5".
But then, when I click the link/button the second time, it won't change, it just stays "0.5".
I think that jQuery doesn't get the new input value by the second time click, it probably thinks the value is "0".
How can I fix that?
Update:
Here's the fiddle: https://jsfiddle.net/m7pvjrve/1/

Use
var currentValue = parseFloat($('input.test').val());
instead of
var currentValue = parseInt($('input.test').val());
parseInt() converts 0.5 to 0 everytime and the value you get is 0.5 which is actually the step value
Demo: http://jsfiddle.net/GCu2D/657/

Related

How to create a minus and plus button to update a field?

I am trying to create a products page with a forum that shows the price of the item, the name of the item and also the quantity with buttons to add or subtract from the quantity field.
I have no idea where to begin, I thought I'd do some looking into different types of buttons and form input types but none of them seem to have what I need.
I was wondering if anyone can point me to the right direction so I can figure out how these buttons are changing the quantity field and how I can make a plus and minus button which appears next to the quantity.
Here is a picture of what I mean:
Use JavaScript to increase and decrease the input value:
const minusButton = document.getElementById('minus');
const plusButton = document.getElementById('plus');
const inputField = document.getElementById('input');
minusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue - 1;
});
plusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 1;
});
<button id="minus">−</button>
<input type="number" value="0" id="input"/>
<button id="plus">+</button>
Here what happens in the JS code. First it gets references to the HTML elements using the id HTML attribute and the document.getElementById JS function. Then it adds functions which are executed when one of the buttons is clicked. Inside the functions, the default button browser action (submitting the form) is cancelled, the input value is read, increased/decreased and put back to the input.

How to add values from two buttons to single inputbox?

Assume that I have two buttons with the values 'abc' and 'efg' respectively, and an inputbox.
This is what I want to achieve :
When I click the button with the value 'abc' a single time, the value 'a' gets appended to the inputbox. If I press it two times immediately the value suddenly changes to 'b' instead of 'a', and when I do it three times it changes to 'c' instead of 'b'.
I should be able to type double 'a''s (or any of 'a', 'b', 'c') by waiting some time between button clicks on button 'abc'. For instance : I first click button 'abc', then 'a' gets into the inputbox, I wait for a short time and clicks one more time to get another 'a'.
I want the same functionality with all the buttons ('abc' and 'efg').
I have linked sample expected output image.
View this jsfiddle Code
<div ng-controller="MyCtrl">
<input type="text" ng-model="btnTxt[btnarr]">
<button ng-modle="btnarr" ng-Click="change()">abc</button>
</div>
Expected output:
Can anyone help me with this ?
I have tried one without using built-in timer functions, and checking it manually.
Solution at Pastebin : pastebin.com/vHF517FN
See if it's good enough for you. Btw, I didn't really refactor much, will do it if you are satisfied with this (I'm also new to js -_-).
EDIT
Refactored anyway.
Refactored Solution at Pastebin : pastebin.com/EnHz2EHK
EDIT 2
Added it to JSFiddle. However, I had to add everything to HTML part to make it work there, moving script to script part isn't working for me (wonder why).
Solution at JSFiddle
<script>
var prevClick = '!';
var prevClickTime;
var clicks = 0;
function buttonClick(letters) {
var input = document.getElementById("put");
var backLetterIndex = (clicks == 0) ? letters.length-1 : clicks - 1;
if(letters[backLetterIndex] == prevClick) {
var now = (new Date()).getTime();
if(now - prevClickTime < 500) {
var val = input.value;
input.value = val.slice(0, val.length - 1);
}
else
clicks = 0;
}
else
clicks = 0;
prevClickTime = (new Date()).getTime();
prevClick = letters[clicks];
clicks = (clicks + 1) % letters.length;
input.value = input.value + prevClick;
}
</script>
<input id="put" type="text"></input>
<button onClick="buttonClick('abc');">abc</button>
<button onClick="buttonClick('defg');">defg</button>
I get it, you want to do phone keyboard.
I am not sure what exactly is your question so here I wrote complete example
http://jsfiddle.net/daybda4h/5/
Bacically, I wrote click event listener with timer if click comes within 200ms after another click I count up.
clicks++;
if(timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
timer = null;
updateInput(clicks, evt.target);
clicks = 0;
}, timeout);
Then, when no more clicks are comming, I take the final number of clicks, take data attribute of a button that says what letters does it control, and take the letter number according to num of clicks.
to add value to input, you simply take input value and add the same value + some custom string.
function updateInput(cl, btn) {
var input = document.getElementById("test");
var letters = btn.getAttribute("data-letters").split("");
input.value = input.value + letters[cl-1];
}
Hope this resolves your problem :)

Is there a way to assign unique IDs to createElement objects?

I have a button when pressed creates new input bars and I would like those input bars to have unique ids, for example - textBar1, textBar2, textBar3 and so on.
I tried creating a variable outside of the function that has the value 0 and then inside the function add the value with +1 for each time the function runs but that doesn't work but instead it assigns the id textBar0 to every element that is created.
Does anyone have any suggestions on how to solve this?
Thanks in advance!
HTML
<label for='ingredient'></label>
<input id="textBar" class="textBar" type="name" name="ingredient">
<div id="textBarPosition"></div>
<div id="addRemoveContainer">
<input id="addBar" type="button" value="Add Ingredient">
JavaScript/jQuery
var counter = 0;
function createSector() {
var input = document.createElement('input');
input.setAttribute("id", 'textBar' + counter +1);
input.type = 'text';
input.name = 'name[]';
return input;
counter = 1;
}
var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
// step 1: create element and set opacity to 0.
var selector = $(createSector());
selector.fadeIn();
// step 2: append it to its parent.
$(form).append(selector);
$('#removeBar').click(function(){
$("input:last-child").remove(".textBar");
});
});
That is becaus you're not reassinging the changed value to counter.
Use counter+=1 instead or just counter++
input.setAttribute("id", 'textBar' + counter++); // now it should work
What you were doing before was always add 1 to 0
Best way is to use _.uniqueId.
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.
_.uniqueId('contact_');
=> 'contact_104'
You can use Math.random like this:
input.setAttribute("id", 'textBar_' + Math.random().toString(36));
It is my understanding that when you first call Math.random it generates a sequence of unique random numbers between 0 and 1 using the current time in milliseconds as a seed then returns the first one. Subsequent calls will move through the generated sequence of numbers, returning them one at a time, giving you the ability to generate random unique strings for element IDs.
jQuery Code -
var counter = 0;
function createSector() {
var input = document.createElement('input');
input.setAttribute("id", 'textBar' + counter);
input.type = 'text';
input.name = 'name[]';
return input;
}
var form = document.getElementById('textBarPosition');
document.getElementById('addBar').addEventListener('click', function(e) {
// step 1: create element and set opacity to 0.
var selector = $(createSector());
counter++;
selector.fadeIn();
// step 2: append it to its parent.
$(form).append(selector);
$('#removeBar').click(function(){
$("input:last-child").remove(".textBar");
});
});
Working JSFiddle - http://jsfiddle.net/Ashish_developer/mtafre04/

changing attribute of element - why is onchange event not fireing?

For demonstration of the problem described below see JSFiddle
HTML:
<input type="range" id="slider_length" min="10" max="200" value="0" step="10" onchange="changeValue1();" />
<span id="slider_length_span">10 mm</span>
</br>
<input type="range" id="slider_length2" min="5" max="15" value="0" step="10" onchange="changeValue2();" />
<span id="slider_length2_span">5 mm</span>
JS:
window.changeValue1 = function()
{
var slider = document.getElementById("slider_length");
var span = document.getElementById("slider_length_span");
span.innerHTML = slider.value + " mm";
var slider2 = document.getElementById("slider_length2");
slider2.setAttribute("max", slider.value - 5);
}
window.changeValue2 = function()
{
var slider = document.getElementById("slider_length2");
var span = document.getElementById("slider_length2_span");
span.innerHTML = slider.value + " mm";
}
I have one range element where the user can select a value between 10 and 200 with steps of 10.
There is a second range element with values between 5 and 15 with steps of 10.
If the user changes the first range element, the onchange event gets fired (successfully), in which the "max" attribute of the second range element gets changed (by value of first element -5). So far this works fine.
Steps to reproduce the problem:
select any number on first range element (e.g. 150)
select highest possible number on second range element (e.g. 145)
reduce selected number on first range element (e.g. 150 -> 110)
Expected behaviour:
When the onchange Event of the first range element gets fired the "max" attribute of the second range element changes to 105. The value of the second range element still is at 145 and should go to 105 (highest possible value). Because the second range element changes, the onchange event gets fired, updating a span element which shows its value.
Actual behaviour:
When the "max" Attribute of the second range element gets changed the onchange event doesn't seem to fire.
Question: Why is the onchange event not fireing? If onchange event is not the correct event to use in this case, which event am I supposed to use?
I have made a trick on your function like;
window.changeValue1 = function()
{
var slider = document.getElementById("slider_length");
var span = document.getElementById("slider_length_span");
span.innerHTML = slider.value + " mm";
var slider2 = document.getElementById("slider_length2");
if ((slider.value - 5) < slider2.value) {
slider2.value = 0;
slider2.setAttribute("max", slider.value - 5);
slider2.value = slider.value - 5;
var span = document.getElementById("slider_length2_span");
span.innerHTML = slider2.value + " mm";
} else {
slider2.setAttribute("max", slider.value - 5);
}
}
In order to set max value of second range in your case, I have set second range to zero, set max range of slide2 and set slide2 value to possible max value. You can see working example here: http://jsfiddle.net/wtq6H/7/
Onchange only checks if the value of an input changes not if any of it's other attributes change. In addition only after specific user actions like a textfield loosing focus will the browser check if a change has happend to begin with.
Why do you want to use the second event anyway? It seems like you should be able to do everything you want to do in the second event from within the first.

Configure value manually and change color of box(circle) in JavaScript

Here is simple javascript code which has 3 function Increment(), Stop(), Start().
var value = 0;
var end;
function Increment(){
value++;
document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />';
}
end = setInterval(Increment, 1000);
function Stop(){
clearInterval(end);
}
function Start(){
end = setInterval(Increment, 1000);
}
<p id="counter"></p></br>
<div>
<input id= "btn1" type="button" value="Stop" onclick="Stop()">
<input id = "btn2" type="button" value="Start Again" onclick="Start()">
</div>
How can I manually configure the value; like I would enter a desired value and it will start from that value.
How can I set a threshold value, after crossing the threshold value, the corresponding box/circle will change the color.
Thanks, Kind Regard,
If you mean how could you on the code side set the value, then you would simply change the var value = 0 line to whatever value you want. If you want the user to be able to set the value, then you would use an input to get the user value and then set that as the var value =.
In your script, add a line in Increment() like "if (value >= _) {" with your threshold value in the blank, and then add your color-change code after the bracket.
You want to add an input field that allows the user to set an initial value. I also don't recommend writing inline JavaScript - take a look into the subject of unobtrusive JavaScript.
Here's how your startCounting() should look like:
// Hold our counter info
var counter = {
currValue: 0,
interval: null
};
function startCounting() {
// Set the current value if provided
counter.currValue = startValueField.value || 0;
counter.interval = setInterval(increment, 1000);
}
I'll leave adding the threshold value as an exercise. It's the same idea.
FIDDLE

Categories

Resources