How to make an input field maxlength work from a keypad? - javascript

Got an input field that has a maxlength of 6, when typing normally it works fine, but when I try to use the keypad I made, it doesn't. It just seems to bypass the limit as if it isn't even there.
HTML:
<div class="bank-screen">
<h1>Please enter your pin to continue</h1>
<div class="options">
<input name="pin" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "4"
id="pinfield">
</div>
<div class="keypad">
<div class="keys">
<button value="1" class="key" onclick="GetNum(this)">1</button>
<button value="2" class="key" onclick="GetNum(this)">2</button>
<button value="3" class="key" onclick="GetNum(this)">3</button>
<button value="4" class="key" onclick="GetNum(this)">4</button>
<button value="5" class="key" onclick="GetNum(this)">5</button>
<button value="6" class="key" onclick="GetNum(this)">6</button>
<button value="7" class="key" onclick="GetNum(this)">7</button>
<button value="8" class="key" onclick="GetNum(this)">8</button>
<button value="9" class="key" onclick="GetNum(this)">9</button>
<button class="key"></button>
<button value="0" class="key" onclick="GetNum(this)">0</button>
<button class="key"></button>
<button class="key" id="submit">Submit</button>
<button class="key" id="cancel">Cancel</button>
<button class="key" id="clear" onclick="clearall()">Clear</button>
</div>
</div>
JS:
function GetNum(a){
var pinfield = document.getElementById("pinfield");
pinfield.value = pinfield.value + a.value;
}
function clearall(){
var pinfield = document.getElementById("pinfield");
pinfield.value = null;
}
var result = 103/50;
result = Math.floor(result);
console.log(result);

It seems that setting the input value via JavaScript will ignore the length limit.
In your case, you can add some validation in your GetNum function, only adding to the input field if the current value is shorter than 4 characters.
function GetNum(a){
var pinfield = document.getElementById("pinfield");
if (pinfield.value.length < 6) {
pinfield.value = pinfield.value + a.value;
}
}

Related

Sum the value of all buttons clicked on form and insert text

