How to disable a key on key press on javascript? - javascript

This how the code works, when i press left key button (e.keyCode =39) it jumps up to the next page. All in all there are 7 ($('#btn-group input').length) pages in my program. I tried using preventDefault(); command inside the condition where the comment i dont know hat will put here but i wont work on my program( it jumps to page 8 and returns to page 7). Thank you
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
if (new_num == $('#btn-group input').length) {
// i dont know what will put here
}
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" style ="background-color:#66cdaa" value="1">
<input class="btn butt" type="button" id="btn_page2" style ="background-color:#66cdaa" value="2">
<input class="btn butt" type="button" id="btn_page3" style ="background-color:#66cdaa" value="3">
<input class="btn butt" type="button" id="btn_page4" style ="background-color:#66cdaa" value="4">
<input class="btn butt" type="button" id="btn_page5" style ="background-color:#66cdaa" value="5">
<input class="btn butt" type="button" id="btn_page6" style ="background-color:#66cdaa" value="6">
<input class="btn butt" type="button" id="btn_page7" style ="background-color:#66cdaa" value="7">
<input class="btn butt active-btn" type="button" style ="background-color:#66cdaa" id="next_btn" value="Next">
</div>

You can call this function on keypress of an element.
function ValidateClientname(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
} else if (e) {
var charCode = e.which;
} else {
return true;
}
alert (charCode); // this will give you key value and you can pass it in if statement like if ((charCode > 47 && charCode < 58) || (charCode ==8))
if ((charCode > 47 && charCode < 58) )
return true;
else
return false;
} catch (err) {
alert(err.Description);
}
}

