Javascript to validate only Numeric after predefined text in a textbox - javascript

I'm trying to use Javascript to make a textbox that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. I need to allow only 10 digit numeric after the readonly text and need to validate for the numeric digits. The following is the Javascript code for having the readonly in textbox
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
&& ((this.selectionStart < readOnlyLength)
|| ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});

If you looking for solution with script then here is plain js and RegExp:
var fixedText = function(textbox, label) {
var num = textbox.value.replace(/\D/g, ''); //non numeric
num = num.substr(0, 10); //max 10 digits
textbox.value = label + num;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />
With simple label ,input and script:
var numeric = function(textbox) {
var num = textbox.value.replace(/\D/g, '');
num = num.substr(0, 10);
textbox.value = num;
};
label.partial,
input.partial {
border: 1px ridge grey;
margin-bottom: 3px;
}
label.partial {
border-right: none;
cursor: text;
}
input.partial {
border-left: none;
margin-left: -4px;
top: -1px;
position: relative;
}
<label for="PostalCode" class='partial'>Postal Code </label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No </label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />

Related

Validation with html form only gives if statement

No matter how many characters I enter, it only gives the if statement and not the else.
is there a typo I entered somewhere I am not seeing, or does the function not work if there are two inputs?
function valid_Function(){
var x, text;
x = document.getElementById("name").value;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
}
else {
text = "Input OK";
}
document.getElementById("valid").innerHTML = text;
}
form input {
display: block;
margin-top: 10px;
}
form [type="submit"] {
padding: 5px;
border-radius: 5px;
border: none;
background: skyblue;
transition: .5s ease;
}
form [type="submit"]:hover {
box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}
<form action="#">
<input for="fname" id="name" placeholder="First Name" type="text">
<input for="lname" id="name" placeholder="Last Name" type="text">
<input onclick="valid_Function()" type="submit" value="Submit">
</form>
<p id="valid"></p>
The couple issues noted in the comments are causing your code to break.
IDs in HTML need to be unique, so having 2 elements with id="name" will cause problems in JavaScript
Assuming you meant to check the length of first/last names rather than comparing the values to the integers 1 and 10, the code should be checking the .length property in your conditionals.
Assuming you want to run this check separately for each name input, here is the adjusted code to validate first and last name separately. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event for more information about handling form submission events.
document.getElementById('form').addEventListener('submit', function(event) {
event.preventDefault(); // this prevents the form from submitting right away so the rest of the validation can run
var firstName = document.getElementById("first_name").value.trim();
var lastName = document.getElementById("last_name").value.trim();
var text;
if (firstName.length < 1 || firstName.length > 10) {
text = "First name is not valid";
} else if (lastName.length < 1 || lastName.length > 10) {
text = "Last name is not valid";
} else {
text = "Input OK";
}
document.getElementById("valid").innerHTML = text;
return false; // this stops the form from continuing to submit, you may or may not want this line here
});
form input {
display: block;
margin-top: 10px;
}
form [type="submit"] {
padding: 5px;
border-radius: 5px;
border: none;
background: skyblue;
transition: .5s ease;
}
form [type="submit"]:hover {
box-shadow: 0 2px 5px 2px rgba(92, 228, 252, 0.8);
}
<form id="form">
<input for="fname" id="first_name" placeholder="First Name" type="text">
<input for="lname" id="last_name" placeholder="Last Name" type="text">
<input type="submit" value="Submit">
</form>
<p id="valid"></p>
Why not a simple truthy check?
if (!x) {
text = "Input not valid";
}
else {
text = "Input OK";
}
And, if you just want to make sure the length remains less than 10, then
if (!x || x.length> 10) {
text = "Input not valid";
}
else {
text = "Input OK";
}
No matter how many characters I enter, it only gives the if statement and not the else
Yes because isNaN will always return true if you give it a non number string and that's what is happening with you, if you try and input a number between 1 and 9 then your else will be executed.
Your validation works with number type inputs but since you want to validate a text input(name) then it can be done like this
your if statement
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
}
should be
if(x === "" || x.length > 10) {
text = "Input not valid";
}
because you need to check if the input is empty and if it is larger than 10 chars, besides I noticed you have two inputs with the same id!, the id is something unique it's not like classes, so pls change your HTML code

