I am working on this snippet. How can I increment the index continuously when the #adder in clicked and pressed?
var index = 0;
$("#adder").on("click", function(){
++index;
$("#res").html(index);
});
$("#adder").on("keydown", function(){
++index;
$("#res").html(index);
});
$("#adder").on("keypress", function(){
++index;
$("#res").html(index);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-default" id="adder">+</button>
<div id="res"> </div>
Here is an example by using mousedown and mouseup event handler and use setInterval to do continuously adding index.
Edited
Recovered the click event handler that makes the index increase immediately after clicking.
Edited
Add a limit condition
var index = 0;
var interval;
var timeout;
// $("#adder").on("click", function(){
// increase();
// });
$("#adder").on("mousedown", function(){
increase();
timeout = setTimeout(function(){
interval = setInterval(function(){
increase();
}, 100);
}, 500);
});
$("#adder").on("mouseup", function(){
clearTimeout(timeout);
clearInterval(interval);
});
function increase(){
$("#res").html(++index);
checkLimit();
}
function checkLimit(){
// here to check stop increasment
if(index >= 50 ){
// stop interval
clearInterval(interval);
// remove event handler
$("#adder").off('click').off('mousedown').off('mouseup');
return;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-default" id="adder">+</button>
<div id="res"> </div>
I have started from your code to make one working with pure JavaScript and Bootstrap where you can add as many buttons and input fields as you like and get the max, min values from input fields. To sum up I have improved my code with autoincrement input values when button is pressed.
I have further improved the code using onpointerdown, onpointerup, onpointerleave methods instead than onmousedown and onmouseup. In this way it will work on mobile devices as well.
function imposeMinMax(el) {
if (el.value != '') {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
var index = 0;
var interval;
var timeout;
var stopFlag=false;
function clearAll(){
clearTimeout(timeout);
clearInterval(interval);
}
function modIn(el) {
var inId = el.id;
if (inId.charAt(0) == 'p') {
var targetId = inId.charAt(2);
var maxValue = Number(document.getElementById(targetId).max);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue < maxValue){
stopFlag=false;
document.getElementById(targetId).value++;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index+1 >= maxValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value++;
}
index++;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
if (inId.charAt(0) == 'm') {
var targetId = inId.charAt(2);
var minValue = Number(document.getElementById(targetId).min);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue > minValue){
stopFlag=false;
document.getElementById(targetId).value--;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index-1 <= minValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value--;
}
index--;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Button example</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<button type='button' class='btn btn-danger btn-sm ' id='mbA' onpointerdown='modIn(this)' onpointerup='clearAll()' onpointerleave='clearAll()'>-</button>
<input type='number' id='A' onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbA' onpointerdown='modIn(this)' onpointerup='clearAll()' onpointerleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onpointerdown='modIn(this)' onpointerup='clearAll()' onpointerleave='clearAll()'>-</button>
<input type='number' id='B' onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbB' onpointerdown='modIn(this)' onpointerup='clearAll()' onpointerleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onpointerleave='clearAll()'>-</button>
<input type='number' id='C' onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onpointerleave='clearAll()'>+</button>
</body>
</html>
Related
I found this snippet to add additional fields to a form. Works great. If you may, please let me know how I can have the added fields start at 2 while also maintaining the option to remove it. While i = 2 does work, I have not figured out what's needed for the option to add/remove said fields accordingly. Thank you for your time.
$(document).ready(function() {
var i = 1;
$('#add').click(function() {
if (i <= 7) {
$('#dynamic_field').append('<div class="add-row" id="row' + i + '"><label" for="number_' + i + '">Number ' + i + '</label><input type="text" name="number_' + i + '" value=""></div>')
i++;
$('.btn-remove').removeClass('hidden');
}
});
$(document).on('click', '.btn-remove', function() {
var button_id = $(this).attr("id");
i--;
$('#row' + $('#dynamic_field div').length).remove();
if (i<=1) {
$('.btn-remove').addClass('hidden');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add" class="btn-add">Add Another Number</button> <button type="button" class="btn-remove hidden">Remove last</button>
<div id="dynamic_field"></div>
Your code is being made unnecessarily complicated by the use of id attributes which you generate at runtime.
You can completely avoid the need to do this by using the same content in each row, which you can store in a template element. Note that this template content uses no id, but the same class instead, and also that the label wraps the input so no for attribute is required.
You can then simply get the number of existing rows in the DOM to calculate the next number to display. Also, as the 'remove' button only targets the last row you can select it directly with .row:last.
Here's a working example with all these changes implemented:
jQuery($ => {
let maxRows = 7;
let rowTemplate = $('#row-template').html();
let $container = $('#dynamic_field');
$('#add').on('click', () => {
let rowCount = $('.row').length;
if (rowCount >= maxRows)
return;
let $row = $(rowTemplate).appendTo($container);
$row.find('span').text(rowCount += 2);
$('.btn-remove').removeClass('hidden');
});
$(document).on('click', '.btn-remove', () => $('.row:last').remove());
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add" class="btn-add">Add Another Number</button>
<button type="button" class="btn-remove hidden">Remove last</button>
<div id="dynamic_field"></div>
<template id="row-template">
<div class="row">
<label>
Number <span></span>
<input type="text" name="number[]" value="" />
</label>
</div>
</template>
You do not need to keep a count yourself
$(function() {
const $container = $("#dynamic_field");
let count = $container.children().length;
$('.btn-remove').toggle(count > 1);
$('#add').click(function() {
let count = $container.children().length;
if (count < 7) {
$('#dynamic_field').append(`<div class="add-row" id="row$(count)"><label" for="number_${count}">Number ${count+1}</label><input type="text" name="number_${count}" value=""></div>`);
count++;
}
$('.btn-remove').toggle(count > 0);
});
$(document).on('click', '.btn-remove', function() {
const $children = $container.children();
$children.last().remove();
let count = $children.length;
console.log(count)
$(this).toggle(count > 1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add" class="btn-add">Add Another Number</button> <button type="button" class="btn-remove hidden">Remove last</button>
<div id="dynamic_field"></div>
Also You could CLONE an existing row
$(function() {
const $container = $("#dynamic_field");
const getCount = () => $container.find(".add-row").length;
$('.btn-remove').toggle(getCount() > 1);
$('#add').click(function() {
let count = getCount();
if (count < 7) {
const $cloneDiv = $container.children().first().clone().appendTo($container);
$cloneDiv.find("input").val("").attr("name",`number${count+1}`);
$cloneDiv.find("label").text(`Number ${count+1}`);
}
$('.btn-remove').toggle(count > 0);
});
$(document).on('click', '.btn-remove', function() {
$container.find(".add-row").last().remove();
let count = getCount()
console.log(count)
$(this).toggle(count > 1);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="add" class="btn-add">Add Another Number</button> <button type="button" class="btn-remove hidden">Remove last</button>
<div id="dynamic_field">
<div class="add-row" id="1">
<label for="number_1">Number 1</label><input type="text " name="number_1 " value="" />
</div>
</div>
I am trying to make a calculator, simply my problem is this:
Page refreshes.
User clicks on any number and the number gets added to the First Number: nums_clicked h1.
If user clicks on an operator sign(+ - *), the clicked boolean becomes true.
If clicked is true, add the numbers clicked to the Second Number: nums_clicked
My problem is even if I click on an operator sign, it keeps adding the numbers I am clicking to the First Number: nums_clicked h1, why is that happening? It even happens while clicked is TRUE!
My
let numbers = [];
let first_num = "";
let second_num = "";
let clicked = false;
let result = false;
for (var i = 0; i < 9; i++) {
numbers[i] = parseInt(document.querySelectorAll("button")[i].innerText);
}
for (var i = 9; i < 12; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function() {
clicked = true;
});
}
if (!clicked && !result) {
for (let i = 0; i < 9; i++) {
if (clicked) {
break;
}
document.querySelectorAll("button")[i].addEventListener("click",
function() {
console.log("clicked = " + clicked);
first_num += this.innerText;
document.getElementById("firstNumber").innerText = "Number1: " + first_num;
});
}
}
if (clicked && !result) {
for (let i = 0; i < 9; i++) {
document.querySelectorAll("button")[i].addEventListener("click",
function() {
second_num += this.innerText;
document.getElementById("secondNumber").innerText = "Number2: " + second_num;
});
}
}
document.getElementById("result-btn").addEventListener("click",
function() {
result = true;
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<title></title>
</head>
<body>
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br>
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br>
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br>
<br>
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br>
<button id="result-btn" type="button" name="button">Result</button>
<h1 id="firstNumber">First Number: </h1>
<h1 id="secondNumber">Second Number: </h1>
<h1 id="result">Result: </h1>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Code:
Screenshot of index.html (Red part while clicked=false and blue part is while clicked=true:
Your main issue was that you were never creating the click events for the second number, because those were behind the if(!result.... Like Barmar mentioned, even if you created the click events for the second number, the events from the first number would be triggered also and it would still not work. Also you did not had anything for setting the actual results.
I made some changes on your code to make it simpler to understand, but still trying to follow your logic. Here you go:
let first_num;
let second_num;
let operation;
for (var i = 9; i < 12; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
operation = this.innerText;
});
}
for (let i = 0; i < 9; i++) {
document.querySelectorAll('button')[i].addEventListener('click', function () {
if (!operation) {
document.getElementById('firstNumber').innerText += this.innerText;
} else {
document.getElementById('secondNumber').innerText += this.innerText;
}
});
}
document.getElementById('result-btn').addEventListener('click', function () {
first_num = document.getElementById('firstNumber').innerText;
second_num = document.getElementById('secondNumber').innerText;
document.getElementById('result').innerText = calculate(
parseInt(first_num),
parseInt(second_num),
operation
);
});
function calculate(a, b, operation) {
if (operation === '+') {
return sum(a, b);
} else if (operation === '-') {
return minus(a, b);
} else if (operation === '*') {
return multiply(a, b);
}
}
function sum(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
<div class="container">
<button type="button" name="button">1</button>
<button type="button" name="button">2</button>
<button type="button" name="button">3</button>
<br />
<button type="button" name="button">4</button>
<button type="button" name="button">5</button>
<button type="button" name="button">6</button>
<br />
<button type="button" name="button">7</button>
<button type="button" name="button">8</button>
<button type="button" name="button">9</button>
<br />
<br />
<button type="button" name="button">+</button>
<button type="button" name="button">*</button>
<button type="button" name="button">-</button>
<br />
<button id="result-btn" type="button" name="button">Result</button>
<h1>First Number: <span id="firstNumber"></span></h1>
<h1>Second Number: <span id="secondNumber"></span></h1>
<h1>Result: <span id="result"></span></h1>
</div>
I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<script type="text/javascript">
var x = 0
document.write(x)
function button1() {
document.write(x++)
}
function button2(){
document.write(x--)
}
</script>
</body>
The problem is that you put ++ and -- after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.
Also, as mentioned, you have some trouble with document.write(). Consider the following documentation from the W3Schools page:
The write() method writes HTML expressions or JavaScript code to a
document.
The write() method is mostly used for testing. If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Thus, document.write() will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML like this:
var x = 0;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
Why don't you change your code a bit? Instead of document.write(x++) and document.write(x--) use document.write(++x) and document.write(--x).
The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.
Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.
Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.
document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.
Moreover, use addEventListener instead of inline event listeners:
var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function () {
// this function is executed whenever the user clicks the increment button
span.textContent = x++;
});
decrement.addEventListener('click', function () {
// this function is executed whenever the user clicks the decrement button
span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.
document write will delete full html:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
As in w3schools
try this instead
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<div id="value"></div>
<script type="text/javascript">
var x=0
var element = document.getElementById("value");
element.innerHTML = x;
function button1(){
element.innerHTML = ++x;
}
function button2(){
element.innerHTML = --x;
}
</script>
I changed the x-- and x++ to ++x and --x so the changes are immediatly. With this change your code would have worked aswell. showing 1 or -1.
HTML code for UI
<div class="card">
<div class="card-body">
<h5 class="card-title">How many guests can stay?</h5>
<div class="row">
<ul class="guestCounter">
<li data-btn-type="increment"><span class="romoveBtn"><i class="fa fa-plus"></i></span> </li>
<li class="counterText"><input type="text" name="guestCount" id="btnGuestCount" value="1" disabled /> </li>
<li data-btn-type="decrement"><span class="romoveBtn"><i class="fa fa-minus"></i></span></li>
</ul>
</div>
Java Script:
// set event for guest counter
$(".guestCounter li").on("click", function (element) {
var operationType = $(this).attr("data-btn-type");
//console.log(operationType);
var oldValue = $(this).parent().find("input").val();
//console.log(oldValue);
let newVal;
if (operationType == "increment") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$(this).parent().find("input").val(newVal);
});
var x = 1;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
if(x <= 0 ){
alert(' minimum value 0 // By Khaydarov Marufjon marvell_it academy uzb ')
return false ;
}
document.getElementById('output-area').innerHTML = --x;
}
input{
width: 70px;
background-color: transparent;
padding: 20px;
text-align: center;
}
button{
padding: 20px;
}
<input type='button' value="plus" onclick="button1()" />
<span id="output-area"></span>
<input type='button' value="minus" onclick="button2()" />
This question is very common. I have developed a solution with Bootstrap and pure JavaScript in another very similar thread here.
There is autoincrement input on keeping button pressed down.
Use ontouchstart and ontouchend instead than onmousedown and onmouseup method for mobile. To make it work for both mobile and desktop browser without headache use onpointerdown, onpointerup, onpointerleave
https://stackoverflow.com/a/70957862/13795525
function imposeMinMax(el) {
if (el.value != '') {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
var index = 0;
var interval;
var timeout;
var stopFlag=false;
function clearAll(){
clearTimeout(timeout);
clearInterval(interval);
}
function modIn(el) {
var inId = el.id;
if (inId.charAt(0) == 'p') {
var targetId = inId.charAt(2);
var maxValue = Number(document.getElementById(targetId).max);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue < maxValue){
stopFlag=false;
document.getElementById(targetId).value++;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index+1 >= maxValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value++;
}
index++;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
if (inId.charAt(0) == 'm') {
var targetId = inId.charAt(2);
var minValue = Number(document.getElementById(targetId).min);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue > minValue){
stopFlag=false;
document.getElementById(targetId).value--;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index-1 <= minValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value--;
}
index--;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Button example</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<button type='button' class='btn btn-danger btn-sm ' id='mbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='A' onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='B' onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='C' onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
</body>
</html>
i'm trying to do an price counter synchronizing with increment and decrement buttons, but the price is not changing when i click one of the buttons (+/-) this is not working, how can i solve this issue? Thanks!!!
$('#plus').click(function add() {
var $qtde = $("#quantity");
var a = $qtde.val();
a++;
$("#minus").attr("disabled", !a);
$qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());
$('#minus').click(function minust() {
var $qtde = $("#quantity");
var b = $qtde.val();
if (b >= 1) {
b--;
$qtde.val(b);
}
else {
$("#minus").attr("disabled", true);
}
});
/* On change */
$(document).ready(function()
{
function updatePrice()
{
var price = parseFloat($("#quantity").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total-price").val(total);
}
$(document).on("change, keyup, focus", "#quantity", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value=""/>
If you change your binding to update whenever there is a click on an input, you'll get the behavior that you are expecting.
$('#plus').click(function add() {
var $qtde = $("#quantity");
var a = $qtde.val();
a++;
$("#minus").attr("disabled", !a);
$qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());
$('#minus').click(function minust() {
var $qtde = $("#quantity");
var b = $qtde.val();
if (b >= 1) {
b--;
$qtde.val(b);
} else {
$("#minus").attr("disabled", true);
}
});
/* On change */
$(document).ready(function() {
function updatePrice() {
var price = parseFloat($("#quantity").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total-price").val(total);
}
// On the click of an input, update the price
$(document).on("click", "input", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value="" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="sp-quantity">
<div class="container" style=" font-size:14px; ">
<div class="sp-input">
<input type="text" class="quantity-input" value="1">
<div class="button" style="cursor: pointer;">
+
</div>
<div class="button" style="cursor: pointer;">
-
</div>
</div>
<p>custom filed</p>
<div class="sp-input">
<input type="text" class="quantity-input-db" value="1.8" step="1.8">
<div class="button" style="cursor: pointer;">
+
</div>
<div class="button" style="cursor: pointer;">
-
</div>
</div>
</div>
</div>
<script type="text/javascript">
// debugger;
$(document).ready(function () {
$(".button").on("click", function() {
var $db_value = $('.db_value').val();
var $quantity = $('.quantity_input').val();
var db_valu_fix = 1.8;
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quantity-input");
var oldValue_q = $input.val();
var $db_value = $button.closest('.sp-quantity').find("input.quantity-input-db");
var oldValue_db = $db_value.val();
console.log(oldValue_db);
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue_q) + 1;
newdbVal = parseFloat(oldValue_db) + 1;
//newdbVal.toFixed(2);
}
else {
if (oldValue_q > 0) {
newVal = parseFloat(oldValue_q) - 1;
newdbVal = parseFloat(oldValue_db) - 1;
newdbVal = Math.round(newdbVal * 100) / 100;
} else {
newVal = 1;
}
}
$input.val(newVal);
$db_value.val(newdbVal);
});
// $(".ddd").on("click", function(step) {
// var a=$(".quantity-input").val();
// var attr=$(".quantity-input").attr(step);
// var getValue=a/1;
// console.log(attr);
// });
});
</script>
</body>
</html>
I have tried searching this up many times. I have come close, but have not figured this out yet. What I am trying to do is when the user reaches a certain amount of clicks, a button pops up.
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" onclick="hi()" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" style="visibility:hidden;" value="Button" id="Sir" />
</body>
</html>
Here is the javascript:
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
}
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
I think I need to assign the count variable outside the hi() function, but I don't know how to do that (or if that's possible)
From mobile so excuse my pseudo code
Is you're using jquery, you can store the value in a
$(btn).data('clicks')
Otherwise define a global variable above your hi function.
Then you need to put your logic of if(clicks > 20) inside your hi function
var count = 0;
function store(){
alert(count);
}
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 4) document.getElementById('Sir').style.display = 'inline-block';
}
#Sir{display:none;}
<h1>Click the Button</h1>
<input type="button" id="countButton" onclick="hi()" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" value="Button" id="Sir" />
Try this:
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<!-- <input type="button" id="countButton" onclick="store()" value="Store"/> -->
<input type="button" style="visibility:hidden;" value="Button" id="Sir" />
<script>
var count = 0;
var clickbutton = document.getElementById("countButton");
var showbutton = document.getElementById("Sir");
var amountstatus = document.getElementById("amount");
clickbutton.onclick = function(){
if(count < 3){
count++;
amountstatus.innerHTML = count;
}
else{
showbutton.style.visibility = "visible";
}
}
</script>
</body>
</html>
Check I put this <input type="button" id="countButton" onclick="store()" value="Store"/> in comments, that's why you must not have two id with the same name.
Hello can you please give a try to following code below:
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
}
Only change i think to move if condition inside hi function. Hope it works
I agree with Zakk. Storing the value in a data attribute would be the best way to do this. Here's how I'd code it.
$(function() {
$( "#countButton" ).on( "click", function() {
var clicks = $( this ).data( "clicks" );
clicks++;
// Display the clicks.
$( "#amount" ).html( clicks );
$( this ).data( "clicks", clicks );
// Check to see if the sir button should be displayed.
if( clicks >= 20 ) {
$( "#Sir" ).css( "visibility", "visible" );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" data-clicks="0" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" style="visibility: hidden;" value="Button" id="Sir" />
</body>
</html>
Your condition is outside the function hi(), so it is checked once when the file loaded, no when hi() is call.
So you may put your condition inside hi().
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
}