You need to "short circuit" your function before it reaches the .toggle function. This will prevent all further execution of the function.
$(function() {
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '39') {
var old_num = $('#btn-group').find('.active-btn').val();
var new_num = +old_num + 1;
// if new number is for a page that doesnt exist
// short circuit
if (new_num == $('#btn-group input').length) {
return false;
}
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
});
.active-btn {
background-color: red !important;
}
.page {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<input class="btn butt active-btn" type="button" id="btn_page1" style="background-color:#66cdaa" value="1" />
<input class="btn butt" type="button" id="btn_page2" style="background-color:#66cdaa" value="2" />
<input class="btn butt" type="button" id="btn_page3" style="background-color:#66cdaa" value="3" />
<input class="btn butt" type="button" id="btn_page4" style="background-color:#66cdaa" value="4" />
<input class="btn butt" type="button" id="btn_page5" style="background-color:#66cdaa" value="5" />
<input class="btn butt" type="button" id="btn_page6" style="background-color:#66cdaa" value="6" />
<input class="btn butt" type="button" id="btn_page7" style="background-color:#66cdaa" value="7" />
<input class="btn butt active-btn" type="button" style="background-color:#66cdaa" id="next_btn" value="Next" />
</div>
</div>
<div id="pages_all">
<div id="page1" class="page active-page" style="display:block">Page 1</div>
<div id="page2" class="page">Page 2</div>
<div id="page3" class="page">Page 3</div>
<div id="page4" class="page">Page 4</div>
<div id="page5" class="page">Page 5</div>
<div id="page6" class="page">Page 6</div>
<div id="page7" class="page">Page 7</div>
</div>

you can try this:
$('.btn').click(function(){
$(this).addClass('active-btn').siblings().removeClass('active-btn');
});
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
var old_num = parseInt($('#btn-group').find('.active-btn').val());
var new_num = old_num+1;
if (new_num == $('#btn-group input').length) {
new_num=1;
}
if (e.keyCode == '39') {
$('#page' + old_num).toggle('slide', {
direction: 'left',
complete: function() {
$('#btn_page' + old_num).removeClass('active-btn');
$('#page' + old_num).clearQueue();
$('#page' + old_num).removeClass('active-page');
$('#page' + new_num).addClass('active-page');
$('#btn_page' + new_num).addClass('active-btn');
$('#page' + new_num).toggle('slide', {
direction: 'right'
});
}
});
}
}
.pager:not(:first-child) { display:none;}
.butt{background-color:#66cdaa}
.active-btn {background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p id="page1" class="pager" style="display:inline-block">1</p>
<p id="page2" class="pager">2</p>
<p id="page3" class="pager">3</p>
<p id="page4" class="pager">4</p>
<p id="page5" class="pager">5</p>
<p id="page6" class="pager">6</p>
<p id="page7" class="pager">7</p>
<div class="pull-right" id="btn_all">
<input class="btn active-btn" type="button" id="prev_btn" style="background-color:#66cdaa" style="width:70px;margin:1em" value="Prev.">
<div class="btn-group" id="btn-group">
<br>
<input class="btn butt active-btn" type="button" id="btn_page1" value="1">
<input class="btn butt" type="button" id="btn_page2" value="2">
<input class="btn butt" type="button" id="btn_page3" value="3">
<input class="btn butt" type="button" id="btn_page4" value="4">
<input class="btn butt" type="button" id="btn_page5" value="5">
<input class="btn butt" type="button" id="btn_page6" value="6">
<input class="btn butt" type="button" id="btn_page7" value="7">
<input class="btn butt" type="button" id="next_btn" value="Next">
</div>

I think you can just use a switch statement to test for the key :
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
I have written my own version of what you're trying to do (at least what I think you're trying to do), feel free to use that as an inspiration.
I use CSS3 transitions instead of jQuery's toggle.
const pagesCount = 7;
let currentPage = 1;
// ---- Generating buttons and pages
const $btnGroup = $("#btn-group");
const $pagesContainer = $("#pages");
for(let i=1; i<=pagesCount; i++){
$pagesContainer.append(`<div class='page'><h2>PAGE ${i}</h2></div>`);
$btnGroup.append(`<input type='button' value='${i}'/>`);
}
const $btns = $btnGroup.find("input")
$btns.first().addClass("active");
const $pages = $(".page");
$pages.not(":eq(0)").addClass("toRight");
// ---- End generating buttons
$btns.click( function() {
currentPage = +$(this).val();
changePage(currentPage);
});
changePage = (pageNum) => {
$pages.removeClass("toLeft toRight");
$pages.slice(0, pageNum-1).addClass("toLeft");
$pages.slice(pageNum, pagesCount).addClass("toRight");
updateButtons();
}
updateButtons = () => {
$btns.removeClass("active");
$btns.eq(currentPage-1).addClass("active");
}
nextPage = () => {
return currentPage===pagesCount ? null : changePage(++currentPage);
}
prevPage = () => {
return currentPage===1 ? null : changePage(--currentPage);
}
document.onkeydown = (e) => {
switch (e.keyCode) {
case 37 :
prevPage(); break;
case 39 :
nextPage(); break;
}
}
$("#prev_btn").click(prevPage);
$("#next_btn").click(nextPage);
#pages {
position: relative;
width: 400px;
height: 200px;
overflow: hidden;
}
#pages .page {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #000;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-transition: all 0.3s ease-in-out;
transition: all 0.3s ease-in-out;
}
#pages .page:nth-child(even) {
background: #008000;
}
#pages .page:nth-child(odd) {
background: #00f;
}
#pages .page.toLeft {
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
#pages .page.toRight {
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
#pages .page h2 {
color: #fff;
}
nav {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
width: 400px;
}
nav input {
background-color: #66cdaa;
}
nav #btn-group input {
margin: 0 5px;
}
nav #btn-group input.active {
background: #00f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pages"></div>
<nav>
<input class="btn active-btn" type="button" id="prev_btn" value="Prev.">
<div id="btn-group"></div>
<input class="btn butt active-btn" type="button" id="next_btn" value="Next">
</nav>
One could also imagine a solution where all the pages would be in a line, forming a ribbon, and the pagination buttons would just translate the whole ribbon to the right place, to show the correct page transform : translateX(n%)
I hope it helps.