Simple Javascript Loop Using input box variable

I'm just trying to start with JavaScript and have put this little loop together. Providing I put 1 in the start box.. it works fine. If I put anything else though the loop itself never takes place.
According to the console my variables should all match the criteria for the loop to activate so I don't see the problem
function myFunction() {
console.clear();
var Start = document.getElementById("Start").value
console.log("Start=", Start)
var End = document.getElementById("End").value
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>
You need to use integers in the for loop, by default you use string, so you need to parse it first.
1st problem: '5' < '10' this is false.
2nd problem: '5'++ will convert it to 5 and only after that will be incremented.
function myFunction() {
console.clear();
var Start = parseInt( document.getElementById("Start").value, 10)
console.log("Start=", Start)
var End = parseInt(document.getElementById("End").value, 10)
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>

Social Security Number input validation

I have this sample:
function ssnFormat() {
$("#ssn").on('blur change', function() {
text = $(this).val().replace(/(\d{3})(\d{2})(\d{4})/, "$3-$2-$4");
if ($(this).val() == '' || $(this).val().match(text) || $(this).val().length == 0) {
$(this).removeClass('valid').addClass('invalid');
} else {
$(this).removeClass('invalid').addClass('valid');
}
});
}
$("#ssn").on('blur change', function() {
ssnFormat();
});
.valid {
border: 1px solid blue;
}
.invalid {
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="required-input" id="ssn" maxlength="9" type="text" name="ssn" placeholder="123-45-6789">
What I want to do these things are:
If I write the following text I want to validate this format 123-12-1234
If I write 123456789 I want to transform when click outside input in this format
123-12-1234
I tried to do this by using the function below but don't work
$("#ssn").on("click", function() {
var thisVal = $(this).val();
var value = thisVal.replace(/[^\/\d]/g,''); //here is a problem
$(this).val(value);
});
Can you please help me solve this problem?
Thanks in advance!
Try this
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">
Also there is another way to enforce user always enters that pattern -
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()" required pattern="\d{3}[\-]\d{2}[\-]\d{4}">
function myFunc() {
var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
var x = document.getElementById("ssn");
var res = patt.test(x.value);
if(!res){
x.value = x.value
.match(/\d*/g).join('')
.match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
.replace(/-*$/g, '');
}
}
.valid{
border:1px solid blue;
}
.invalid{
border:1px solid red;
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">

Prevent button jquery

I am using jQuery for min and maxlength. I want here to prevent button if minlength is not correct. I mean if user not entered minimum 8 digit, then prevent button.
jQuery:
var minLength = '8';
var maxLength = '13';
$("input[name=354]").keypress(function(){
if(this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if(this.value.length < minLength) {
$(this).css('border','1px solid #f00');
} else {
$(this).css('border-color','#cfdadd');
}
});
HTML button code:
<button type="button" class="btn next">Next</button>
You can add disabled attribute to button if length of input isn't valid.
var minLength = "5";
var maxLength = "10";
$("input").on("keydown change", function(){
var value = $(this).val();
// length is short
if (minLength > value.length){
$("button").attr("disabled", true);
$(this).addClass("error");
} else {
$("button").attr("disabled", false);
$(this).removeClass("error");
}
// length is long
if (value.length > maxLength)
this.value = value.slice(0, maxLength);
});
.error {
border: 2px solid rgba(255, 0, 0, 0.48);
box-shadow: 0px 0px 2px -1px red;
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="number" class="error" />
<button type="submit" disabled>Submit</button>
</form>
I think you need to use disabled.
And it would be better to use input instead of keypress.
var minLength = '8';
var maxLength = '13';
$('input[name=354]').on('input', function() {
if (this.value.length > maxLength) {
this.value = this.value.slice(0, maxLength);
}
if (this.value.length < minLength) {
if (!$(this).hasClass('invalid')) {
$(this).addClass('invalid');
}
$('.btn').attr('disabled', true);
} else {
$(this).removeClass('invalid');
$('.btn').attr('disabled', false);
}
});
.invalid {
border:1px solid #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="invalid" name="354" type="text">
<button type="button" class="btn next" disabled>Next</button>
Here's a fiddle

How to add placeholder <input type="datetime-local"> field?

I've been trying to add placeholder in input type='datetime-local' field but it doesn't work at all. Use css for solving the issue but still unable to do it :(
input[type="datetime-local"]:before{
content: 'Selecteer Datum';
color: #000;
text-align: center;
width:100%;
}
input[type="datetime-local"]:active:before, input[type="datetime-local"]:hover:before, input[type="datetime-local"]:visited:before, input[type="datetime-local"]:focus:before{
content: '';
width: 100%;
}
<form action="" method="post">
<div class="datetime">
<input type="datetime-local" >
</div>
</form>
This is kind of a wonky idea, change the input type to text, then it will convert to datetime-local on focus using the below javascript.
<input type="text" id="txtbox" placeholder="Heya">
<script>
var dtt = document.getElementById('txtbox')
dtt.onfocus = function (event) {
this.type = 'datetime-local';
this.focus();
}
</script>
Sharath Daniel is on the right lines. A jQuery version:
http://jsfiddle.net/2e97L3d0/1/
HTML
<form action="" method="post">
<div class="datetime">
<input type="text" id="datetime1" placeholder="Enter the starting date" >
</div>
Javascript
$(document).ready(function(){
$("#datetime1").focus( function() {
$(this).attr({type: 'datetime-local'});
});
});
I have tried this solution
Here I tried to get YYYY-MM-DD HH:mm pattern placeholder y, u can make your own format
Just change value format, data-date-format and add pattern in js too.
HTML :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<input type="datetime-local" data-date="" data-date-format="YYYY-MM-DD HH:mm" value="2000-01-01T00:00:00">
JS :
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD'T'HH:mm:ss")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
CSS:
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
In case the previous answers do not work or you don't want to use jquery or other libraries you can set the date input to a default value. This helps on browsers that displays the date input by default as dashes '--' so the user can understand what it's for. This works quite the same as a placeholder for me.
<form action="" method="post">
<div>
<input type="datetime-local" id= "dateInput" >
</div>
</form>
JS
const dateInput = document.getElementById("dateInput");
//date string must be in format 'yyyy-mm-ddT00:00'
let todayString = '2022-03-15T12:20';
dateInput.value= todayString;
If you want to go the extra mile, set the datetime-local to the current day of year using js
In the example below I set the datetime-local to the users current date, but you can set it to any value you choose.
function addZeros(time) {
if (time < 10) {
time = "0" + time;
}
return time;
}
const today = new Date();
let dd = today.getDate() ;
let mm = today.getMonth() + 1; //January is 0 so need to add 1 to make it 1!
let yyyy = today.getFullYear();
let hr = addZeros(today.getHours());
let min = addZeros(today.getMinutes());
dd = addZeros(dd);
mm = addZeros(mm)
let todayString = yyyy + '-' + mm + '-' + dd+'T'+ hr+':'+min;
dateInput.value= todayString;
A bit tricky, but it works:
Html:
<form action="" method="post">
<div class="datetime">
<input id="pholderInput" class="placeholder" type="datetime-local">
</div>
</form>
Css:
.placeholder
{
color: gray;
}
.focused
{
color: black;
}
Javascript:
var inp = document.getElementById("pholderInput");
var placeholderText = "default text";
inp.value = placeholderText;
inp.onfocus = function(e) {
if (inp.value == placeholderText)
{
inp.value = "";
inp.className = "focused";
}
};
inp.onblur = function(e) {
if (inp.value === "")
{
inp.value = placeholderText;
inp.className = "placeholder";
}
};
JSBin
Try this code:
$(document).ready(function(){
$("input[type='datetime-local']").attr('placeholder','date time');
});
FIDDLE DEMO

Categories

Resources