Validating function with getElementById - javascript

I'm trying to use getElementById to validate both the quantity and price are integers. Any troubleshooting help would be appreciated. I've created a couple of inputs in HTML as well.
<body>
<section>
<p><input name="quantity" type="text" id="quantity"
placeholder="quantity" autofocus></p>
<p><input name="price" type="text" id="price" placeholder="price"></p>
</section>
<script>
quantity.addEventListener("blur", validate, false);
price.addEventListener("blur", validate, false);
function validate() {
box = this.id;
data = this.value;
thequantity = document.getElementById("quantity");
theprice = document.getElementById("price");
thetotal = document.getElementById("total");
if (data) {
error1 = thequantity.value.match(/[0-9\.]/);
error2 = thequantity.value.match(/[0-9\.]/);
if (!error1 && !error2) {
alert("Please enter a number");
price = Number(theprice.value);
quantity = Number(thequantity.value);
thetotal.value = thequantity.value * theprice.value;
}
if (error1) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
if (error2) {
alert("Please enter a number");
document.getElementById(box).value = "";
}
} else {
var num = box.value(/[0-9]/);
document.getElementById(box).value = thetotal;
}
}
</script>

Just check if converting to a number does not result in NaN:
if (isNaN(Number(document.getElementById("quantity").value))) {
alert("Please enter a number.");
}

Related

Form doesn't remove alert from the first input box when the input being an empty string is changed to false

I am doing an assignemnt for school to showcase our knowledge of javascript. It is doing everything I want it to except when I adjust the first input from an empty string to a value it still has the display of first name required. I was also wondering if anyone had insight as to how to display the needed inputs when the other buttons I have clicked are cliked as I don't want the other functions to run unless all inputs are filled in the form. Thanks!
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t2result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t1result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
you were getting wrong element in your function validate in first condition , in else condition you were getting t2result instead of t1, hope this will work now.

trying to clear value in textbox in javascript function

i am trying to put validation on a textbox onkeyup. Textbox should contain only 5 digit value and after decimal only upto 4 decimal places. eg,12345 ,12345.2345
if user enter value other than regex then the texbox should become blank and i want it to be done in function and this function should be generic so that any other can use this function
.Aspx
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this.value)" />
Script function
<script type="text/javascript">
function isFloatNumber(value) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
value = "";
return false;
}
return true;
}
</script>
function isFloatNumber(elem) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(elem.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
elem.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN1' value='' runat="server" onkeyup="isFloatNumber(this)" />
<input type="number" id='inpSurfIndN2' value='' runat="server" onkeyup="isFloatNumber(this)" />
You can use above snippet which will work for n numbers of inputs.
Updating value = ""; doesn't update the UI element. You should access the UI Element object by passing this and update the value like this.value = " " else you should use the selectors like document.getElementbyId() to access those object like document.getElementbyId('inpSurfIndN').value = ""
One of way you can use below logic,
function isFloatNumber(obj) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(obj.value);
if (regmatch == null || regmatch == false) {
alert("Please fil correct expression");
obj.value = "";
return false;
}
return true;
}
<input type="number" id='inpSurfIndN' value='' runat="server" onkeyup="isFloatNumber(this)" />
var n = document.getElementById("numPeople"),
r = document.getElementById("result");
n.addEventListener("keyup", function(e) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(n.value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
n.value='';
return false;
}
}, false);
<input id="numPeople" type="number" min="0" value="" placeholder="Pick a number" />
You cannot access the value variable which is passed as a parameter, it doesnt reference to the value of the input box
Instead you can access the element and change the value like below:
function isFloatNumber(eve) {
var regex = /^[0-9]\d{0,4}(\.\d{1,4})?%?$/
var regmatch = regex.test(value);
if (regmatch == null|| regmatch==false) {
alert("Please fil correct expression");
var elem = eve.currentTarget;
elem.value = "";
return false;
}
return true;
}

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

How to Validate Input in JavaScript?

I am trying to validate a input field. The input field should take only numbers, if not it will alert "input must be a number". And if the field is empty it will do nothing. But when I left the field empty it will aslo alert me. How can I fix this.
Here is my code
<div class="form-group">
<label class="col-lg-2 control-label">Gross Salary</label>
<div class="col-lg-8">
<input class="form-control" placeholder="Gross Salary" type="text" name="gross_salary"id="tax4">
</div>
</div>
and javascript code
<script type="text/javascript">
var validate_int_taxid = function() {
var tax = document.getElementById("tax4");
var tax_id = parseFloat(tax.value);
if (isNaN(tax_id)) {
alert("Gross Salary must be a Number");
return false;
}
return true;
}
</script>
Thank You
make it like
var tax = document.getElementById("tax4");
if(tax.value!="") {
var tax_id = parseFloat(tax.value);
if (isNaN(tax_id)) {
alert("Gross Salary must be a Number");
return false;
}
return true;
} else {
return false;
//do nothing
}
Here is a fiddle.
Here you go:
<script type="text/javascript">
var validate_int_taxid = function() {
if (tax.value !="") {
var tax_id = parseFloat(tax.value);
if (isNaN(tax_id)) {
alert("Gross Salary must be a Number");
return false;
}
return true;
}
return false;
}
</script>
Try with this.
<script type="text/javascript">
var validate_int_taxid = function() {
var tax = document.getElementById("tax4");
if(tax.value!="" )
{
var tax_id = parseFloat(tax.value);
if (isNaN(tax_id)) {
alert("Gross Salary must be a Number");
return false;
}
}
}
</script>

Categories