Related

button to be visible after it fulfilled requirements

Requirements:
When more than one button is clicked, users will then be able to click on "proceed-button".
Current situation:
I am making a cinema web page. Users will get to choose their preferred seats. When the seat is chosen, they will then be able to click on "proceed-button" to pay. However, i have difficulty implementing this function. I know that i needed to use the visibility-hidden function.
The following is my code:
var buttons = document.getElementsByClassName("button");
var count = 0;
var disp = document.getElementById("display");
for (let i = 0, l = buttons.length; i < l; i++) {
buttons[i].addEventListener('click', function() {
buttons[i].classList.toggle('active');
if (this.classList.contains("active")) {
count++;
if (this.classList.contains("active") > 1) {
function proceedButton() {
document.getElementById("pButton").style.display = "visible";
}
} else {
document.getElementById("pButton").style.display = "block";
}
} else {
count--;
}
disp.innerHTML = count;
})
}
function proceedButton() {
var x = document.getElementById("payment-section");
if (x.style.display === "none") {
x.style.display = "block";
}
}
.button {
background-color: #423F3E;
height: 30px;
width: 30px;
margin: 5px;
border-radius: 10px;
border: none;
float: left;
}
.button.active {
background-color: #F7EA00 !important;
}
<div class="seats-layout">
<div class="row">
<input type="button" id="button1" class="button" />
<input type="button" id="button2" class="button" />
<input type="button" id="button3" class="button" />
</div>
<div class="row">
<input type="button" id="button1" class="button" />
<input type="button" id="button2" class="button" />
<input type="button" id="button3" class="button" />
</div>
</div>
<p> Button Clicked <span id="display">0</span> Times</p>
<input type="submit" value="Proceed" onclick="proceedButton()" id="pButton" class="proceed-button" />
```
<div id="payment-section" style="display: none">
<h1>Payment</h1>
</div>
```
Demo page
use document.querySelectorAll to returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.
function proceedButton() {
var x = document.getElementById("payment-section");
var item_click = document.querySelectorAll('.active').length;
if (item_click>1) {
x.style.display = "block";
}else{
x.style.display = "none";
}
}

The if/else statement

