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

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.

Related

can javascript version of print be inserted inside the code of a Div?

I have a form that adds and subtracts a smaller form when user clicks on add or subtract users button.
what I want to do is add a +1 every time the user hits the add button to a ID tag inside the div tag.. confusing yes I know
say this is the original tag:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
now say the user clicks on a add button and a new form will pop up below the current form and using a print or echo version of javascript this would be the new code created for the div using .append(html) or something along those lines too this:
<div id="formwrap" class="test" name="test">im a form in this formwrap</div>
<div id="formwrap" class="test2" name="test2">im a form in this formwrap</div>
and so on as u can see next the 2 would change to a 3 if someone where to click the add button
<div id="formwrap" class="test(+1 code would go here)" name="test(+1 code would go here)">im a form in this formwrap</div>
So before I code is this even possible? I want to be able to style the smaller form differently and I want the phpmailer to be able get retrieve all the data depending on how many clicks they do. and adding a +1 too each of the tags would do both goals.
It is possible using data attributes.
See: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
You would do something like this
var count = 0
var formwrap = document.getElementById('formwrap');
formwrap.dataset.name = "aName" + count
// increment count on click
You can use jquery for this when user click on add button you have to increment the value of count like this ...
var count = 0;
$("button").on("click", function () {
var html = '<div id="formwrap'+count+'" class="test'+count+'"
name="test'+count+'">im a form in this formwrap</div>';
count++;
$(div).append(html);
});
this way you can do this.
//Create a private counter var
const counter = (function() {
var formCount = 0;
return {
value: () => formCount,
increment: () => ++formCount
}
})();
//A function that will generate a "form" element
const ID_PREFIX = 'formwrap_';
const generateFormEl = () => {
let el = document.createElement('div');
el.setAttribute('id', `${ID_PREFIX}${counter.increment()}`);
el.setAttribute('class', 'test');
el.setAttribute('name', 'test');
el.appendChild(document.createTextNode(`ID: ${el.getAttribute('id')}`));
return el;
};
//Store your DOM elements in some vars
const forms = document.querySelector('#forms');
const btn = document.querySelector('[type="button"]');
//Add a form element to the DOM on click
btn.addEventListener('click', () => {
const form = generateFormEl();
forms.appendChild(form);
});
<div id="container">
<input type="button" value="Add a form" />
<div id="forms"></div>
</div>

Multiple input and multiple output with onclick eventlistener in javascript

Want to ask :
For example , i have multiple button and when i click on anyone, the value will be shown at the result textbox and the input textbox will back to 0 , need help on check my code :
document.getElementById("plusthevalue").addEventListener('click',function plus()
{
var inputvalue = document.getElementById("Input");
var resultvalue = document.getElementById("Result");
document.write("Result").value = inputvalue + resultvalue;
document.write("Input").value ="0";
});
and, if i want to write a single statement that can include all the button and will display the output depend on the button, how would the code will be?
p/s: i know i can hardwork until i code function for every button but that would be very messy , i want to include all :(
You can assign all your buttons a certain class, then use document.querySelectorAll('.myclass') to grab all of them. Then you can loop through the results to add the event listener to each of them.
Example:
var myButtons = document.querySelectorAll('.myclass');
for (i = 0; i < myButtons.length; ++i) {
myButtons[i].addEventListener('click', function(e) {
// Do stuff
}
}
See https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll for more info about querySelectorAll.

How do I attach eventListeners to dynamically generated radio buttons?

I want to attach an event listener to each radio input click, so that I can retrieve that radio input's value and assign it as the value of a new property in the current question object in the allQuestions array.
I'm not sure why I'm having difficulty making choice.addEventListener work.
My HTML:
<div id="quiz"></div>
<button id="button">Next</button>
My JavaScript:
var allQuestions = [{question: "What is the capital of the Czech Republic?",
choices: ["Skopje", "Budapest", "Prague", "Bucharest"],
correctAnswer: 2},
{question: "When was the Declaration of Independence signed?",
choices: ["1492", "1776", "1812", "1791"],
correctAnswer: 1}];
var quiz = document.getElementById("quiz");
var index = -1;
var next = function() {
index += 1;
quiz.innerHTML = "";
for (var i = 0; i < allQuestions[index]['choices'].length; i++) {
var choice = document.createElement('input');
choice.type = 'radio';
choice.name = 'choices';
choice.value = i;
choice.addEventListener('click', function() {
alert('hi');
});
quiz.appendChild(choice);
quiz.innerHTML += allQuestions[index]['choices'][i] + '<br>';
}
};
var button = document.getElementById('button');
button.addEventListener('click', next);
You're trying to use markup and DOM elements at the same time. Here's the main problem:
quiz.appendChild(choice);
quiz.innerHTML += allQuestions[index]['choices'][i] + '<br>';
The first line appends a DOM element with an attached event handler to the quiz element. The second line converts the contents of quiz to an HTML string, appends some further text (markup) to that string, and then parses that HTML and replaces the content of quiz with the parsed result. That wipes out anything not represented in the HTML, including the dynamically-added event handler.
The solution is not to do innerHTML += ..., which is almost always a bad idea. In this particular case, you can do this:
quiz.appendChild(choice);
quiz.appendChild(document.createTextNode(allQuestions[index]['choices'][i]));
quiz.appendChild(document.createElement('br'));
...which also has the advantage that any characters that are special in HTML (like <) are treated literally (because that's what createTextNode does).
Now, having said that, you don't need handlers on every radio button. Instead, you can use event delegation by using a handler on your quiz element, and then using e.target within the handler to know which radio button was clicked:
quiz.addEventListener("click", function(e) {
if (e.target.tagName.toUpperCase() === "INPUT") {
var value = e.target.value; // The value of the clicked radio button
}
});
That way, you don't have to worry about adding handlers dynamically; just do it once, after the quiz element is known to exist, and you can update its content all you want without having to worry about attaching handlers to the radio buttons within.
To do event delegation in general, you usually have to loop starting from e.target and going to its parentNode in order to find the element you're interested in (say you're interested in a div, but the click was on a span inside it); but of course, input elements can't have any elements inside them, so it's simple here.
You're probably wondering why the check on the tag name. If you associate your radio buttons with label elements (as is usually good practice), either by putting the input inside the label or using the for attribute on the label, you'll see two clicks when you click the label: One on the label itself, and a second one on the input that the label relates to. We're only interested in the one on the actual radio button.
Here's a simple example of the delegation above:
var quiz = document.getElementById("quiz");
quiz.addEventListener("click", function(e) {
if (e.target.tagName.toUpperCase() === "INPUT") {
var value = e.target.value; // The value of the clicked radio button
console.log("The value of that radio button is " + value);
}
});
for (var n = 0; n < 5; ++n) {
var div = document.createElement("div");
div.innerHTML = '<label><input type="radio" value="' + n + '" name="answer"> Radio ' + n + '</label>';
quiz.appendChild(div);
}
<div id="quiz"></div>

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 :)

I need to assign a value to textbox where the value will be the value of the currently pressed button

I need to assign a value to textbox where the value will be the value of the currently pressed button..i have used the following codes
<button id="but0" value="0" onClick="button_value(this.id)">0</button>
function button_value(id)
{
var val=document.getElementById(id).value ;
alert(val) ;
//display.value=val;
}
but i couldnot achieve the output...can anyone help me out
put this in your load event and change the apropriate IDs of your elements.
var button = document.getElementById("button");
var input = document.getElementById("input");
button.onclick=function(){
input.value = document.getElementById("button").innerHTML;
};

Categories

Resources