I've got a form with 6 questions and 4 button answers. Each button has a different numeric value that I'd like to sum up.
<form name="my-form" id="survey">
<div id="formpage_1" class="question" style="visibility: visible; display: block;">
<h3>1. Question 1</h3>
<button class="btn" value="-15" name="price1">Strongly Disagree</button>
<button class="btn" value="-10" name="price1">Disagree</button>
<button class="btn" value="0" name="price1">Agree</button>
<button class="btn" value="0" name="price1">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Next" onclick="pagechange(1,2);">
</div>
</div>
Depending on that sum, I'll insert some different text into a div.
const myForm = document.forms["my-form"],
toleR = document.getElementById("tolerance");
myForm.onsubmit = (e) => {
e.preventDefault(); // disable form submit
//Count the value of each answer
let sum =
Number(myForm.price1.value) +
Number(myForm.price2.value) +
Number(myForm.price3.value) +
Number(myForm.price4.value) +
Number(myForm.price5.value) +
Number(myForm.price6.value);
//insert image and text
if (sum < 0)
txt = '<div><p>Profile A</p></div>';
if (sum < 12)
txt = '<div><p>Profile B</p></div>';
if (sum > 11)
txt = '<div><p>Profile C</p></div>';
if (sum > 17)
txt = '<div><p>Profile D</p></div>';
if (sum > 20)
txt = '<div><p>Profile E</p></div>';
myForm.totalSum.value = sum;
toleR.innerHTML = txt;
};
I had this working when the answers were radio buttons, but I couldn't style the radio input as easily as I wanted so moved to buttons. Now I'm not sure why this has stopped working.
Bonus Points: Each button is meant to stay orange when clicked/"active". Help?
Working example: https://jsfiddle.net/bnedale/jp0k18wd/7/
Thanks
Please check below code. I have mentioned changes with comments. Change 1, Change 2 etc.
Please refer querySelectorAll, getAttribute, closest if you are not familiar with it.
const myForm = document.forms["my-form"],
toleR = document.getElementById("tolerance");
myForm.onsubmit = (e) => {
e.preventDefault(); // disable form submit
// Change 1
// get selected buttons, button with active class inside myForm
let activeBtn = myForm.querySelectorAll('.btn.active');
//Count the value of each answer
let sum = 0;
for (var i = 0; i < activeBtn.length; i++) {
// Change 2
// in case of button you can not have .value to get value.
// instead we can use button.getAttrinute("value") to get its value
sum += Number(activeBtn[i].getAttribute("value"))
}
// Change 3
// use if then else if for next conditions
//insert image and text
if (sum < 0)
txt = '<div><p>Profile A</p></div>';
else if (sum < 12)
txt = '<div><p>Profile B</p></div>';
else if (sum > 11)
txt = '<div><p>Profile C</p></div>';
else if (sum > 17)
txt = '<div><p>Profile D</p></div>';
else if (sum > 20)
txt = '<div><p>Profile E</p></div>';
myForm.totalSum.value = sum;
toleR.innerHTML = txt;
};
//page change function
function pagechange(frompage, topage) {
var page = document.getElementById("formpage_" + frompage);
if (!page) return false;
page.style.visibility = "hidden";
page.style.display = "none";
page = document.getElementById("formpage_" + topage);
if (!page) return false;
page.style.display = "block";
page.style.visibility = "visible";
return true;
}
//reset the form and scroll to top
document.getElementById("secondaryButton").onclick = function() {
pagechange(7, 1);
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
};
//// Get the container element
//var btnContainer = document.getElementById("investments");
// Change 4
// Get all buttons with class="btn" inside the entire form
var btns = document.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
// Change 5
// get active button in current question div.
// this.closest(.question) will find parent with class question for current element
// then find button with active class
var current = this.closest('.question').getElementsByClassName("active");
// If there's no active class
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
// Add the active class to the current/clicked button
this.className += " active";
});
}
.btn {
border: 2px solid #ea730b;
border-radius: 5px;
padding: 10px;
width: 20%;
display: inline;
float: left;
margin: 10px;
background-color: white;
}
.active,
.btn:hover {
color: white;
background-color: #ea730b;
border: 2px solid #ea730b;
}
#myDIV {
width: 80%;
margin: auto !important;
}
#reset {
float: left;
clear: both;
}
.change {
display: block;
clear: left;
padding: 20px 0 0 0;
width: 20%;
height: auto;
margin: auto;
}
<form name="my-form" id="survey">
<div id="formpage_1" class="question" style="visibility: visible; display: block;">
<h3>1. Question 1</h3>
<button class="btn" value="-15" name="price1">Strongly Disagree</button>
<button class="btn" value="-10" name="price1">Disagree</button>
<button class="btn" value="0" name="price1">Agree</button>
<button class="btn" value="0" name="price1">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Next" onclick="pagechange(1,2);">
</div>
</div>
<div id="formpage_2" class="question" style="visibility: hidden; display: none;">
<h3>2. Question 2 </h3>
<button class="btn" value="1" name="price2">Strongly Disagree</button>
<button class="btn" value="2" name="price2">Disagree</button>
<button class="btn" value="3" name="price2">Agree</button>
<button class="btn" value="5" name="price2">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Back" onclick="pagechange(2,1);">
<p style="display: inline;">&nbsp&nbsp&nbsp</p>
<input type="button" value="Next" onclick="pagechange(2,3);">
</div>
</div>
<div id="formpage_3" class="question" style="visibility: hidden; display: none;">
<h3>3. Question 3</h3>
<button class="btn" value="5" name="price3">Strongly Disagree</button>
<button class="btn" value="3" name="price3">Disagree</button>
<button class="btn" value="2" name="price3">Agree</button>
<button class="btn" value="1" name="price3">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Back" onclick="pagechange(3,2);">
<p style="display: inline;">&nbsp&nbsp&nbsp</p>
<input type="button" value="Next" onclick="pagechange(3,4);">
</div>
</div>
<div id="formpage_4" class="question" style="visibility: hidden; display: none;">
<h3>4. Question 4</h3>
<button class="btn" value="5" name="price4">Strongly Disagree</button>
<button class="btn" value="3" name="price4">Disagree</button>
<button class="btn" value="2" name="price4">Agree</button>
<button class="btn" value="1" name="price4">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Back" onclick="pagechange(4,3);">
<p style="display: inline;">&nbsp&nbsp&nbsp</p>
<input type="button" value="Next" onclick="pagechange(4,5);">
</div>
</div>
<div id="formpage_5" class="question" style="visibility: hidden; display: none;">
<h3>5. Question 5</h3>
<button class="btn" value="1" name="price5">Strongly Disagree</button>
<button class="btn" value="2" name="price5">Disagree</button>
<button class="btn" value="3" name="price5">Agree</button>
<button class="btn" value="5" name="price5">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Back" onclick="pagechange(5,4);">
<p style="display: inline;">&nbsp&nbsp&nbsp</p>
<input type="button" value="Next" onclick="pagechange(5,6);">
</div>
</div>
<div id="formpage_6" class="question" style="visibility: hidden; display: none;">
<h3>6. Question 6</h3>
<button class="btn" value="5" name="price6">Strongly Disagree</button>
<button class="btn" value="3" name="price6">Disagree</button>
<button class="btn" value="2" name="price6">Agree</button>
<button class="btn" value="1" name="price6">Strongly Agree</button>
<br>
<div class="change">
<input type="button" value="Back" onclick="pagechange(6,5);">
<p style="display: inline;">&nbsp&nbsp&nbsp</p>
<button type="submit" onclick="pagechange(6,7)">Calculate</button>
</div>
</div>
<div id="formpage_7" style="visibility: hidden; display: none;">
<div id="tolerance"></div>
<br>
<br>
<input id="secondaryButton" type="reset" value="Start again">
<input type="text" name="totalSum" value="" size="2" readonly="readonly">
</div>
</form>
You need to declare the buttons inside a form with type="button", otherwise this buttons will work as 'submit' by default
<button type="button" class="btn" value="-15" name="price1">Strongly Disagree</button>
<button type="button" class="btn" value="-10" name="price1">Disagree</button>
<button type="button" class="btn" value="0" name="price1">Agree</button>
<button type="button" class="btn" value="0" name="price1">Strongly Agree</button>
You've some errors in your code
All your buttons having same name price1 (it should be an array or the name should be different)
Try getting the buttons value by id
Set the type of the buttons as button(type="button")
function pagechange(elem1,elem2){
const myForm = document.forms["my-form"],
toleR = document.getElementById("tolerance");
myForm.onsubmit = (e) => {
e.preventDefault(); // disable form submit
//Count the value of each answer
let sum =
Number(document.getElementById("price1").value) +
Number(document.getElementById("price2").value) +
Number(document.getElementById("price3").value) +
Number(document.getElementById("price4").value);
//insert image and text
if (sum < 0)
txt = '<div><p>Profile A</p></div>';
if (sum < 12)
txt = '<div><p>Profile B</p></div>';
if (sum > 11)
txt = '<div><p>Profile C</p></div>';
if (sum > 17)
txt = '<div><p>Profile D</p></div>';
if (sum > 20)
txt = '<div><p>Profile E</p></div>';
alert(sum);
myForm.totalSum.value = sum;
toleR.innerHTML = txt;
};
}
<form name="my-form" id="survey">
<div id="formpage_1" class="question" style="visibility: visible; display: block;">
<h3>1. Question 1</h3>
<button class="btn" type="button" value="-15" name="price1" id="price1">Strongly Disagree</button>
<button class="btn" type="button" value="-10" name="price1" id="price2">Disagree</button>
<button class="btn" type="button" value="0" name="price1" id="price3">Agree</button>
<button class="btn" type="button" value="0" name="price1" id="price4">Strongly Agree</button>
<br>
<div class="change">
<input type="submit" value="Next" onclick="pagechange(1,2);">
</div>
</div>
</form>

