Password box - get value from input field with javascript - javascript

Does anybody know how to make a password box like this image?
This password box will be the first page of the site/mobile. The user have to insert 4 numbers (1 - 2 - 3 - 4). If they dont type 1 -2 - 3 - 4 as their password, they will get a message box saying "wrong password". If they type correct they will be sent to the next page.
Appreciate help!

Here a working sample
var password = [1,2,3,4];
var pwdInputs = $("#pwdContainer input");
var inputs = pwdInputs.toArray();
pwdInputs.keyup(function(){
if (this.value.length == this.maxLength) {
if(inputs.indexOf(this) == inputs.length-1){
testPassword();
} else {
$(this).next('input').focus();
}
}
});
function testPassword(){
var valid = true;
for(var i=0; i<inputs.length; i++){
if(password[i] != inputs[i].value){
valid = false;
break;
}
}
if(valid){
console.log("Correct Password!");
window.location.href = 'http://www.google.com';
}else{
console.log("Wrong Password!");
}
}
div.box-big {
background-color: grey;
margin: auto;
display:inline-block;
padding: 10px;
padding-top: 20px;
}
input.box-text {
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pwdContainer" class="box-big" >
<input type="text" maxlength="1" class="box-text" >
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
</div>

As per your comment, in the picture provided you seem to want to provide the user with 4 boxes, and in it, they would then type their password.
In this case, I do not think that you need regular expressions at all. What you need to do, in my opinion, is the following:
Create the 4 password field text boxes.
In the section where you check the password, simply check that the first box has a value of 1 stored in it, the second box has 2, the third has 3 and the fourth has 4.
Since you are looking for specific, entire string values, as opposed to patterns, regular expressions are not needed.

You probably want a regular expression (regex), which can be used to validate your input.
The regex string would look something like this: \d{4} or [0-9]{4}, which is basically saying match all digits (`\d' or numbers from 0-9) four times strictly, so only four digits exactly would be valid
<input type="password" pattern="[0-9]{4}" id="passcode" required onkeyup="checkIfValid()">
<p id="isValid"></p>

Related

Comma separated step for float number input

I want to comma seperated value for my input box. For Example 2100000.90 will be 2,100,000.90. What I achieved is 2100000.90 to 2,100,000 from some Solution in Stack overflow
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
And My Javascript is
document.getElementById('salary').addEventListener('input', event =>
event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
I want both comma separated and value after point.
Thanks in advance
Your logic is defeated by its own.
Here is what you are currently doing:
ask the user to input a series of digits and only digits
parse the input into an integer
format the integer in the en-US locale
what will happen when the user tries to input a decimal point?
It will automatically be removed by the regex replace.
What you need to do is the following:
Allow the user to input digits and decimal points
That will mess up if the user types more than one decimal point, but that can be detected and dealt with later
Try to detect if the input is a valid number or not
if not, then provide a negative feedback to the user
if yes, then provide a positive feedback
most important: the process of converting text to number will get rid of the decimal point if it is the last character in the input box. The user will not see the dot since the conversion from text to number will see that it is the last thing and it's not affecting the number, so it is removed, and the user doesn't know why.
Therefor, it is essential to add the "dot" back if it is the last thing typed by the user.
document.getElementById('salary').addEventListener('input', event => {
event.preventDefault();
// allow only digits and dots
let text = event.target.value.replace(/[^\d\.]/gi, '');
// check if last character is a dot
let lastCharIsAdot = text.substr(text.length - 1, 1) === ".";
// try to check if input text is a valid number
if (isNaN(text)) {
// if not, then give feedback to the user
event.target.classList.remove('valid');
event.target.classList.add('invalid');
} else {
// if yes, then give positive feedback
event.target.classList.remove('invalid');
event.target.classList.add('valid');
// format number
event.target.value = Number(text).toLocaleString("en-US");
// this will remove the dot if it is the last thing input
// therefor, we need to put it back
if (lastCharIsAdot) event.target.value += ".";
}
});
.valid {
background-color: lightgreen;
color: darkgreen;
}
.invalid {
background-color: pink;
color: maroon;
}
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
You can try this
parseInt(number, 10).toLocaleString()
here is also the link from mozilla docs about Number.prototype.toLocaleString() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
This function help you :
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Output :
numberWithCommas(88888888.88)); // 88,888,888.88

Client side input validation via Bootstrap and jQuery

I am kind of stuck, with this I don't even know where to start but
I need to mark the first input as green on the correct password, red if the password does not meet the requirements
Requirements:
Passwords must be at least 10 characters long and have lowercase and uppercase letters
Passwords less than 15 characters must have a number and a special character
Marking the second input outline as green if it matches the first input and the password is correct, red otherwise.
Any help would be very appriciated
<div class="form-group">
<label for="newPasswordTextBox">Password</label>
<input type="password" id="newPasswordTextBox" class="form-control" name="newPassword"
placeholder="New Password" autocomplete="off">
</div>
<div class="form-group">
<label for="confirmNewPasswordTextBox">Confirm Password</label>
<input type="password" id="confirmNewPasswordTextBox" class="form-control"
name="confirmNewPassword" placeholder="Confirm New Password" autocomplete="off">
</div>
<div class="small">
<ul>
<li>Passwords must be at least 10 characters long and have a lowercase and
uppercase letters</li>
<li>Passwords less than 15 characters must have a number and a special
character</li>
</ul>
</div>
You could try using javascript to collect both inputs document.getElementById("newPasswordTextBox") and document.getElementById("confirmNewPasswordTextBox") and then you can take the .value attributes from the input boxes to check the input against if conditionals with your specified requirements. eg.
let newPass=document.getElementById("newPasswordTextBox");
newPass.addEventListener("keyup",function(evt){
let val=newPass.value;
//check requirements here
});
or in jquery
$("#newPasswordTextBox").on("keyup", function(evt){
let val=$("#newPasswordTextBox").val(); //get the value using jquery
//check requirements here
});
Next, use if conditionals by //check requirements here to get your functionality. You can use val.length to get the length of the string obtained from the textbox, then just compare this to the size you want(10). Repeat the aforementioned for 15 but just add the extra requirements of checking for numbers and special characters(see regular expressions in javascript). For validating that passwords match just grab both values and use "===" to determine if they are equal. You can also change the input boxes' outline colours using the border property as follows:
$("#newPasswordTextBox").css({"border-color":"green"});//Use the appropriate id and colour for the box you wish to change
Addition(correcting the authors code post):
I've managed to capture most of what I believe you'd want here and corrected some of your code by changing the wrong variables that were called and changed to the proper regex code.
$("#newPasswordTextBox").on("keyup", function () {
let pass = $("#newPasswordTextBox").val();
if ((pass.length >=10) && (pass.length < 15)) {
var regex = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~])/;
if(!pass.match(regex)){
$("#newPasswordTextBox").css({ "border-color": "red"});
}
else{
$("#newPasswordTextBox").css({ "border-color": "green" });
}
} else if (pass.length>=15){
$("#newPasswordTextBox").css({ "border-color": "green","outline":"none" });
}else {
$("#newPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
}
);
$("#confirmNewPasswordTextBox").on("keyup", function () {
let pass = $("#confirmNewPasswordTextBox").val();
let confpass = $("#newPasswordTextBox").val();
if (pass === confpass) {
$("#confirmNewPasswordTextBox").css({ "border-color": "green","outline":"none" })
} else {
$("#confirmNewPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<input type="text" id="newPasswordTextBox" placeholder="new">
<input type="text" id="confirmNewPasswordTextBox" placeholder="re-enter">
</body>

Get value for javascript from input="number"

I have tried everything I can find on here and all over the Internet and this just will not work.
I simply want to check the input type="number" to see if it matches a number already in the database. For now I have kept it simple as I can work out the rest.
Here is my code:
The Input:
<input style="width: 50px; font-size: 17px;" type="number" min="1" autocomplete="off" id="days" name="days" value="1" onchange="daysChange(this.days)" required />
Here is the Javascript:
function daysChange(days) {
var day = document.getElementById("days");
if (day == "3"){
alert("You Already Have An Email Going Out That Day. Please Select Another Day.");
}
}
It's not picking up the value of days. Instead if I do an alert and have it output the value this is what it says... [object HTMLInputElement]
You need to get value:
function daysChange(days) {
var day = document.getElementById("days");
if (day.value == "3"){
alert("You Already Have An Email Going Out That Day. Please Select Another Day.");
}
}
As mentioned guys above, document.getElementById("days") returns the whole object of matched input. You need to get value attribute to get the current input value. Working example:
function daysChange(days) {
var day = document.getElementById("days");
if (day.value == "3"){
alert("You Already Have An Email Going Out That Day. Please Select Another Day.");
}
}
<input style="width: 50px; font-size: 17px;" type="number" min="1" autocomplete="off" id="days" name="days" value="1" onchange="daysChange(this.days)" required />
As mentioned before, you have to get value out of the HTMLInput:
if (day.value === "3")
Also good point, is that the value of the input is type string, I believe, you need type integer, so using a shorthand property for parseInt:
if (day.value|0 === 3)
Is much more pretty.

jQuery Click Function, input value length and pattern

I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

If condition is true print text in input field with specific ID

Noob in need of some input here. I've spent some hours now trying to get this to work, with both PHP and javascript and this is where i'm at now.
I want to get an input field to show a specific text based on a condition. If the digit in input field 'ebctotal' is within the range 1-4, then show the text "very pale" in input field 'hue'.
Code:
function getHue() {
var ebc = document.getElementById("ebctotal").value;
if (ebc >= 1 && ebc <= 4) {
// insert text "Very pale" into element with id 'hue'
document.getElementById('hue').value;
}
}
HTML:
// print text in this field
<input class="input" type="text" id="hue" size="7" maxlength="20">
// based on value of this field
<input class="input" type="text" id="ebctotal" size="7" maxlength="20">
Am I on the right track?
Cheers
If you want to check whether length of "ebc" between 1-4 then try like;
function getHue() {
var ebc = document.getElementById("ebctotal").value;
if (ebc.length>=1 && ebc.length<=4) {
document.getElementById('hue').value='Very pale';
}
}
or whether value of "ebc" between 1-4 then try like;
function getHue() {
var ebc = parseInt(document.getElementById("ebctotal").value);
if (ebc>=1 && ebc<=4) {
document.getElementById('hue').value='Very pale';
}
}

Categories