How to validate both input text - javascript

I want to show the message "Input Number Only" if I oninput the alphabet. The first text box is successfully show but when I input alphabet into the second text box it does not show anything at the span. How to edit my code so that it will show the message after I on input the alphabet. Here my code :
function allvalidate(){
var inp = document.getElementsByClassName('text');
for(var i in inp){
if(inp[i].type == "text"){
if(!/^\d{1,}$/.test(inp[i].value)){
error.textContent = "Input Number Only";
error.style.color = "red";
return false;
}
else {
error.textContent = "";
}
return true;
break;
}
}
}
<p>Number of Customer</p>
<p><input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" oninput="allvalidate()"></p>
<p>Age</p>
<p><input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" oninput="allvalidate()"></p>
<span id="error"></span>

Replace the following statement:
for(var i in inp){
with
for(let i=0 ;i<inp.length;i++){

A delegated event listener bound to the document can intercept and process all the input elements without needing to explicitly add the oninput event handler to each one as above. That event handler can likely also be simplified by using isNaN rather than a regex
const errspan=document.getElementById('error');
document.addEventListener('input',e=>{
errspan.textContent = "";
if( e.target.type=='text' && isNaN( e.target.value ) ) {
errspan.textContent = "Input Number Only";
}
})
#error{
color:red
}
<p>Number of Customer</p>
<p>
<input type="text" name="people" class="text" placeholder="no.of people" size="18" maxlength="10" />
</p>
<p>Age</p>
<p>
<input type="text" name="post" class="text" placeholder="postcode" size="18" maxlength="2" />
</p>
<span id="error"></span>

Related

Focus next Element in tabindex when pressing Enter key

Users on my application are used to press "Enter" when changing to the next input instead of "Tab", so I've been trying to change focus to the next Element in tabindex when pressing "Enter" instead of "Tab" given this code:
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Now that I've achieved it I want to share my solution so the next person who has this problem finds the solution quickly.
Solution
In my case I aimed $("#data") for the function to trigger but you can use it with $(window).
This function will get triggered on keydown, will check if the key is "Enter" (wich key code is 13), look for the next element of the focused element (activeElement) according to the tabindex and then will focus it.
$("#data").keydown(function(e) {
if(e.keyCode == 13){
let active = document.activeElement;
let target = $('[tabindex="' + (active.tabIndex + 1) + '"]');
target.focus();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>
Edit
In reference to #freedomn-m 's comment, this is his code to set the tabindex attribute on the non-readonly elements:
$(() => $("#data :input:not([readonly])").attr("tabIndex", (i, a) => i));
That's the code that I was using before:
$(document).ready(function(){
let inputs = $('#data :input');
let tabindex = 0;
for(let i = 0; i < inputs.length; i++){
if($(inputs[i]).attr("readonly") !== "readonly"){
inputs[i].setAttribute("tabindex", tabindex);
tabindex++;
}
}
})
const inputs = document.querySelectorAll('#data input');
const inputsArray = Array.prototype.slice.call(inputs);
document.addEventListener('keypress', function (event) {
const key = event.which || event.keyCode;
if (key === 13) { // 13 is the keycode for the Enter key
const activeElement = document.activeElement;
const index = inputsArray.indexOf(activeElement);
if (index > -1 && index < inputsArray.length - 1) {
inputsArray[index + 1].focus();
}
}
});
<div id="data">
<input type="text" tabindex="0">
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" value="Lorem ipsum" readonly>
<input type="text" value="Lorem ipsum" readonly><br/>
<input type="text" tabindex="1">
<input type="text" tabindex="2">
</div>

Change input to Upper Case with CapsLock on

I would just like to know is it possible to change the input automatically to capitalized on a certain input field where the user entered a value with Caps Lock on.
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps On = TEST NAME
Expected: Test Name
<input placeholder="Brand Name" style="text-transform: capitalized" type="text" />
Caps Off = test name
Default: Test Name
I know some Names looks like Reader Van der Bank where not all the name parts are capitalized, but still would like to know if its possible. Thanks
Alternative : Think i might be using a php function to transform everything to lowercase and then capitalized.
Here is a javascript function to do that, if there is no CSS solution for it.
var id = document.getElementById("test");
function change() {
var arr = id.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
id.value = arr.join(" ");
}
id.addEventListener("change", change);
id.addEventListener("keyup", change);
<input placeholder="Brand Name" id="test" type="text" />
For multiple elements with class test
var elements = document.getElementsByClassName("test");
function change() {
var arr = this.value.split(" ").map(function(x) {
return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
});
this.value = arr.join(" ");
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("change", change);
elements[i].addEventListener("keyup", change);
}
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
<input placeholder="Brand Name" class="test" type="text" />
Do you want to enter all the text capitalized in the input? then u can use text-transform:uppercase in css and if u want to change it while typing you can use toUpperCase() on keyup of that input.
style="text-transform: capitalize"
(Question was edited. New Answer.)
Give your input an id, for this example let's say it's called "theInputId".
Then add an onkeypress event to it also and call the function script I've listed below.
<input placeholder="Brand Name" style="text-transform: capitalized"
type="text" id="theInputId" onkeypress="capsLock(event)">
<script>
//Script to check if Caps Lock is on.
function capLock(e){
kc = e.keyCode?e.keyCode:e.which;
sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)){
document.getElementById('theInputId').style.textTransform = 'lowercase'
document.getElementById('theInputId').style.textTransform = 'capitalize'
}
}
</script>

How would it be possible to call multiple js functions to a single form?

Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);

Extract Unique Element ID using Javascript

Okay, so I have a form which adds an item to a list of items and does calculations with it, but every new item thats added is done on the users side before being submitted to the server for verification and updating of database. Now, I've looked at other answers and couldnt really get an answer. If the user adds a new item and enter a quantity and rate it should calculate the amount automatically, how would one extract the unique ID identifier to change the value of the amount? The code below and in this case the unique identifier is 19786868. The length of this identifier is always different and their is no unique pattern, the length and value is generated by a random command.
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
How would I extract this unique identifier with the OnChange command in JavaScript to calculate the amount value?
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
var id = el.id.replace(/\D+/g,"");
console.log( id ); // "19786868"
});
so basically use a this.id.replace(/\D+/g,"") where all non Digit \D gets replaced by ""
Here's an example using the input event:
[].forEach.call(document.querySelectorAll(".form-control"), function(el) {
el.addEventListener("input", function() {
var id = this.id.replace(/\D+/g,"");
alert( id );
}, false)
});
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_123_foobar" />
Take note that: asd_123_foo_9 will return 1239 as result so make sure to always have asd_123_foo as ID value
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" onchange="extractId(event);"/>
And in javascript :
function extractId(event) {
var elem = event.target;
var myArr = elem.id.split('_');
var yourUnique_id = myArr[3];
}
To be able to respond to newly added input controls, you need to capture the change event at some parent element, otherwise you will not trap the change on newly added elements.
Here is some code that handles the change event on the document. As this event bubbles up, it will eventually get there, so we can respond to it:
For extracting the number from the input's id, we can use a regular expression:
document.onchange = function(e) {
var match = e.target.id.match(/^(list_item_attributes_.*?_)(rate|quantity)$/);
if (!match) return; // not rate or quantity
// read rate and quantity for same ID number:
var rate = +document.querySelector('#' + match[1] + 'rate').value;
var quantity = +document.querySelector('#' + match[1] + 'quantity').value;
// write product as amount:
document.querySelector('#' + match[1] + 'amount').value = rate*quantity;
}
Quantity: <input class="form-control" type="text" id="list_item_attributes_19786868_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_19786868_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_19786868_amount" /><br>
<p>
Quantity: <input class="form-control" type="text" id="list_item_attributes_14981684_quantity" /><br>
Rate: <input class="form-control" type="text" id="list_item_attributes_14981684_rate" /><br>
Amount: <input class="form-control" type="text" id="list_item_attributes_14981684_amount" /><br>
As you have asked to respond to the change event, I have kept it that way, but you might be interested to use the input event instead, which will trigger as soon as any character changes in an input.
The above sample does not protect the amount fields from input. You should probably do something about that, because users could just overwrite the calculated result.
document.querySelector(".my-form").addEventListener("change", function(e) {
var changed = e.target;
var matchedId = changed.id.match(/^(list_item_attributes_[^_]*)_/);
if (!matchedId) {
// this isn't one of the relevant fields
return;
}
var uniquePrefix = matchedId[1];
var quantity = document.querySelector("#" + uniquePrefix + "_quantity");
var rate = document.querySelector("#" + uniquePrefix + "_rate");
var amount = document.querySelector("#" + uniquePrefix + "_amount");
var newVal = quantity.value * rate.value;
if (isNaN(quantity.value) || isNaN(rate.value) || isNaN(newVal)) {
amount.value = "";
} else {
amount.value = newVal;
}
});
<form class="my-form">
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</form>
If the user adds a new item and enter a quantity and rate it should
calculate the amount automatically, how would one extract the unique
ID identifier to change the value of the amount?
You can use input event; for loop; attribute contains selector [attributeName*=containsString], .nextElementSibling, .previousElementSibling, to sum values of id containing "quantity" and id containing "rate" and set result at id containing "amount"
function calculate() {
this.parentElement.querySelector("[id*=amount]")
.value = +this.value
+ +(/quantity/.test(this.id)
? this.nextElementSibling
: this.previousElementSibling
).value
}
var elems = document.querySelectorAll("[id*=quantity], [id*=rate]");
for (var i = 0; i < elems.length; i++) {
calculate.call(elems[i]); elems[i].oninput = calculate;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786868_quantity" value="1" />
<input class="form-control" type="text" id="list_item_attributes_19786868_rate" value="2" />
<input class="form-control" type="text" id="list_item_attributes_19786868_amount" />
</div>
<div>
<input class="form-control" type="text" id="list_item_attributes_19786867_quantity" value="3" />
<input class="form-control" type="text" id="list_item_attributes_19786867_rate" value="4" />
<input class="form-control" type="text" id="list_item_attributes_19786867_amount" />
</div>

Combining javascript functions

hi i am using javascript function to balnk ma textboxes when its clicked, initially the text boxes contain their respective label names, eg: Client Name, Company etc. When the text box is clicked it makes the text box empty so data can be types. for this i am using a javascript function and for each textbox i have to have a seperate function, can anyone tell me how i can combine all these function, the only different thing in each function is the value used in the textbox and the textbox name.
The Javascript function
function clientnameclear() {
if(document.bunkerfrm.clientname.value=="Client Name") {
var bunkerfrm = document.bunkerfrm.clientname.value="";
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.clientname.focus();
}
}
function clientnamereset() {
if(document.bunkerfrm.clientname.value=="") {
var bunkerfrm = document.bunkerfrm.clientname.value="Client Name";
}
}
function vesselnameclear() {
if(document.bunkerfrm.vesselname.value=="Vessel Name") {
var bunkerfrm = document.bunkerfrm.vesselname.value="";
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
else {
var bunkerfrm = document.bunkerfrm.vesselname.focus();
}
}
function vesselnamereset() {
if(document.bunkerfrm.vesselname.value=="") {
var bunkerfrm = document.bunkerfrm.vesselname.value="Vessel Name";
}
}
function compclear() {
if(document.bunkerfrm.company.value=="Company") {
var bunkerfrm = document.bunkerfrm.company.value="";
var bunkerfrm = document.bunkerfrm.company.focus();
}
else {
var bunkerfrm = document.bunkerfrm.company.focus();
}
}
function compreset() {
if(document.bunkerfrm.company.value=="") {
var bunkerfrm = document.bunkerfrm.company.value="Company";
}
}
The Html Code is
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" class="txtbox" value="Client Name" onmousedown="clientnameclear()" onclick="clientnameclear()" onblur="clientnamereset()" />
<br /><br>
<input type="text" name="company" class="txtbox" value="Company" onmousedown="compclear()" onclick="compclear()" onblur="compreset()" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
First, store the default values somewhere, such as the alt of the given input.
<form name="bunkerfrm" id="bunkerfrm" action="#" method="post"><br>
<input type="text" name="clientname" alt="Client Name" class="txtbox" value="Client Name" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="text" name="company" class="txtbox" alt="Company" value="Company" onfocus="clear_text(this);" onblur="reset_text(this);" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" value="Send Your Inquiry" /><br>
</form>
Then pass the input element this as the parameter to these onfocus/onblur functions:
function clear_text(elem)
{
if (elem.value == elem.alt)
elem.value = "";
}
function reset_text(elem)
{
if (elem.value == "")
elem.value = elem.alt;
}
Which will clear the input when it gets focus if its value is the same as the placeholder stored in the alt attribute. The event onblur will trigger the reset_text function which will check if the value is empty and restore it to the default placeholder stored in the alt attribute.
Use placeholder:
<input type="text" name="clientname" placeholder="Client Name" class="txtbox" />
<br /><br>
<input type="text" name="company" class="txtbox" placeholder="Company" />
<br /><br>
<input type="submit" name="submitting" class="bunksubmit" placeholder="Send Your Inquiry" /><br>
</form>
I suggest you use and/or study existing libraries, such as:
In-Field http://fuelyourcoding.com/scripts/infield/
ClearField http://labs.thesedays.com/projects/jquery/clearfield/

Categories