Multiple buttons using same function

I have multiple buttons I would like to increment a value in different corresponding inputs. I am able to get all the buttons working but they only effect the first input. I realize I can write out three different functions for each button but I know there is a way to utilize one function. Thank you for any help in advance!
Here is code for reference:
let submit = document.querySelectorAll(".submit");
let num = document.querySelector(".num");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
let value = 0;
function increment(){
value +=1;
num.value = value;
}
<div class="container">
<div class="main">
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
<button class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"></input> </div>
</div>
</div>
Select the next sibling and select the input.
const submit = document.querySelectorAll(".submit");
submit.forEach((btn) => {
btn.addEventListener("click", increment);
});
function increment() {
const inp = this.nextElementSibling.querySelector("input");
inp.value = Number(inp.value) + 1;
}
<div class="container">
<div class="main">
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
<button type="button" class="submit">Submit</button>
<div class="withinDiv"><input type="number" class="num" value="0"> </div>
</div>
</div>
That's how i would do it - basically in your "submit" buttons you create attribute (in this case "for" (see EDIT)) that will point to id of input to be incremented. This gives you full flexibility, no matter what html you have.
EDIT
Better use custom attribute, for example data-for, button doesn't have for attribute, as pointed in the comments below
let submit = document.querySelectorAll(".submit");
submit.forEach((btn)=>{
btn.addEventListener("click", increment);
});
function increment(ev){
let targetInputId = ev.target.getAttribute("data-for");
let targetInput = document.getElementById(targetInputId);
targetInput.value = parseInt(targetInput.value) + 1;
}
<div class="container">
<div class="main">
<button data-for="num1" class="submit">Submit</button>
<div class="withinDiv"><input id="num1" type="number" class="num" value="0"></input> </div>
<button data-for="num2" class="submit">Submit</button>
<div class="withinDiv"><input id="num2" type="number" class="num" value="0"></input> </div>
<button data-for="num3" class="submit">Submit</button>
<div class="withinDiv"><input id="num3" type="number" class="num" value="0"></input> </div>
</div>
</div>

html value=" " not displaying

