JavaScript if statment don't work - javascript

I need help with javascript. here is my problem:
<script type="text/javascript">
function validateForm() {
var ime = document.getElementById('ime');
var prezime = document.getElementById('prezime');
var telefon = document.getElementById('telefon');
var datum = document.getElementById('datum');
var patt1 = /^\+[0-9]+$/;
if (telefon.match(patt1) == null) {
alert("Niste dobro uneli broj");
}
if (ime.value.length == 0 && prezime.value.length == 0 && telefon.value.length == 0 && datum.value.length == 0) {
alert("Niste dobro uneli podatke!");
return false;
}
}
</script>
<form action="popup.php" method="post" onsubmit="return validateForm()">Vase ime:
<input type="text" name="ime" id="ime"> <br/>
Vase prezime:
<input type="text" name="prezime" id="prezime"> <br/>
Broj telefona:
<input type="text" name="telefon" id="telefon"> <br/>
Datum rodjenja:
<input type="text" name="datum" id="datum"> <br/>
<input type="submit" name="save" value="sacuvaj">
</form>
I don't understand why telefon.match(patt1)==null) doesn't work. Please help!

Reason is because you can't apply regex to HTML Element, you can apply it to its value:
var telefon = document.getElementById('telefon').value;
Then you can execute your regex on var telefon

telefon is a DOM element, not a string
telefon.value can be matched

The object stored in telefon will be a DOM element (e.g. HTMLDivElement), which has no method "match". You'll want to extract the pertinent text from that element before matching. How you do that will depend on the exact DOM type:
if (telefon.value.match(patt1) == null) // For form elements...
if (telefon.innerHTML.match(patt1) == null) // For "plain" DOM elements...

Related

How to validate length and match required character?

I want to hide the submit button if value does not match the required type, I m able to hide it on the length, but my match does not work.
JavaScript Code:
function submitChangej(){
var inputlastName = document.getElementById("lastname");
var inputfirstName = document.getElementById("firstname");
var inputmobileNumber = document.getElementById("mobilenumber");
var inputidNumber = document.getElementById("idnumber");
var firstname = /^[a-zA-Z-\s]{2,128}$/;
var lastname = /^[a-zA-Z-\s]{2,128}$/;
var mobilenumber = /^[0-9]{10,20}$/;
var idnumber = /^([0-9]){2}([0-1][0-9])([0-3][0-9])([0-9]){4}([0-1])([0-9]){2}?$/;
var inputSubmit = document.getElementById("apply");
var Container = document.getElementById('Agreement');
if((inputfirstName.value.length < 2 || inputfirstName.value.length > 128 ) || ( inputlastName.value.length < 2 || inputlastName > 128 ) || (inputmobileNumber.value.length < 10 || inputmobileNumber > 20) || (inputidNumber.value.length < 13)){
Container.style.display = 'none';
}
else{
Container.style.display = 'block';
}
var Container = document.getElementById('Agreement');
if((firstname.match(firstname) != null) || (lastname.match(lastname) != null) || (mobilenumber.match(mobilenumber) != null) || (idnumber.match(idnumber) != null)){
Container.style.display = 'none';
}
else{
Container.style.display = 'block';
}
}
HTML Code:
<form >
<label for="firstname"><span class="starRequired"><b>*</b> </span>First name:</label><br>
<input type="text" name="firstname" id="firstname" required autofocus="autofocus" pattern="[a-zA-Z-\s]{3,128}" onkeyup="submitChangej();" onkeypress="checkFirstname(this.value);" value="">
<br/><label for="lastname"><span class="starRequired"><b>*</b> </span>Last name:</label><br>
<input type="text" name="lastname" required id="lastname" pattern="[a-zA-Z-\s]{3,128}" onkeyup="submitChangej();" onkeypress="checkLastname(this.value);"
onblur="checkLastname(this.value);" value="">
<br/><label for="mobilenumber"><span class="starRequired"><b>*</b> </span>Mobile Number:</label><br/>
<input type="text" name="mobilenumber" required id="mobilenumber" onkeyup="submitChangej();" onkeypress="checkMobilenumber(this.value);"
onblur="checkMobilenumber(this.value);" value="">
<br/><label for="idnumber">ID Number:</label><br/>
<input type="text" name="idnumber" id="idnumber" maxlength="13" onkeyup="submitChangej();" onkeypress="checkIdnumber(this.value);"
onblur="checkIdnumber(this.value);" value="">
<div id="Agreement" style="display:none">
<input type="submit" id="apply" name="apply" value="Apply"
onclick="if(!this.form.terms.checked){alert('Please indicate that you accept the Agreement');return false}"/>
<input type="checkbox" id="terms" name="terms" >
<label id="accept" >I accept the Agreement</label>
<textarea name="textfield" id="textfield" rows="10" cols="105" readonly="readonly" >
1. Acceptance
1.1 I have read and accepted the above terms and conditions.
</textarea>
</span>
</div>
</form>
I than call my method submitChangej()on the fields that i validate.
The button should be hidden when match and length are invalid, if everything is correct than the button should appear. The length work good, but the match of required characters does not match
Change the final lines of your code to:
if(!firstname.test(inputfirstName.value) || !lastname.test(inputlastName.value) || !mobilenumber.test(inputmobileNumber.value) || !idnumber.test(inputidNumber.value)){
Container.style.display = 'none';
}
else {
Container.style.display = 'block';
}
As it was already mentioned you're trying to find a match on a pattern itseld, which has no sense. Then, the match method is used to get a matching string, but you only want to test the string against some pattern, so use the test method instead.
I would suggest simplifying this and letting the browser do more of the leg work for you by putting this in a form on change listener:
inputSubmit.style.display = (document.querySelectorAll('*:invalid').length)? = 'none' : 'block';