I want to show a suitable button with if/else statement. For example, when none of the checkboxes are checked I want to display the disabled button, but when one or more checkboxes are checked I want to display another button.
Js
$("#checkAll").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Html
<input type="checkbox" id="checkAll" style="margin-left:-10px" />
<input type="checkbox" style="margin-left:5px" />
<input type="checkbox" style="margin-left:5px" />
<div class="ml-2">
if(checked){
<button type="button" class="btn btn-danger ">Delete</button>
}else{
<button type="button" class="btn btn-outline-danger" disabled>Delete</button>
}
</div>
As long the button is right next to the other button you don't even need no javascript for that.
Thats of course quite a simple approach and can easily be 'hacked' via the Inspector. But if you do it with Javascript it can be hacked as well.
.checkbox + .button {
opacity: 0.5;
pointer-events: none;
}
.checkbox:checked + .button {
display: none;
}
.checkbox + .button + .button2 {
display: none;
}
.checkbox:checked + .button + .button2 {
display: block;
}
<input type="checkbox" class="checkbox">
<div class="button">Button 1</div>
<div class="button2">Button 2</div>
When none of the checkboxes are checked I want to display the disabled button, but when 1 or more checkbox are checked I want to display another button.
You can include both buttons in the html with one hidden - then in your js show/hide them as appropriate.
A basic implementation would to check:
if ($("input:checkbox:checked").length == 0) {
then use .show() .hide() on each of the buttons as required.
This can be made more streamlined, eg using .toggle($("input:checkbox:checked").length == 0) but this is to show the explicit if/else as requested in the title.
$("#checkAll").change(function() {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
$("input:checkbox").change(function() {
if ($("input:checkbox:checked").length == 0) {
$(".ml-2>.btn-danger").hide();
$(".ml-2>.btn-outline-danger").show();
} else {
$(".ml-2>.btn-outline-danger").hide();
$(".ml-2>.btn-danger").show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll" />
<input type="checkbox" />
<input type="checkbox" />
<div class="ml-2">
<button type="button" class="btn btn-danger " style='display:none;' >Delete</button>
<button type="button" class="btn btn-outline-danger" disabled>Delete (disabled)</button>
</div>
If - as outlined - you want to have two buttons (rather than, say, one button where you change the classes and properties) you can:
listen for when one of the checkboxes changes
then check the collective state of all the checkboxes
then, depending on that collective state, apply:
Element.classList.add('show')
Element.classList.remove('show')
to show and hide the respective buttons.
Working Example:
// DECLARE VARIABLES
const btnDanger = document.querySelector('.btn-danger');
const btnOutlineDanger = document.querySelector('.btn-outline-danger');
const checkBoxes = document.querySelectorAll('input[type="checkbox"]');
// FUNCTION: REVIEW CHECKBOXES
const reviewCheckBoxes = () => {
let allUnchecked = true;
checkBoxes.forEach((checkBox) => {
if (checkBox.checked) {
allUnchecked = false;
}
});
if (allUnchecked === true) {
btnDanger.classList.remove('show');
btnOutlineDanger.classList.add('show');
}
else if (allUnchecked === false) {
btnDanger.classList.add('show');
btnOutlineDanger.classList.remove('show');
}
}
// ADD EVENT LISTENERS TO EACH OF THE CHECKBOXES
checkBoxes.forEach((checkBox) => {
checkBox.addEventListener('change', reviewCheckBoxes);
});
input[type="checkbox"] {
margin-left: 10px;
}
.btn-danger,
.btn-outline-danger,
input[type="checkbox"]#checkAll {
margin-left: 10px;
}
.btn-danger,
.btn-outline-danger {
display: none;
}
.btn-danger.show,
.btn-outline-danger.show {
display: inline-block;
}
<input type="checkbox" id="checkAll" />
<input type="checkbox" />
<input type="checkbox" />
<button type="button" class="btn btn-danger ">Delete</button>
<button type="button" class="btn btn-outline-danger show" disabled>Delete</button>

Trying to add Go Back Function. (Previous) Button to my Multi Steps Form using Javascript

I am trying to add Back buton to my existing Script without success so far. I like this script because it also has a Validation process. I tried another code that has Previous button working, but no validation which made my project useless..
Here is my Javascript code below:
<script>
//Validation & Steps
$(document).ready(function ()
{
var navListItems = $('div.setup-panel div a');
allWells = $('.setup-content');
allNextBtn = $('.nextBtn');
allPrevBtn = $('.prevBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href'));
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-success').addClass('btn-default');
$item.addClass('btn-success');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
}
});
allNextBtn.click(function ()
{
var curStep = $(this).closest(".setup-content");
curStepBtn = curStep.attr("id");
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn +
'"]').parent().next().children("a");
curInputs = curStep.find("input[type='url'],input[type='checkbox'],input[type='text'],input[type='email'],input[type='radio']"); //
isValid = true;
$(".form-group").removeClass("has-error");
for (var i = 0; i < curInputs.length; i++)
{
if (!curInputs[i].validity.valid)
{
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid) nextStepWizard.removeAttr('disabled').trigger('click');
});
// Back button click action
allPrevBtn.click(function()
{
curStepBtn = curStep.attr("id");
curStep = curStep - 2;
allPrevBtn.trigger('click');
nextStepWizard.removeAttr('disabled').trigger('click');
allWells.hide();
})
$('div.setup-panel div a.btn-success').trigger('click');
});
</script>
I was returned to source of your code, this is full code with back button:
<html >
<head>
<meta charset="utf-8"/>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<style>
body{
margin-top:40px;
}
.stepwizard-step p {
margin-top: 10px;
}
.stepwizard-row {
display: table-row;
}
.stepwizard {
display: table;
width: 100%;
position: relative;
}
.stepwizard-step button[disabled] {
opacity: 1 !important;
filter: alpha(opacity=100) !important;
}
.stepwizard-row:before {
top: 14px;
bottom: 0;
position: absolute;
content: " ";
width: 100%;
height: 1px;
background-color: #ccc;
z-order: 0;
}
.stepwizard-step {
display: table-cell;
text-align: center;
position: relative;
}
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.428571429;
border-radius: 15px;
}
</style>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn'),
allPrevBtn = $('.prevBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
allPrevBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
prevStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().prev().children("a");
prevStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
</script>
</head>
<body>
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Step 1</p>
</div>
<div class="stepwizard-step">
2
<p>Step 2</p>
</div>
<div class="stepwizard-step">
3
<p>Step 3</p>
</div>
</div>
</div>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 1</h3>
<div class="form-group">
<label class="control-label">First Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name</label>
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Last Name" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label class="control-label">Company Name</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Name" />
</div>
<div class="form-group">
<label class="control-label">Company Address</label>
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Enter Company Address" />
</div>
<button class="btn btn-warning prevBtn btn-lg pull-left" type="button" >Back</button>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<h3> Step 3</h3>
<button class="btn btn-success btn-lg pull-right" type="submit">Finish!</button>
</div>
</div>
</div>
</form>
</div>
</body>
</html>

Jquery fuction on multiple elements

As you can see in the Snippet code below, I have two buttons and one input for each container. Now, The input calc and sums up the number of clicks on the 2 buttons in the same container. But, it's only working for the first container. How can I make it work for each container separately without setting an ID for each group of inputs?
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.click').click(function() {
var val1 = +$('.val1').val();
var val2 = +$('.val2').val();
$('.count').val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
First get the parent of the clicked element, then search for the .valx elements only within this parent.
$('.click').click(function (e) {
var $parent = $(e.currentTarget).parent();
var val1 = +$parent.find('.val1').val();
var val2 = +$parent.find('.val2').val();
$parent.find('.count').val(val1 + val2);
});
This way, you can have as many counters as you want.
Update:
You can also add the +1 feature in the same click event. Like so:
$('.click').click(function (e) {
var $input = $(e.currentTarget);
var $parent = $input.parent();
// Value ++
$input.val($input.val() + 1);
// Set the total count
var val1 = +$parent.find('.val1').val();
var val2 = +$parent.find('.val2').val();
$parent.find('.count').val(val1 + val2);
});
Got it working for you!
Use $(this).parent().find();
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.click').click(function() {
var val1 = + $(this).parent().find('.val1').val();
var val2 = + $(this).parent().find('.val2').val();
$(this).parent().find('.count').val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
Here is the Solution for You:
$(function() {
$('.click').on('click', function() {
$(this).val(parseInt($(this).val()) + 1);
});
$('.val1').click(function() {
var val1 = +$(this).val();
var val2 = +$($(this).siblings('.val2')).val();
$($(this).siblings('.count')).val(val1+val2);
});
$('.val2').click(function() {
var val1 = +$($(this).siblings('.val1')).val();
var val2 = +$(this).val();
$($(this).siblings('.count')).val(val1+val2);
});
});
.cont {
border: 1px solid red;
padding: 10px;
margin-bottom: 5px;
}
h1 {
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>First</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>
<h1>Second</h1>
<div class="cont">
<input type="text" class="count" value="0">
<input type="button" class="click val1" value="0">
<input type="button" class="click val2" value="0">
</div>

How to change value of an input with buttons

I have a form in which I want the user to be able to set the value in 15 minute increments with the use of two buttons.
Here is what I have so far:
<div class="form-group">
<label class="control-label " for="time">Authorisation Duration</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
<input type="text" class="form-control" id="time" name="time" value="00:00">
<span class="input-group-btn">
<button class="btn btn-info" type="button">+ 15 Minutes</button>
<button class="btn btn-danger" type="button">- 15 Minutes</button>
</span>
</div>
</div>
I am wondering how to go about making it change the value according to which button is pressed. Also, how to I make sure it does not go into the negative.
Thank you in advance.
An example with native functions ( stepUp() & stepDown() ):
function incr() {
document.getElementById("myTime").stepUp(15);
}
function decr() {
document.getElementById("myTime").stepDown(15);
}
Time: <input type="time" id="myTime" value="16:32:55">
<p>Click the button to increment the value of the time field by 10 minutes (each time you click).</p>
<button onclick="incr()">+ 15</button>
<button onclick="decr()">- 15</button>
An example ( with jQuery ) - integers:
// Set counter default to zero
var counter = 0
// Display total
$("#counter").text(counter);
// When button is clicked
$("#add").click(function(){
//Add 10 to counter
counter = counter + 15;
// Display total
$("#counter").text(counter);
});
//Subtract
$("#subtract").click(function(){
counter = counter - 15;
$("#counter").text(counter);
});
// Reset
$("#reset").click(function(){
counter = 0;
$("#counter").text(counter);
});
body{
font-size: 1.5em;
font-family: 'Oswald', sans-serif;
font-weight: 700;
}
.button_group{
width: 100%;
display: flex;
}
button {
font-family: 'Oswald', sans-serif;
font-size: 1em;
font-weight: 300;
border: 0;
padding: 1em 2em;
margin: 0.5em 0;
width: 100%;
background: rgba(0,0,0,0.1);
-webkit-transition:.2s;
}
button:nth-child(2){
margin: 0.5em;
}
button:hover{
background: rgba(0,0,0,0.3);
}
button:active{
background: rgba(0,0,0,0.5);
}
#add:active{
-webkit-transform:translateY(-1em);
}
#subtract:active{
-webkit-transform:translateY(1em);
}
#counter{
font-size: 3em;
text-align: center;
width: 100%;
display block;
background: rgba(0,0,0,0.1);
padding: 2em 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter"></div>
<div class="button_group">
<button id="subtract">- 15</button>
<button id="reset">Reset</button>
<button id="add">+ 15</button>
</div>
Sources:
CSS tricks
Good example ( with Bootstrap & jQuery )
Example
This should help
$(function()
{
$(".btn-inc").click(function(){
var v = $(this).data("val");
$("#time").val(addMinutes($("#time").val(), v));
});
/*http://stackoverflow.com/questions/13338960/add-20-minutes-in-string-time-and-populate-it-in-the-textbox-or-alert-it*/
function addMinutes(time/*"hh:mm"*/, minsToAdd/*"N"*/) {
function z(n){
return (n<10? '0':'') + n;
}
var bits = time.split(':');
var mins = bits[0]*60 + (+bits[1]) + parseInt(minsToAdd);
if(mins < 0) return time;
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label " for="time">Authorisation Duration</label>
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
<input type="text" class="form-control" id="time" name="time" value="00:00">
<span class="input-group-btn">
<button class="btn-inc btn btn-info" data-val="15" type="button">+ 15 Minutes</button>
<button class="btn-inc btn btn-danger" data-val="-15" type="button">- 15 Minutes</button>
</span>
</div>
</div>
You can use native html5 time input:
<input type="time" step="900">
Try it:
<input type="time" step="900">
The disadvantage is that is bad supported on Firefox and Safari so you can use this as alternative:
<input type="number" min="0" max="100" step="5">
<input type="range" min="0" max="15" step="5">

Categories

Resources