<div id="minus_vacancies">
<h4>Mínimo de vagas</h4>
<div>
<input type="button" id="decrease_btn" name="decrease_btn" value="-" onclick="subtractVacancies(this)">
</div>
<div>
<input id="vacancies_qtt" type="text" name="vacancies_qtt" value="0" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
</div>
<div>
<input type="button" id="increase_btn" name="increase_btn" value="+" onclick="addVacancies(this)">
</div>
</div>
Hey! I am making a Decrement/Increment buttons with the value on the middle. The buttons work fine but I can´t see the number. Its not displaying the value="0" of the vacancies_qtt
Why?
Thanks in advance
A possible solution for addVacancies() and subtractVacancies():
function addVacancies(){
let num = document.getElementById("vacancies_qtt");
num.value++;
}
function subtractVacancies(){
let num = document.getElementById("vacancies_qtt");
num.value--;
}
function addVacancies() {
cur = parseInt($("#vacancies_qtt").val())+1;
$("#vacancies_qtt").val(cur);
}
function subtractVacancies() {
cur = parseInt($("#vacancies_qtt").val())-1;
$("#vacancies_qtt").val(cur);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="minus_vacancies">
<h4>Mínimo de vagas</h4>
<div>
<input type="button" id="decrease_btn" name="decrease_btn" value="-" onclick="subtractVacancies(this)">
</div>
<div>
<input id="vacancies_qtt" type="text" name="vacancies_qtt" value="0" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
</div>
<div>
<input type="button" id="increase_btn" name="increase_btn" value="+" onclick="addVacancies(this)">
</div>
</div>
Try this out

How to Distinguish between ID values of html Element using jquery

Actually I have two divs available on my page with buttons and I am passing the hidden field attached with that button to the jquery function But when I click on the second div it pass the value of the first div. Below is the html code
<div id="polls-42-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons" id="vote-btn">
<input type="hidden" value="42" id="poll-id">
</div>
<div id="polls-11-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons" id="vote-btn">
<input type="hidden" value="11" id="poll-id">
</div>
And I am using this jquery :
$(document).on('click','#vote-btn', function() {
console.log( $("#poll-id").val());
});
NOTE: The Div ids are not same all the time
The id attribute should be unique in the same document, it will be better if you're using global classes instead :
<div id="polls-42-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons vote-btn">
<input type="hidden" value="42" class="poll-id">
</div>
<div id="polls-11-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons vote-btn">
<input type="hidden" value="11" class="poll-id">
</div>
Then use siblings to target the related field :
$(this).siblings(".poll-id").val();
Hope this helps.
$(document).on('click','.vote-btn', function() {
console.log( $(this).siblings(".poll-id").val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="polls-42-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons vote-btn">
<input type="hidden" value="42" class="poll-id">
</div>
<div id="polls-11-ans"class="wp-polls-ans">
<input type="button" name="vote" value="Vote" class="Buttons vote-btn">
<input type="hidden" value="11" class="poll-id">
</div>
You can select the DIVs with the class "wp-polls-ans" and then the buttons inside
$(".wp-polls-ans #vote-btn").click(function(){
var val = $(this).parent().find( "#poll-id").val();
alert(val);
})
This is the fiddle
Here is the working javascript code:
$(document).on('click','#vote-btn', function() {
console.log( $(this).siblings("#poll-id").val() );
});

Add character function need to add 0 before decimal point

I'm using the following JavaScript to add a decimal into an input field:
function addChar(input, character) {
if (input.value == null || input.value == "0"){
input.value = character}
else{
input.value += character}
};
$('#button-dot').click(function() {
addChar(this.form.display, '.');
});
with HTML markup:
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>
When the user presses the the #button-dot key prior to any number key, the decimal appears with no zero to the left of it and I would like for that to be the case. So is there a way to alter this code such that when the user inputs the decimal point as the first key, a zero will appear to the left of the decimal?
Try this handler:
$('#button-dot').click(function(){
var txt = disp.val().replace(/\./g, '');
if(!txt)
txt = '0';
txt += '.';
disp.val(txt);
});
$(function() {
var disp = $('#disp');
//all buttons except for last button `dot`
$('[id^=button-]').slice(0, -1).click(function() {
var txt = disp.val();
if('0' === txt) { //modified condition
txt = '';
}
disp.val(txt + this.value);
});
$('#button-dot').click(function() {
var txt = disp.val().replace(/\./g, ''); //replace all previous dots
if (!txt)
txt = '0';
disp.val(txt + '.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25" />
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>
Not entirely sure what you want, but this code will replace a dot or a zero or an empty input with 0.:
function addChar(input, character) {
if (input.value == '' || input.value == '.' || input.value == "0"){
input.value = "0" + character}
else{
input.value += character}
};
$('#button-dot').click(function() {
addChar($('input').get(0), '.');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="i" />
<button id="button-dot">.</button>

Categories