javascript error: function is not defined

I was trying to find the reason why my code doesnt work, and chrome comes back with this eror:
Uncaught ReferenceError: calcMPG is not defined...
Can someone spot my mistake ?(desperate)
<script type="text/javascript">
function calcMPG() {
document.calc.startingMileage.value = startMileage;
document.calc.endingMileage.value = endMileage;
document.calc.gallonsUsed.value = gallUsed;
var MPG = (endMileage - startMileage) / gallUsed;
if (isNAN(startMileage) || isNAN(endMileage) || isNAN(gallUsed)) alert('please type in numbers only!');
else document.calc.milesPerGalon.value = MPG;
}
</script>
<form name="calc">Starting mileage:
<input type="text" value="0" name="startingMileage" onchange="calcMPG()">
<br>Ending mileage:
<input type="text" value="0" name="endingMileage" onchange="calcMPG()">
<br>Gallons used:
<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()">
<br>Miles per galon:
<input type="text" value="0" name="milesPerGalon">
</form>
Your declarations are wrong please correct them.
var startMileage = document.calc.startingMileage.value ;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
I don't know why you do that, but try this:
<script type="text/javascript">
function calcMPG(){
var startMileage = document.calc.startingMileage.value,
endMileage = document.calc.endingMileage.value,
gallUsed = document.calc.gallonsUsed.value,
MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed)){
alert('please type in numbers only!');
} else {
document.calc.milesPerGalon.value = MPG;
}
}
</script>
<form name="calc">
Starting mileage:<input type="text" value="0" name="startingMileage" onchange="calcMPG()"><br>
Ending mileage:<input type="text" value="0" name="endingMileage" onchange="calcMPG()"><br>
Gallons used:<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()"><br>
Miles per galon:<input type="text" value="0" name="milesPerGalon">
</form>
startMileage
and your other right side references don't mean anything, they are undefined variables.
Give your inputs an id and fetch the values from them like this:
var startingMileage = document.getElementById('startingMileage').value;
Check here Fiddle
function calcMPG(){
var startMileage = document.calc.startingMileage.value;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
var MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed))
alert('please type in numbers only!');
else
document.calc.milesPerGalon.value = MPG;
}

Javascript text field validation

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;
You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>
Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.

Javascript return false, alert not working

