I have been trying to get a plus minus button integrated into my number input. I have been able to update the field between the buttons with the new value however am trying to get that value to populate a second area (specifically a button) If I select the number input and click up or down arrows both the input and the button text are successfully updating, I am just stuck on mingling the two together.
How do I get the button to load the value of the number field after clicking the plus and minus buttons?
var adultModal = document.getElementById("adultModal");
var adultBtn = document.getElementById("guests");
var adultSpan = document.getElementsByClassName("adultClose")[0];
adultBtn.onclick = function() {
adultModal.style.display = "block";
}
adultSpan.onclick = function() {
adultModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == adultModal) {
adultModal.style.display = "none";
}
}
// NUMBER FIELD PLUS / MINUS SCRIPT
function incrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal)) {
parent.find('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
}
function decrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal) && currentVal > 0) {
parent.find('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
}
$('.input-group').on('click', '.button-plus', function(e) {
incrementValue(e);
});
$('.input-group').on('click', '.button-minus', function(e) {
decrementValue(e);
});
function updateGuests() {
let adultNumb = document.getElementById("adultQuantity");
let produceAdult = document.getElementById('adultValue');
produceAdult.innerHTML = adultNumb.value;
let childNumb = document.getElementById("childQuantity");
let produceChild = document.getElementById('childValue');
produceChild.innerHTML = childNumb.value;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
/* The Close Button */
.adultClose,
.childClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* INPUT NUMBER PLUS/MINUS BUTTONS */
input,
textarea {
border: 1px solid #eeeeee;
box-sizing: border-box;
margin: 0;
outline: none;
padding: 10px;
}
input[type="button"] {
-webkit-appearance: button;
cursor: pointer;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.input-group {
clear: both;
margin: 15px 0;
position: relative;
}
.input-group input[type='button'] {
background-color: #eeeeee;
min-width: 38px;
width: auto;
transition: all 300ms ease;
}
.input-group .button-minus,
.input-group .button-plus {
font-weight: bold;
height: 38px;
padding: 0;
width: 38px;
position: relative;
}
.input-group .quantity-field {
position: relative;
height: 38px;
left: -6px;
text-align: center;
width: 62px;
display: inline-block;
font-size: 13px;
margin: 0 0 5px;
resize: vertical;
}
.button-plus {
left: -13px;
}
input[type="number"] {
-moz-appearance: textfield;
-webkit-appearance: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Guests</h3>
<button id="guests" type="button" class="adults">
<span class="bw-toggle__value"><span id="adultValue">2</span> Adults <span class="bw-divide">/</span> <span id="childValue">0</span> Children</span>
</button>
<!-- Adult Modal -->
<div id="adultModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="adultClose">×</span>
<div class="input-group">
ADULTS
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="2" name="quantity" class="quantity-field" id="adultQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
<div class="input-group">
CHILDREN
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="0" name="quantity" class="quantity-field" id="childQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
</div>
</div>
Just call updateGuests() in your increment and decrement functions. You were 99% there.
I'd encourage you to move away from jQuery. You're halfway there with this code anyway, and it's a crutch against robust learning of JavaScript. These operations are simple enough that you just don't need it. See https://youmightnotneedjquery.com.
var adultModal = document.getElementById("adultModal");
var adultBtn = document.getElementById("guests");
var adultSpan = document.getElementsByClassName("adultClose")[0];
adultBtn.onclick = function() {
adultModal.style.display = "block";
}
adultSpan.onclick = function() {
adultModal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == adultModal) {
adultModal.style.display = "none";
}
}
// NUMBER FIELD PLUS / MINUS SCRIPT
function incrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal)) {
parent.find('input[name=' + fieldName + ']').val(currentVal + 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
updateGuests();
}
function decrementValue(e) {
e.preventDefault();
var fieldName = $(e.target).data('field');
var parent = $(e.target).closest('div');
var currentVal = parseInt(parent.find('input[name=' + fieldName + ']').val(), 10);
if (!isNaN(currentVal) && currentVal > 0) {
parent.find('input[name=' + fieldName + ']').val(currentVal - 1);
} else {
parent.find('input[name=' + fieldName + ']').val(0);
}
updateGuests();
}
$('.input-group').on('click', '.button-plus', function(e) {
incrementValue(e);
});
$('.input-group').on('click', '.button-minus', function(e) {
decrementValue(e);
});
function updateGuests() {
let adultNumb = document.getElementById("adultQuantity");
let produceAdult = document.getElementById('adultValue');
produceAdult.innerHTML = adultNumb.value;
let childNumb = document.getElementById("childQuantity");
let produceChild = document.getElementById('childValue');
produceChild.innerHTML = childNumb.value;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 5px 20px;
border: 1px solid #888;
width: 280px;
position: relative;
}
/* The Close Button */
.adultClose,
.childClose {
color: #aaaaaa;
position: absolute;
right: 5px;
top: 0px;
font-size: 22px;
font-weight: bold;
cursor: pointer;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* INPUT NUMBER PLUS/MINUS BUTTONS */
input,
textarea {
border: 1px solid #eeeeee;
box-sizing: border-box;
margin: 0;
outline: none;
padding: 10px;
}
input[type="button"] {
-webkit-appearance: button;
cursor: pointer;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
.input-group {
clear: both;
margin: 15px 0;
position: relative;
}
.input-group input[type='button'] {
background-color: #eeeeee;
min-width: 38px;
width: auto;
transition: all 300ms ease;
}
.input-group .button-minus,
.input-group .button-plus {
font-weight: bold;
height: 38px;
padding: 0;
width: 38px;
position: relative;
}
.input-group .quantity-field {
position: relative;
height: 38px;
left: -6px;
text-align: center;
width: 62px;
display: inline-block;
font-size: 13px;
margin: 0 0 5px;
resize: vertical;
}
.button-plus {
left: -13px;
}
input[type="number"] {
-moz-appearance: textfield;
-webkit-appearance: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Guests</h3>
<button id="guests" type="button" class="adults">
<span class="bw-toggle__value"><span id="adultValue">2</span> Adults <span class="bw-divide">/</span> <span id="childValue">0</span> Children</span>
</button>
<!-- Adult Modal -->
<div id="adultModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="adultClose">×</span>
<div class="input-group">
ADULTS
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="2" name="quantity" class="quantity-field" id="adultQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
<div class="input-group">
CHILDREN
<input type="button" value="-" class="button-minus" data-field="quantity">
<input type="number" step="1" max="" value="0" name="quantity" class="quantity-field" id="childQuantity" onchange="updateGuests()">
<input type="button" value="+" class="button-plus" data-field="quantity">
</div>
</div>
</div>
Related
Any time I have elements within my div ".packagebuilder" get class ".shown" added it adds code to fluidly transition. It works when the pricing table appears but not when all the other elements come into view. When ".hidden" gets added it should fluidly go back into place, but it doesn't transition at all, just immediately flashes back. What am I missing? Appreciate any help.
.hidden {
opacity: 0;
max-height: 0px;
transition: max-height 0s cubic-bezier(0, 1, 0, 1) 0s;
position:absolute;
top:-100000px;
}
.shown {
opacity: 1;
max-height: 1000px;
transition: max-height 1s ease-in-out 0s;
position:relative;
}
This is the code. Anything with the class "hidden" will get "shown" added onclick of an input.
var seoSelect = document.querySelector("select#seo");
var designSelect = document.querySelector("select#design");
var anySelect = document.querySelector(".packagebuilder select");
var seoOption = document.querySelector(".seo.option");
var designOption = document.querySelector(".design.option");
var anyOption = document.querySelector(".packagebuilder .option");
var estimateTable = document.querySelector(".estimate");
//Price Table Items
var seofirstmonthitem = document.querySelector(".item.seofirstmonth");
var seosetupfeeitem = document.querySelector(".item.setupfee");
var designdeposititem = document.querySelector(".item.designdeposit");
var designpayoffitem = document.querySelector(".item.designpayoff");
var seomonthlyitem = document.querySelector(".item.seomonthly");
var dueToday = document.querySelector(".today #val");
var dueLater = document.querySelector(".later #val");
var dueMonthly = document.querySelector(".monthly #val");
function hidePriceTable() {
$(estimateTable).addClass("hidden");
$(estimateTable).removeClass("shown");
$(".disclaimer.pricing").addClass("hidden");
$(".disclaimer.pricing").removeClass("shown");
$(".button.package").addClass("hidden");
$(".button.package").removeClass("shown");
}
function showPriceTable() {
$(estimateTable).removeClass("hidden");
$(estimateTable).addClass("shown");
$(".disclaimer.pricing").removeClass("hidden");
$(".disclaimer.pricing").addClass("shown");
$(".button.package").removeClass("hidden");
$(".button.package").addClass("shown");
}
function HideSE0() {
$(seoOption).addClass("hidden");
$(seoOption).removeClass("shown");
}
function ShowSEO() {
$(seoOption).addClass("shown");
$(seoOption).removeClass("hidden");
}
function HideDesign() {
$(designOption).addClass("hidden");
$(designOption).removeClass("shown");
}
function ShowDesign() {
$(designOption).addClass("shown");
$(designOption).removeClass("hidden");
}
function hideSEOcontent() {
$(".item.seofirstmonth").hide();
$(".item.seomonthly").hide();
$(".item.setupfee").hide();
$('select#seo').prop('selectedIndex', null);
$("input#seosetup").val("0");
$("input#seovalue").val("0");
HideSE0();
}
function showSEOcontent() {
$(".item.seofirstmonth").show();
$(".item.seomonthly").show();
$(".item.setupfee").show();
ShowSEO();
}
function hideDesigncontent() {
$(".item.designdeposit").hide();
$(".item.designpayoff").hide();
$('select#design').prop('selectedIndex', null);
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
HideDesign();
}
function showDesigncontent() {
$(".item.designdeposit").show();
$(".item.designpayoff").show();
ShowDesign();
}
function hideAll() {
hideSEOcontent();
hidePriceTable();
HideDesign();
HideSE0();
}
hideAll();
$(function () {
setInterval(constantChecker, 1);
});
/// Web Design Package Choices + Pricing /////////////////////////////////////////////////
function designSelectValues() {
// Set Default values
$('select#design').prop('selectedIndex', null);
//Check for new package choice
$(designSelect).change(function () {
if (designSelect.value == "1") {
$("input#designdeposit").val("1500");
$("input#designpayoff").val("1500");
$("input#designtotal").val("3000");
} else if (designSelect.value == "2") {
$("input#designdeposit").val("2500");
$("input#designpayoff").val("2500");
$("input#designtotal").val("5000");
} else if (designSelect.value == "3" || designSelect.value == "0" ) {
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
} else {
$("input#designdeposit").val("1500");
$("input#designpayoff").val("1500");
$("input#designtotal").val("3000");
}
});
}
/// SEO Package Choices + Pricing /////////////////////////////////////////////////
function seoSelectValues() {
// Set Default values
$('select#seo').prop('selectedIndex', null);
//Check for new package choice
$(seoSelect).change(function () {
if (seoSelect.value == "1") {
$("input#seosetup").val("500");
$("input#seovalue").val("750");
} else if (seoSelect.value == "2") {
$("input#seosetup").val("1000");
$("input#seovalue").val("1500");
} else if (seoSelect.value == "3") {
$("input#seosetup").val("1500");
$("input#seovalue").val("2500");
} else if (seoSelect.value == "4" || seoSelect.value == "0" ) {
$("input#seosetup").val("0");
$("input#seovalue").val("0");
} else {
$("input#seosetup").val("500");
$("input#seovalue").val("750");
}
});
}
// When service added, activate options and values ////////////////////////////////////
$('#chooseseo').change(function () {
if (!$('#chooseseo').is(':checked')) {
hideSEOcontent();
$("input#seosetup").val("0");
$("input#seovalue").val("0");
} else if ($('#chooseseo').is(':checked')) {
showSEOcontent();
seoSelectValues();
}
});
$('#choosedesign').change(function () {
if (!$('#choosedesign').is(':checked')) {
hideDesigncontent();
$("input#designdeposit").val("0");
$("input#designpayoff").val("0");
$("input#designtotal").val("0");
} else if ($('#choosedesign').is(':checked')) {
showDesigncontent();
designSelectValues();
}
});
// Convert String to US Currency ///////////////////////////////////////////////////////////
var formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
// Constanly check for new numbers /////////////////////////////////////////////////////////////
function constantChecker() {
// Show or Hide Custom Disclaimer ///
// if ($(seoSelect).val() == "4" || $(designSelect).val() == "3") {
// $(".disclaimer.custom").show();
// } else if ($(seoSelect).val() != "4" || $(designSelect).val() != "3") {
// $(".disclaimer.custom").hide();
// }
if (($("select#design")[0].selectedIndex === 0) && ($("select#seo")[0].selectedIndex === 0)) {
hidePriceTable();
}
else {
showPriceTable();
}
// Get Current Select Values /////
var currentSeoSetup = $("input#seosetup").val();
var currentSeoValue = $("input#seovalue").val();
var currentDesignDeposit = $("input#designdeposit").val();
var currentDesignPayoff = $("input#designpayoff").val();
var currentDueToday = formatter.format(+currentDesignDeposit + +currentSeoSetup + +currentSeoValue);
var currentDueLater = formatter.format(+currentDesignPayoff);
var currentMonthly = formatter.format(+currentSeoValue);
// Format individual Items ///
var seoSetupVal = formatter.format(+currentSeoSetup);
var seoMonthlyVal = formatter.format(+currentSeoValue);
var DesignDepositVal = formatter.format(+currentDesignDeposit);
var DesignPayoffVal = formatter.format(+currentDesignPayoff);
// Apply Current Values /////
$(dueToday).text(currentDueToday);
$(dueLater).text(currentDueLater);
$(dueMonthly).text(currentMonthly);
$(".setupfee span#val").text(seoSetupVal);
$(".seofirstmonth span#val").text(seoMonthlyVal);
$(".seomonthly span#val").text(seoMonthlyVal);
$(".designdeposit span#val").text(DesignDepositVal);
$(".designpayoff span#val").text(DesignPayoffVal);
}
/// Submit Button
$('.packagebuilder').on('submit', function (e) {
e.preventDefault();
var formData = $(this).serialize();
var fullUrl = window.location.href;
var finalUrl = fullUrl + "?&" + formData;
//window.location.href = finalUrl;
alert(finalUrl);
});
.hidden {
opacity: 0;
max-height: 0px;
transition: max-height 0s cubic-bezier(0, 1, 0, 1) 0s;
position:absolute;
top:-100000px;
}
.shown {
opacity: 1;
max-height: 1500px;
transition: max-height 1s ease-in-out 0s;
position:relative;
}
.packagebuilder {
max-width: 700px;
margin: auto;
box-sizing: border-box;
}
form .services {
display:
flex;
/* grid-gap: 30px; */
box-sizing: border-box;
/* padding-bottom: 20px; */
flex-direction: column;
width: auto;
}
form .option {display: flex;grid-gap: 10px;border-radius: 20px;padding-top: 30px;flex-direction: column;}
.services label {
font-size: 22px;
position: relative;
color: black;
font-weight:600!important;
}
.services select {
padding: 15px!important;
height: auto;
font-size: 20px!important;
padding-right: 45px!important;
font-weight: 300;
border-radius: 5px;
appearance: none;
-webkit-appearance:none;
overflow-wrap: break-word;
background: #ffffff;
border: solid 2px #e0e0e0!important;
}
.services select {
background-image: url("https://static1.squarespace.com/static/5ee80dfeb418dc785b48ee76/t/62ec6656067dab5da9df2fa0/1659659862901/angle-down-solid.svg");
background-size: 20px;
background-position: right 15px center;
background-repeat: no-repeat;
}
.services option {}
.services select:focus {
outline:none!important;
}
.estimate {
display: flex;
flex-direction: column;
/* background: linear-gradient(180deg, #eeeeee, transparent); */
margin: 30px 0px 20px;
overflow: hidden;
border-top: solid 1px #000000;
}
.figure {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0px;
border-bottom: solid 1px #dedede;
}
.figure span:first-child {
font-weight:600
}
.figure span:last-child {
font-size: 20px;
}
.figure:last-child {
border:none;
}
#val {
font-weight:600!important;
padding: 0;
border-radius: 5px;
}
.today #val {font-size: 30px;}
.figure.today {
color: black;
}
.figure {
}
.packagebuilder .disclaimer {
background: #f9f6e6;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
text-align: left;
font-size: 14px;
grid-gap: 10px;
}
.disclaimer i {
color: #ff9d00;
font-size: 20px;
}
.packagebuilder input.package {
background: #000000!important;
border: none!important;
color: white;
margin-top: 20px!important;
}
.packagebuilder input.package:hover {
background: var(--mainbrand)!important;
}
label.choose {
display:
block;
line-height:40px;
height:40px;
width: fit-content;
cursor: pointer;
min-width: 150px;
font-weight: 300!important;
pointer-events: all;
border-radius: 10px;
-webkit-font-smoothing: antialiased;
margin-top: 10px;
font-family:
Arial,Helvetica,sans-serif;
color: gray!important;
text-align:
center;
background: #e4e4e4;
padding: 1px 15px;
/* box-shadow: 11px 14px 20px #0000001a; */
}
label.add-label {
font-weight:600;
}
input.choose[type=checkbox] {
display: none;
}
input.choose:checked + label {
color: #ffffff!important;
background:
var(--mainbrand);
box-shadow: none;
}
.figure.item {
padding: 0px 20pxpx;
}
.figure.item span, .item span#val {
font-size: 13px;
font-weight: 300!important;
}
.today.item span#val, .today.item span {
color: #656565;
}
.other.item span#val, .other.item span {
color:#6c7674;
}
.today.item {
/* background: #f4f4f4!important; */
}
.other.item {
/* background: #f4f4f4!important; */
}
/* new stuff */
.packcheck {
visibility: hidden;
}
input.choose:checked + label .check {
visibility: visible;
}
input.choose.checkbox:checked + label:before {
content: "";
}
.addservices {
padding-bottom: 20px;
border-bottom: solid 1px #c0c0c0;
}
.flex-options {
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
grid-gap: 10px;
}
:root {
--mainbrand: #006eff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="packagebuilder">
<div class="services">
<div class="addservices">
<label class="add-label">Add Services</label>
<div class="flex-options" name="addservices">
<div>
<input class="choose" id="chooseseo" type="checkbox" name="chooseseo">
<label for="chooseseo" class="choose">SEO</label>
</div>
<div>
<input class="choose" id="choosedesign" type="checkbox" name="choosedesign">
<label for="choosedesign" class="choose">Web Design</label>
</div></div></div>
<div class="seo option hidden">
<label for="seo">Pick your SEO Package</label>
<select type="text" id="seo" name="seo">
<option value="0" disabled selected value>-- Select an Option --</option>
<option value="1" class="one">Gold – $750 per month, $500 setup fee</option>
<option value="2">Essentials – $1500 per month, $1000 setup fee</option>
<option value="3">Local Authority – $2500 per month, $1500 setup fee</option>
</select>
</div>
<div class="design option hidden">
<label for="design">Pick your Design Package</label>
<select type="text" id="design" name="design">
<option value="0" disabled selected value>-- Select an Option --</option>
<option value="1">Vanity – $3000, $1500 deposit</option>
<option value="2">Lux – $5000, $2500 deposit</option>
</select>
</div>
</div><div class="estimate hidden">
<span class="figure today"><span>Due Today: </span><span id="val"></span>
</span><span class="figure today item setupfee" style="display:none;"><span style="">SEO Setup Fee</span><span id="val" style=""></span></span>
<span class="figure today item seofirstmonth" style="display:none;"><span style="">SEO First Month</span><span id="val" style=""></span></span><span class="figure today item designdeposit" style="display:none;"><span style="">Web Design 50% Deposit</span><span id="val" style=""></span></span><span class="figure later"><span>Due Later: </span><span id="val"></span></span><span class="figure other item designpayoff" style="display:none;"><span style="">Web Design Payoff</span><span id="val" style=""></span></span>
<span class="figure monthly"><span>Recurring Starting Next Month: </span><span id="val"></span></span><span class="figure other item seomonthly" style="display:none;"><span style="">SEO Monthly Fee</span><span id="val" style=""></span></span>
</div>
<div class="disclaimer pricing hidden"><i class="fas fa-exclamation-circle"></i>This is only an estimate before the final proposal. The final pricing will be reflected on an e-signature agreement we will send you.</div>
<div class="disclaimer custom" style="
display: none;
"><i class="fas fa-exclamation-circle"></i>Since you chose "Custom" on one of the options, the numbers may not reflect what you have discussed with us. Only choose this option if you spoke with us about a custom package prior.</div><input type="hidden" id="seovalue" name="seovalue" value="">
<input type="hidden" id="seosetup" name="seosetup" value=""><input type="hidden" id="designdeposit" name="designdeposit" value=""><input type="hidden" id="designpayoff" name="designpayoff" value="">
<input type="hidden" id="designtotal" name="designtotal" value=""><input type="submit" value="Continue" class="button package hidden">
</form>
I am dynamically adding new div's to a div container, the problem i'm facing is that the div is probably just a few pixels too big and therefore spawns a scrollbar that is pretty much useless, but with overflow: hidden; a little bit of the div gets cut off. I'm looking to make the div little bit larger in height, applying height: 100%; didn't work. This is how I'm creating the divs
function layerCreatorX(submission) { // creator for normal layers
let unique_id = uuidv4() // created unique IDs
let wrapDiv = document.createElement("div")
wrapDiv.id = "wrapDiv" + unique_id
let activeLayerIcon = document.createElement("IMG")
activeLayerIcon.setAttribute("class", "activeLayerOff")
activeLayerIcon.setAttribute("name", "activeLayerIcon")
let invisibilityIcon = document.createElement("IMG")
invisibilityIcon.setAttribute("class", "visibilityButtonPos invisibilityButton") // filter for grey
invisibilityIcon.setAttribute("name", "invisibilityIcon")
let visibilityIcon = document.createElement("IMG")
visibilityIcon.setAttribute("class", "visibilityButtonPos visibilityButtonOff")
visibilityIcon.setAttribute("name", "visibilityIcon")
let line = document.createElement("hr")
line.setAttribute("style", "margin-top: 0px;")
line.className = "greyLine" //grey line will go underneath the div
let x = document.createElement("span")
let t = document.createTextNode(submission)
layerArray.push(unique_id)
layerNamesForComparison.push(submission) //new name comparator
x.className = "item item-layer"
x.id = unique_id
t.className = "noselect"
x.appendChild(activeLayerIcon)
x.appendChild(t)
x.appendChild(invisibilityIcon)
x.appendChild(visibilityIcon)
wrapDiv.appendChild(x)
wrapDiv.className = "LayerListDiv"
document.querySelector('.LayerList').appendChild(wrapDiv)
document.querySelector('.LayerList').appendChild(line)
}
and this is how they look when I create them:
I want to get rid of the vertical scrollbar on the right but still be able to view the whole div, if I use overflow hidden, the <hr> line from the bottom gets cut off and I can't see it anymore.
.LayerList CSS:
.LayerList {
user-select: none;
overflow: auto;
right: -15px;
width: 100%;
max-height: calc(93% - 60px); /*This height has to stay*/
}
Edit: added snippet
//modals
let modal = document.getElementById("myModal")
let btn = document.getElementById("btnCreate")
let span = document.getElementsByClassName("close")[0]
const div = document.getElementById('layerList')
//layer variables
let layerName
let layerId
let layerVisible
let layerLock
let layerNote
let layerActive
let layerJSObject = []
//other vars
let files //stores json file
let data //stores json file data
let layerArray = [] //stores all layer id's in array for comparison purposes
let layerNamesForComparison = [] //stores names of layers, so that duplicates are not created
//miro vars
let widgetName
let selectedWidgets = []// listener var to store all widget info in
let selectedWidgetIDs = []
// will store id's of widgets currently selected until they are saved into a layer
let superObjectID
//DB vras
let globalToken
let responseToken
let boardId
let availableBoards
let recordId
//timestamp
let timeStamp
let account
let availableResults
let onlineMode
let activeLayer = 0
let activeLayerState
//widgetDisplayer()
//CSS vars
let xDiv
let DeleteLayerButton = document.getElementById("btnDelete").disabled = true
let AddObjectsButton = document.getElementById("btnMove").disabled = true
let RemoveObjectsButton = document.getElementById("btnRemove").disabled = true
//------------------------------------------------------ Modal handling ---------------------------------------------------------
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block"
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none"
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none"
}
}
function success() {
if(document.getElementById("newLayerName").value === "") {
document.getElementById('submitNewLayer').disabled = true;
}
else {
document.getElementById('submitNewLayer').disabled = false;
}
}
//--------------------------------------------------Layer naming/validating/creating/deleting/etc... functions--------------------
function validateNewLayerName() { // validates for empty input from input field
let input = document.forms["newLayerForm"]["newLayerName"].value
let lengthLayers = layerArray.length
for(i = 0; i < lengthLayers; i++){ //checks if input is already used as layer name
if(input == layerNamesForComparison[i]){ //fixed?
alert("This layer name is already used, please either delete it or use a different name")
return false
}
else{
continue
}
}
if (input == "" || input == null || input == 0 || input == "0") { // check if submitted input is empty or 0
alert("Cannot submit empty field, please try again!")
return false
}
else {
//if everything adds up appends layer list with new layer
layerCreatorX(input)
modal.style.display = "none"
}
return false
}
function uuidv4() { //random uuidv4 generator for layer id
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
)
}
function layerCreatorX(submission) { // creator for normal layers
let unique_id = uuidv4() // created unique IDs
let wrapDiv = document.createElement("div")
wrapDiv.id = "wrapDiv" + unique_id
let activeLayerIcon = document.createElement("IMG")
activeLayerIcon.setAttribute("class", "activeLayerOff")
activeLayerIcon.setAttribute("name", "activeLayerIcon")
let invisibilityIcon = document.createElement("IMG")
invisibilityIcon.setAttribute("class", "visibilityButtonPos invisibilityButton") // filter for grey
invisibilityIcon.setAttribute("name", "invisibilityIcon")
let visibilityIcon = document.createElement("IMG")
visibilityIcon.setAttribute("class", "visibilityButtonPos visibilityButtonOff")
visibilityIcon.setAttribute("name", "visibilityIcon")
let line = document.createElement("hr")
line.setAttribute("style", "margin-top: 0px;")
line.className = "greyLine" //grey line will go underneath the div
let x = document.createElement("span")
let t = document.createTextNode(submission)
layerArray.push(unique_id)
layerNamesForComparison.push(submission) //new name comparator
x.className = "item item-layer"
x.id = unique_id
t.className = "noselect"
x.appendChild(activeLayerIcon)
x.appendChild(t)
x.appendChild(invisibilityIcon)
x.appendChild(visibilityIcon)
wrapDiv.appendChild(x)
wrapDiv.className = "LayerListDiv"
document.querySelector('.LayerList').appendChild(wrapDiv)
document.querySelector('.LayerList').appendChild(line)
}
html, body {
height: 91.5%;
margin: 0;
padding: 0;
overflow: hidden;
}
.scrollable-container {
height: 100%;
overflow-y: auto;
}
.scrollable-content {
height: 100%;
overflow-y: auto;
background-color: #2a79ff;
}
.rtb-sidebar-caption {
font-size: 14px;
font-weight: bold;
color: rgba(0, 0, 0, 0.8);
padding: 24px 0 0 24px;
margin-bottom: 20px;
}
.miro-btn, button {
width: 120px;
margin: 3px 0 0 14px;
padding: 5px;
}
.delete-btn {
width: 120px;
margin: 3px 0 0 14px;
padding: 5px;
background-color: rgb(216, 24, 24);
}
.item {
align-items: center;
height: 48px;
line-height: 48px;
cursor: pointer;
padding-left: 24px;
padding-top: 1px;
padding-bottom: 1px;
font-size: 20px;
}
/* css for modal popup */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
text-align: center;
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 15px;
border: 1px solid #888;
width: auto;
display: inline-block;
border-radius: 8px;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: rgb(23, 9, 75);
text-decoration: none;
cursor: pointer;
}
input[type=text] {
width: 230px;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
border-radius: 4px;
}
.LayerList {
user-select: none;
overflow: auto;
right: -15px;
width: 100%;
max-height: calc(93% - 60px); /*Has to be 95 so that the last element of span is visible unlike at 100%*/
}
.LayerListDiv {
height: 100%;
}
.LayerList > .items-container {
border-top: 1px solid #e7e7e7;
}
span:last-child {
height: 100%;
}
.LayerList span {
user-select: inherit;
}
.labelWrap {
margin: 0px;
display: flex;
padding: 0;
}
.btn {
background-color: white;
border: none; /* Remove borders */
padding: 12px 16px;
cursor: pointer;
}
.btn:hover {
background-color: grey;
}
.wrapLabel {
padding: 0;
}
hr.greyLine {
border-top: 1px solid #C3C2CF;
opacity: 1;
margin: 20px;
padding: 0;
margin-bottom: -3px;
}
.activeLayerOn {
float: left;
margin-left: 20px;
margin-top: 12px;
position: relative;
margin-right: 15px;
background: url(icons/edit-2-on-2.svg);
height: 0;
width: 0;
padding: 12px 12px 12px 12px;
border-style: 0;
}
.activeLayerOff {
float: left;
margin-left: 20px;
margin-top: 12px;
position: relative;
margin-right: 15px;
background: url(icons/edit-2.svg);
height: 0;
width: 0;
padding: 12px 12px 12px 12px;
}
.visibilityButtonPos {
float: right;
margin-left: 15px;
margin-top: 12px;
position: relative;
margin-right: 15px;
height: 0;
width: 0;
padding: 12px 12px 12px 12px;
}
.visibilityButton {
background: url(icons/eye-off.svg);
}
.invisibilityButton {
background: url(icons/eye.svg);
}
.visibilityButtonOff {
display: none;
}
.activeDiv {
background: #EBEAEF;
color: #4568FB;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Old versions of Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently
supported by Chrome, Edge, Opera and Firefox */
}
.whiteIcon {
filter: invert(98%) sepia(5%) saturate(8%) hue-rotate(101deg) brightness(102%) contrast(101%);
}
.lefticon {
user-select: none;
width: 150px;
height: 75px;
position: absolute;
position: absolute;
bottom: 20px;
left: 0;
}
.rightIcon {
user-select: none;
width: 150px;
height: 75px;
position: absolute;
position: absolute;
bottom: 20px;
left: 160px;
}
.topIcons {
display: inline-block;
vertical-align: middle;
height: 24px;
width: 24px;
}
.addButton {
user-select: none;
width: 150px;
vertical-align: middle;
padding: 0;
}
.deleteButton {
user-select: none;
width: 150px;
padding: 0;
}
<link rel="stylesheet" href="https://miro.com/app/static/styles.1.0.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://miro.com/app/static/sdk.1.1.js"></script>
<div class="miro-h1" style= "padding-left: 20px; padding-top: 15px; user-select: none;">Layers</div>
<form>
<button id="btnCreate" type="button" title="Create Layer" class="miro-btn miro-btn--secondary miro-btn--medium addButton">
<img src="icons/plus.svg" class="topIcons">
Add new Layer
</button>
<button onclick="deleteLayerById(activeLayer)" id="btnDelete" type="button" title="delete a layer" class="miro-btn miro-btn--secondary miro-btn--medium deleteButton">
<img src="icons/trash-2.svg" class="topIcons">
Delete Layer</button>
<hr class="greyLine">
</form>
<div class="container"></div>
<!------------------------------------------------------------- Modal Create------------------------------------------------------------------->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<form name="newLayerForm" onsubmit="return validateNewLayerName()" method="post" required>
<span class="close">×</span>
<p class="miro-h3" style="text-align: left;">Create Layer </p>
<input placeholder="Layer Name" type="text" name="newLayerName" id="newLayerName" onkeyup="success()" class="miro-input" style="width: 300px;">
<br>
<button type="submit" value="submit" id="submitNewLayer" class="miro-btn miro-btn--primary miro-btn--medium" style="float: right;" disabled>Create Layer</button>
</form>
</div>
</div>
<!----------------------------------------------------------------End of modal ------------------------------------------------------------------>
<div id="layerList" class="LayerList" style="font-size: 0px;">
</div>
<form>
<button onclick="getSelectedWidgets()" id="btnMove" type="button" class="miro-btn miro-btn--primary miro-btn--medium lefticon" >
<img src="icons/arrow-left.svg" class="whiteIcon" alt="arrow-left"> <br> Add selected <br>objects to layer</button>
<button onclick="removeSelectedWidgetsFromLayer()" id="btnRemove" type="button" class="miro-btn miro-btn--secondary miro-btn--medium rightIcon" >
<img src="icons/arrow-right.svg" alt="arrow-right"> <br> Remove selected <br>objects from layer</button>
</form>
From W3Schools (https://www.w3schools.com/howto/howto_css_hide_scrollbars.asp):
/* Hide scrollbar for Chrome, Safari and Opera */
.example::-webkit-scrollbar {
display: none;
}
/* Hide scrollbar for IE, Edge and Firefox */
.example {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
Where .example is the class of the div's with no scrollbar.
I have several inputs, which I am copying n times and I am trying to add numeric values from inputs in the array. I marked word "add" because an array may be already filled by other numbers.
I'm trying to apply method from UncleDave's answer here:
JavaScript - Add Value from input box to array
Example:
I have an array:
var exampleArray = [[1, 1.5], [1, 1], [0, 25.5]];
What I have done:
Wrote value 25 in first input. Wrote value 1.5 in the second input.
Create two new inputs.
Wrote value 25.4 in first input. Wrote value 1 in the second input.
Pressed button for adding into an array.
What I am trying to reach:
var exampleArray = [[1, 1.5], [1, 1], [0, 25.5], [25, 1.5], [25.4, 1]];
What I have reached:
"Udefined" in the console log.
Here Is jsfiddle link with my code: https://jsfiddle.net/aectann/k3qwoz0g/12/
updated with snippet (ok, it was not hard at this time, MTCoster, thank you for advice):
var totalInputs;
var myInputs;
var tmpARR = [];
var count = 0,
types = ['t', 'C' /*, 'Q'*/ ],
button = document.getElementById('button');
button.addEventListener("click", createInputs, false);
function createInputs() {
if (!validInput()) {
return;
}
count += 1;
createInput(count);
}
function createInput(count) {
totalInputs = document.getElementsByClassName('myInput').length;
var existingNode = document.getElementsByClassName('myInput')[totalInputs - 1];
types.forEach(function(type) {
var newNode = existingNode.cloneNode();
newNode.value = null;
newNode.id = type + +count;
newNode.placeholder = 'Placeholder ' + type;
newNode.dataset.id = 'id' + count;
appendNode(newNode);
})
}
function appendNode(node) {
document.querySelector('#div').appendChild(node);
}
function validInput() {
myInputs = document.getElementsByClassName('myInput');
var valid = true;
Array.prototype.slice.call(myInputs).forEach(function(input) {
input.classList.remove('error');
if (!input.value) {
input.classList.add('error');
valid = false;
}
});
return valid;
}
function removeError(event) {
event.classList.remove('error');
}
function guardarNumeros() {
boxvalue = document.getElementsByClassName('myInput').value;
tmpARR.push(boxvalue);
console.log(tmpARR);
return false;
}
#title {
font-family: 'Times New Roman', Times, serif;
font-size: 200%;
}
#step {
font-size: 15pt;
clear: both;
}
#step2 {
font-size: 15pt;
clear: both;
}
#step3 {
font-size: 15pt;
clear: both;
}
summary {
background: #009688;
color: #fff;
padding: 5px;
margin-bottom: 3px;
text-align: left;
cursor: pointer;
padding: 5px;
width: 250px;
/*background-color: #4CAF50;*/
}
summary:hover {
background: #008999;
}
.displayBlockInline-Flex {
display: inline-flex;
}
#margin20 {
margin-left: 20px;
vertical-align: middle;
}
#container {
width: auto;
height: auto;
margin: 0 auto;
display: none;
}
a.myButton {
color: #fff;
/* цвет текста */
text-decoration: none;
/* убирать подчёркивание у ссылок */
user-select: none;
/* убирать выделение текста */
background: rgb(212, 75, 56);
/* фон кнопки */
outline: none;
/* убирать контур в Mozilla */
text-align: center;
cursor: pointer;
width: 150px;
padding-bottom: 11px;
}
a.myButton:hover {
background: rgb(232, 95, 76);
}
/* при наведении курсора мышки */
a.myButton:active {
background: rgb(152, 15, 0);
}
/* при нажатии */
.button1 {
/* background-color: #fc0; /* Цвет фона слоя */
/* padding: 5px; /* Поля вокруг текста */
float: left;
/* Обтекание по правому краю */
width: 450px;
/* Ширина слоя */
}
.button2 {
/* background-color: #c0c0c0; /* Цвет фона слоя */
/* padding: 5px; /* Поля вокруг текста */
width: 650px;
/* Ширина слоя */
float: right;
/* Обтекание по правому краю */
}
.clear {
clear: left;
/* Отмена обтекания */
}
.wrapper {
width: 1100px;
margin-left: 20px;
}
/*inputs*/
#div {
text-align: center;
}
.myInput {
height: 40px;
outline: none;
width: auto;
border: 1px solid #999;
border-radius: 4px;
padding: 5px 10px;
margin: 5px;
display: inline-block;
}
.myInput.error {
border: 1px solid red;
}
#action {
margin: 10px 0;
text-align: center;
}
#button {
width: 190px;
height: 40px;
background: #009688;
color: #fff;
font-weight: 600;
font-size: 13px;
border-radius: 4px;
border: none;
/* text-transform: uppercase;*/
outline: none;
cursor: pointer;
}
#button:hover {
background: #008999;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<center>
<input type="text" class="myInput" name="nameAlloy" placeholder="Name">
</center>
<div id="div">
<!--<form onsubmit="return guardarNumeros()">-->
<div id="action">
<button type="button" id="button">Add more inputs</button>
</div>
<input type="number" onkeypress="removeError(this)" class="myInput" data-id="id0" name="value[]" placeholder="Enter value 1">
<input type="number" onkeypress="removeError(this)" class="myInput" data-id="id0" name="value[]" placeholder="Enter value 2">
<div id="action">
<input type="submit" id="button" value="Add to array">
</div>
<!--</form>-->
</div>
The getElementsByClassName() method returns a collection of all
elements in the document with the specified class name, as a NodeList
object.
You can iterate over the collections for all the numeric inputs and update your result. But I would suggest is to create another class for numeric inputs, so you wouldn't need to check for the type of the input and would keep your code generic.
You can try this code and feel free to clear your doubts in the comments.
function guardarNumeros() {
boxvalue = document.getElementsByClassName('myInput');
i = 0;
while (i < boxvalue.length) {
if (boxvalue[i].type == "number") {
if (boxvalue[i+1] && boxvalue[i+1].type == "number") {
tmp = [boxvalue[i].value, boxvalue[i+1].value]
tmpARR.push(tmp);
i+=2;
}
} else {
i++;
}
}
console.log(tmpARR);
return false;
}
The error is in "guardarNumeros" function because getElementsByClassName returns a collection and collection does not have a "value" property.
try this code
function guardarNumeros() {
const inputs = [...document.getElementsByClassName('myInput')];
const inputNumberArr = inputs.filter(x => x.type === 'number');
// tmpARR = [];
for (let i = 0; i < inputNumberArr.length; i++) {
const element = inputNumberArr[i];
if (i % 2 === 0) {
tmpARR.push([element.value]);
} else if (tmpARR[tmpARR.length -1] instanceof Array) {
tmpARR[tmpARR.length -1].push(element.value);
} else {
tmpARR.push([element.value]);
}
}
return false;
}
I'm trying to reset all the buttons inner.text back to original value (1,2,3) and background.color back to grey with a reset button.
I think something wrong with the for loop because when i place i=0 i < 3, it works. I need it to be btns.length, because i will be adding more buttons later.
What i did wrong with the "YES" button code ?
// Get the Reset that opens the ResetModal
var reset = document.getElementById('ResetModal');
var rst = document.getElementById('reset');
rst.onclick = function() {
reset.style.display = "block";
}
//Hit "NO" to turn off modal window
var rstno = document.getElementById('resetno');
rstno.onclick = function() {
reset.style.display = "none";
}
// Hit "YES" to reset all button to initial value
var rstyes = document.getElementById('resetyes');
var btns = document.querySelectorAll('button:not([id=reset]):not([id=submit])');
for (var i = 0; i < btns.length; i++) {
rstyes.onclick = function() {
var btn = document.getElementById("b"+i);
btn.innerText=i;
btn.style.background="#D3D3D3";
reset.style.display = "none";
}
}
// Get the <span> element that closes the modal
var span1 = document.getElementsByClassName("close1")[0];
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
reset.style.display = "none";
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btns = document.querySelectorAll('button:not([id=reset]):not([id=submit])');
// target value
var TV = document.getElementById('inputtarget');
// Each button click => open modal
for(var i = 0; i < btns.length; i++){
btns[i].onclick = function() {
TV.setAttribute('startbtn', this.id );
modal.style.display = "block";
}
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function() {
if (event.target == modal) {
modal.style.display = "none";
}
}
//Arithematic Operator Control
function checkValue(){
var inputvalue = document.getElementById('modal');
var buttonsubmit = document.getElementById( TV.getAttribute('startbtn') );
var value = parseInt(inputvalue.value);
var targetValue = parseInt(TV.value);
if (value < targetValue){
buttonsubmit.style.background = 'red' ;
buttonsubmit.innerText = value ;
}
else if (value >= targetValue){
buttonsubmit.style.background = 'green';
buttonsubmit.innerText = value ;
}
else{
buttonsubmit.style.background = '';
buttonsubmit.innerText = ''
}
modal.style.display = "none" ;
return false;
}
#b1,
#b2,
#b3 {
background-color: rgb(211, 211, 211);
height: 50px;
width: 50px;
font-family: Arial;
font-weight: bold;
box-shadow: 0 1px #999;
}
#b30,
#b31 {
background-color: rgb(211, 211, 211);
height: 50px;
width: 25px;
font-family: Arial;
font-weight: bold;
font-size: 0.5rem;
box-shadow: 0 1px #999;
}
#inputtarget {
height: 60px;
width: 100px;
font-size: 1.5rem;
text-align: center;
border: 1;
}
#trigger {
height: 0 auto;
width: 100px;
font-size: 0.5rem;
text-align: center;
}
#b1:hover,
#b2:hover,
#b3:hover {
background-color: grey;
}
#b1:active,
#b2:active,
#b3:active {
background-color: silver;
box-shadow: 1px #666;
transform: translateY(2px);
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 240px;
height: 200px;
}
#modal1 {
height: 70px;
width: 100px;
text-align: center;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/* Reset (background) */
.reset {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Reset Content/Box */
.reset-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 240px;
height: 200px;
}
#resetyes,
#resetno {
height: 70px;
width: 100px;
text-align: center;
}
/* The Close Button */
.close1 {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close1:hover,
.close1:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div>
<!-- All Buttons in Matrix Form Production -->
<button id="b1" style="position:absolute; left:30px; top:100px">1</button>
<button id="b2" style="position:absolute; left:80px; top:100px">2</button>
<button id="b3" style="position:absolute; left:130px; top:100px">3</button>
<input id="inputtarget" class=numberonly value=0 type="number" min="0" ondrop="return false;" onpaste="return false;" onkeypress='return event.charCode>=48 && event.charCode<=57' ; style="position:absolute; left:55px; top:160px"><br>
<input id="reset" type=button value=Reset style="position:absolute; left:170px; top: 180px">
<input id="trigger" type=button value="Change Target Value" onclick="return CheckBVWithTV()" style="position:absolute; left:165px; top: 530px">
</div>
<!-- The Modal Box 1-->
<div id="myModal" class="modal" >
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>PLEASE INPUT QUANTITY</p>
<input id="modal" type="number" ondrop="return false;" onpaste="return false;" onkeypress='return event.charCode>=48 && event.charCode<=57' ; style=font-size:20px><br>
<br>
<button id="submit" class=submit_on_enter onclick="return checkValue()">SUBMIT</button>
</div>
</div>
<!-- The Reset Box -->
<div id="ResetModal" class="reset">
<!-- Reset content -->
<div class="reset-content">
<span class="close1">×</span>
<p>Are you sure ? <br> This Action cannot be undone.</p>
<input id=resetyes type="button" value="YES">
<input id=resetno type="button" value="NO">
</div>
</div>
You need to move your for loop inside your rstyes.onclick function. You only have one reset yes button, therefore you would not need 3 click functions for that one button. Then in your for loop start from 1 and set it to end at btns.length + 1 since your btns array index starts at 0 and your buttons ids start at 1.
// Get the Reset that opens the ResetModal
var reset = document.getElementById('ResetModal');
var rst = document.getElementById('reset');
rst.onclick = function() {
reset.style.display = "block";
}
//Hit "NO" to turn off modal window
var rstno = document.getElementById('resetno');
rstno.onclick = function() {
reset.style.display = "none";
}
// Hit "YES" to reset all button to initial value
var rstyes = document.getElementById('resetyes');
var btns = document.querySelectorAll('button:not([id=reset]):not([id=submit])');
rstyes.onclick = function() {
for (var i = 1; i < btns.length + 1; i++) {
var btn = document.getElementById("b" + i);
btn.innerText = i;
btn.style.background = "#D3D3D3";
reset.style.display = "none";
}
};
// Get the <span> element that closes the modal
var span1 = document.getElementsByClassName("close1")[0];
// When the user clicks on <span> (x), close the modal
span1.onclick = function() {
reset.style.display = "none";
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btns = document.querySelectorAll('button:not([id=reset]):not([id=submit])');
// target value
var TV = document.getElementById('inputtarget');
// Each button click => open modal
for (var i = 0; i < btns.length; i++) {
btns[i].onclick = function() {
TV.setAttribute('startbtn', this.id);
modal.style.display = "block";
}
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function() {
if (event.target == modal) {
modal.style.display = "none";
}
}
//Arithematic Operator Control
function checkValue() {
var inputvalue = document.getElementById('modal');
var buttonsubmit = document.getElementById(TV.getAttribute('startbtn'));
var value = parseInt(inputvalue.value);
var targetValue = parseInt(TV.value);
if (value < targetValue) {
buttonsubmit.style.background = 'red';
buttonsubmit.innerText = value;
} else if (value >= targetValue) {
buttonsubmit.style.background = 'green';
buttonsubmit.innerText = value;
} else {
buttonsubmit.style.background = '';
buttonsubmit.innerText = ''
}
modal.style.display = "none";
return false;
}
#b1,
#b2,
#b3 {
background-color: rgb(211, 211, 211);
height: 50px;
width: 50px;
font-family: Arial;
font-weight: bold;
box-shadow: 0 1px #999;
}
#b30,
#b31 {
background-color: rgb(211, 211, 211);
height: 50px;
width: 25px;
font-family: Arial;
font-weight: bold;
font-size: 0.5rem;
box-shadow: 0 1px #999;
}
#inputtarget {
height: 60px;
width: 100px;
font-size: 1.5rem;
text-align: center;
border: 1;
}
#trigger {
height: 0 auto;
width: 100px;
font-size: 0.5rem;
text-align: center;
}
#b1:hover,
#b2:hover,
#b3:hover {
background-color: grey;
}
#b1:active,
#b2:active,
#b3:active {
background-color: silver;
box-shadow: 1px #666;
transform: translateY(2px);
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 240px;
height: 200px;
}
#modal1 {
height: 70px;
width: 100px;
text-align: center;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/* Reset (background) */
.reset {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Reset Content/Box */
.reset-content {
background-color: #fefefe;
margin: 15% auto;
/* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 240px;
height: 200px;
}
#resetyes,
#resetno {
height: 70px;
width: 100px;
text-align: center;
}
/* The Close Button */
.close1 {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close1:hover,
.close1:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div>
<!-- All Buttons in Matrix Form Production -->
<button id="b1" style="position:absolute; left:30px; top:100px">1</button>
<button id="b2" style="position:absolute; left:80px; top:100px">2</button>
<button id="b3" style="position:absolute; left:130px; top:100px">3</button>
<input id="inputtarget" class=numberonly value=0 type="number" min="0" ondrop="return false;" onpaste="return false;" onkeypress='return event.charCode>=48 && event.charCode<=57' ; style="position:absolute; left:55px; top:160px">
<br>
<input id="reset" type=button value=Reset style="position:absolute; left:170px; top: 180px">
<input id="trigger" type=button value="Change Target Value" onclick="return CheckBVWithTV()" style="position:absolute; left:165px; top: 530px">
</div>
<!-- The Modal Box 1-->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>PLEASE INPUT QUANTITY</p>
<input id="modal" type="number" ondrop="return false;" onpaste="return false;" onkeypress='return event.charCode>=48 && event.charCode<=57' ; style=font-size:20px>
<br>
<br>
<button id="submit" class=submit_on_enter onclick="return checkValue()">SUBMIT</button>
</div>
</div>
<!-- The Reset Box -->
<div id="ResetModal" class="reset">
<!-- Reset content -->
<div class="reset-content">
<span class="close1">×</span>
<p>Are you sure ?
<br> This Action cannot be undone.</p>
<input id=resetyes type="button" value="YES">
<input id=resetno type="button" value="NO">
</div>
</div>
Mark,
Length begins at 1, and the loop you are using begins at zero. you either need to modify the use of i in your loop or begin the button IDs at b0. The way your html and js is currently written, the loop does nothing during the first iteration. I would recommend changing the ids to begin at b0 and use the updated for loop above.
If you change the button IDs to begin at zero, you should be able to keep using the condition i < btns.length in the loop.
Happy programming!
I want to add <div> tags inside input type="input" for a number-only input field. I know it can't be done, but I was wondering if there was some way to add the + and - buttons inside an input field that isn't input type="number". For reasons that I will not get into (it took me a good two days to solve an issue), I am unable to use input type="number".
How can I make custom spin buttons for an input that doesn't come with spin buttons? Most of the other questions on SO are asking about styling/hiding the spin buttons in a number input.
I suggest you to make a big div containing on a side the input number and, on the other side, make another div which contains the two buttons one on the top of the other.
Since you can't use the type="number" for some reason, here's a small custom stepper.
var numberSteppers = document.querySelectorAll('.numberStepper input');
for(var i = 0; i < numberSteppers.length; i++){
numberSteppers[i].oninput = function(){
this.value = !isNaN(this.value) ? parseInt(this.value) : 0;
}
}
var stepperButtons = document.querySelectorAll('.numberStepper button');
for(var j = 0; j < stepperButtons.length; j++){
stepperButtons[j].onclick = function(e){
e.preventDefault();
var input = this.parentNode.previousElementSibling;
input.value = input.value !== '' ? parseInt(input.value) + parseInt(this.value) : parseInt(this.value);
}
}
.numberStepper, .numberStepper *{
box-sizing:border-box;
}
.numberStepper{
max-width:200px;
position:relative;
}
.numberStepper input{
display:block;
width:80%;
font-size:2em;
min-height:3ex;
padding:1ch;
text-align:right;
}
.numberStepper .steppers{
position:absolute;
right:0;
top:0;
height:100%;
width:20%;
}
.numberStepper button{
margin:0;
padding:0;
border:1px solid;
width:100%;
cursor:pointer;
height:50%;
}
<div class="numberStepper">
<input type="text"/>
<div class="steppers">
<button value="1">+</button>
<button value="-1">-</button>
</div>
</div>
If for some reason you don't want to add divs or change input type to number, you can use this solution.
jQuery('<div class="quantity-nav"><div class="quantity-button quantity-up">+</div><div class="quantity-button quantity-down">-</div></div>').insertAfter('.quantity input');
jQuery('.quantity').each(function() {
var spinner = jQuery(this),
input = spinner.find('input[type="text"]'),
btnUp = spinner.find('.quantity-up'),
btnDown = spinner.find('.quantity-down'),
min = input.attr('min'),
max = input.attr('max');
btnUp.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue >= max) {
var newVal = oldValue;
} else {
var newVal = oldValue + 1;
}
spinner.find("input").val(newVal);
spinner.find("input").trigger("change");
});
btnDown.click(function() {
var oldValue = parseFloat(input.val());
if (oldValue <= min) {
var newVal = oldValue;
} else {
var newVal = oldValue - 1;
}
spinner.find("input").val(newVal);
spinner.find("input").trigger("change");
});
});
.quantity {
position: relative;
}
input[type=text]::-webkit-inner-spin-button,
input[type=text]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=text] {
-moz-appearance: textfield;
}
.quantity input {
width: 45px;
height: 42px;
line-height: 1.65;
float: left;
display: block;
padding: 0;
margin: 0;
padding-left: 20px;
border: 1px solid #eee;
}
.quantity input:focus {
outline: 0;
}
.quantity-nav {
float: left;
position: relative;
height: 42px;
}
.quantity-button {
position: relative;
cursor: pointer;
border-left: 1px solid #eee;
width: 20px;
text-align: center;
color: #333;
font-size: 13px;
font-family: "Trebuchet MS", Helvetica, sans-serif !important;
line-height: 1.7;
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;
}
.quantity-button.quantity-up {
position: absolute;
height: 50%;
top: 0;
border-bottom: 1px solid #eee;
}
.quantity-button.quantity-down {
position: absolute;
bottom: -1px;
height: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quantity">
<input type="text" value="1">
</div>
This solution seems to work on Chrome and Edge. (Not tested on other browsers).
Credits to this.