i'm trying to make sure certain fields are not left blank in my form. it seems simple enough but for some reason it's not working. The alert is not showing, and return false is not working (it continues to post blank entries into my database) please help, what am i doing wrong. thank you!
the script:
function check(){
var name = getElementById('name');
var date = getElementById('date');
var pri = getElementById('pri');
var asapc = getElementById('asapc');
var asapn = getElementById('asapn');
var obr = getElementById('obr');
var obc = getElementById('obc');
var obn = getElementById('obn');
if (name.value == "" || date.value == "" || pri.value == "not" || asapc.value == "" || asapn.value == "" || obr.value == "" || obc.value == "" || obn.value == "") {
alert( "One or more fields were not filled out." );
return false ; }
return true;
}
The code:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="check();">
<!-- fields here -->
<INPUT TYPE="submit" VALUE="CONTINUE">
access every element as document.getElementById... and in form tag write this onsubmit="return check();" instead if onsubmit="check();"
You are missing return here:
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
You are missing (document) this is the correct syntax:
document.getElementById('id');
<script>
function check() {
var name = document.getElementById('name');
var date = document.getElementById('date');
if (name.value == "" || date.value == "") {
alert( "One or more fields were not filled out.");
return false;
}
}
</script>
and getElementByID means by ID not my tagName
<FORM ACTION="step2.php" METHOD="POST" onsubmit="return check();">
<input name="name" type="text" value="" id="name">
<input name="date" type="text" value="" id="date">
.....etc..
<INPUT TYPE="submit" VALUE="CONTINUE">
</FORM>

Javascript validation for multiple textboxes

I am having some trouble figuring out how to validate my textboxes using js. I have 10 textboxes, the user can fill out any number 1-10, but cant fill out 0. Here is the js that I have written, but it only returns true if all 10 textboxes are filled, rather than just checking if one is filled.
function submitIt() {
if (document.isForm.Student_ID.value == null) {
alert ("You must enter a Colleague ID.");
return false;
} else {
return true;
}
}
And here is the form.....
<form name="isForm" onSubmit="return submitIt()">
<input name="Student_ID" type="text" id="idField1" />
<input name="Student_ID" type="text" id="idField2" />
<input name="Student_ID" type="text" id="idField3" />
<input name="Student_ID" type="text" id="idField4" />
<input name="Student_ID" type="text" id="idField5" />
<input name="Student_ID" type="text" id="idField6" />
<input name="Student_ID" type="text" id="idField7" />
<input name="Student_ID" type="text" id="idField8" />
<input name="Student_ID" type="text" id="idField9" />
<input name="Student_ID" type="text" id="idField10" />
<input name="SUBMIT" type="submit" />
</form>
I realize that I could change all of the names, and check each one, but I am trying to avoid that much clutter in my code, and am curious the best way to do this. Any help is appreciated, thanks!
You can get a collection of all these textboxes with document.getElementsByName. Then loop through them, and make sure at least one is filled in:
var allTbs = document.getElementsByName("Student_ID");
var valid = false;
for (var i = 0, max = allTbs.length; i < max; i++) {
if (allTbs[i].value) {
valid = true;
break;
}
}
DEMO
Function is iterating by all of the student text boxes and return true if some element is filled out. Protected against that if input contain only spaces :)
function submitIt() {
for( var i = 0, t = document.getElementsByName( "Student_ID" ), l = t.length; i < l; i++ )
if( t[i].value && !/^\s+$/.test( t[i].value ) )
return true;
return false
}
Demo on: http://jsfiddle.net/hhD2x/
you can use jquery.
add common class name for all your textboxes i.e.
<input name="Student_ID" type="text" id="idField1" class="student" />
now in js function
function submit()
{
$('.student').each(function() {
if($(this).val() == '' || $(this).val() == null)
{
// your error message
return false;
}
}
}
this function check all the elements with student class.
$('input[type="text"], select,
:input[type="date"],
:input[type="email"],
:input[type="radio"]').each(function () {
if ($.trim($(this).val()) == '' ) {
// your error message here
isValid = false;
}
});

Categories

Resources