Why Javascript is not getting called - javascript

Javascript code is
function jsCheck() {
var msg = '';
//Move email checker to first line of javascript validation
if (document.form1.email.value.indexOf(".") <= 3 && document.form1.email.value.indexOf("#") <= 2){ msg = msg + 'Valid Email Address\n'; }
if (document.form1.name.value == ""){ msg = msg + 'Full Name\n'; }
if (document.form1.company.value == ""){ msg = msg + 'Company Name\n'; }
if (document.form1.telephone.value == ""){ msg = msg + 'Telephone No\n'; }
if (document.form1.country.value == ""){ msg = msg + 'Country\n'; }
if (msg != ''){
alert('The following fields are missing\n\n' + msg);
return false;
}
form name="form1" method="post" action="apply_confirm.asp" onSubmit="return jsCheck();"
Why the javascript is not getting called

Well, if your original posting is accurate (a number of things have changed as people have attempted to make your post legible), it's because everything you posted is enclosed in HTML comments, <!-- ... -->.
And yeah, as far as providing the solution as soon as possible goes, you might want to keep in mind that we don't work for you.

You most likely have an error in your javascript code.
Test your javascript in Firefox.
Open the error console with CTRL+SHIFT+J or Tools -> Error Console.
Look for an error message or warning explaining the javascript error.
If you are unsure what the error message means, add it to the question so we can explain it to you.

Try this:
<html>
<head>
<script type="text/javascript">
function jsCheck() {
var msg = '';
//Move email checker to first line of javascript validation
if (document.form1.email.value.indexOf(".") <= 3 && document.form1.email.value.indexOf("#") <= 2){ msg = msg + 'Valid Email Address\n'; }
if (document.form1.name.value == ""){ msg = msg + 'Full Name\n'; }
if (document.form1.company.value == ""){ msg = msg + 'Company Name\n'; }
if (document.form1.telephone.value == ""){ msg = msg + 'Telephone No\n'; }
if (document.form1.country.value == ""){ msg = msg + 'Country\n'; }
if (msg != ''){
alert('The following fields are missing\n\n' + msg);
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" method="post" action="apply_confirm.asp" onSubmit="return jsCheck();">
<input type='text' id='name'/>
<input type='text' id='company'/>
<input type='text' id='email'/>
<input type='text' id='telephone'/>
<input type='text' id='country'/>
<input type='submit' value='submit'/>
</form>
</body>
</html>

See http://www.w3schools.com/HTMLDOM/dom_nodes_access.asp

Related

interactive PDF Form-Validation Javascript

I'm trying to validate my interactive PDF. So if i click on a button (for validating) there's following code behind it:
var isBlank = false;
var blank = "Please fill following fields:";
var isNotValid = false;
var notValid = "Please check input data in following fields:";
var message = "";
var t = ['Division', 'Oragnisationseinheit', 'Name', 'KZZ', 'Privataddresse'];
var i;
for(var i=0; i<t.length;i++){
//validation text fields needs to be filled in
if (this.getField(t[i]).value == "") {
blank = blank + "\n" + this.getField(t[i]).name;
isBlank = true;
}
//validation text field must contain only lower case letters
if (/^[a-z]*$/.test(this.getField(t[i]).value) == false) {
notValid = notValid + "\n" + this.getField(t[i]).name;
isNotValid = true;
}
//generate message
if (isBlank == true) {
message = blank + "\n" + "\n";
}
if (isNotValid == true) {
message = message + notValid;
}
}
//check all conditions
if ((isBlank == true) || (isNotValid == true)) {
//show message
app.alert({ cMsg: message, cTitle: "Input data error" });
}
The problem is now, if I press the button there's no reaction. --> the var message wont being displayed. Where is the issue?
Thanks for all ideas.
You might try instead to add a custom validation script that would first check to be sure the field isn't blank and if not, simply change the input to lower case so the user doesn't need to modify the field themselves.
Add the following code to the custom field validate script. This should work for any text field.
if (event.value.length == 0) {
app.alert({ cMsg: event.target.name + " cannot be blank.", cTitle: "Input data error" });
}
else {
event.value = event.value.toLowerCase();
}

Javascript loops are crashing my website

So, I have a question about Javascript and HTML. Below I have my code, and I'm not sure why but whenever I try and run it(ie: hit Submit), my website freezes. I have it set right now so that it checks if the username/password EXISTS, but it does not have to be a combination of the 2 quite yet. Can someone help me?
<!DOCTYPE html>
<html>
<title> Welcome to my website!</title>
<body>
<form action="action_page.php" method = "post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Submit" onclick="myLogin()">
</form>
<script type="text/javascript">
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
usernames[5] = "stop";
passwords[5] = "stop";
var a = false;
var b = false;
var i = 1;
while(a===false) {
if(usernames[i] != form.user.value) {
i++;
}else if(usernames[i] == form.user.value){
a=true;
}else if(usernames[i] == "stop"){
alert("Incorrect username or password!");
a=true;
};
};
i = 1;
while(b===false) {
if(passwords[i] != form.pass.value) {
i++;
}else if(passwords[i] == form.pass.value){
b=true;
}else if(passwords[i] == "stop"){
alert("Incorrect username or password!");
b=true;
};
};
if(b&&a===true){
alert("Welcome " + document.getElementsByName("user") + "!");
}else{
alert("I do not recognize you " + document.getElementsByName("pass") + "!");
};
};
</script>
</body>
Don't use a while loop at all, just exit the myLogin function if it was an invalid username or password.
Be aware that what you have written here is completely insecure. Anyone visiting your website with even a basic technical knowledge can see your full list of usernames and passwords.
I changed your code a lot, but I think it is what you wanted. In your scenario beside a few errors, any valid username and any valid password would match. (i.e. user = "rdoucett" and psw= "hovland1").
function myLogin(){
var usernames = ["rdoucett", "hovland"];
var passwords = ["Rd200161", "hovland1"];
var username;
for (var i = 0; i < usernames.length; i++) {
if (usernames[i] == form.user.value) {
username = usernames[i];
break;
}
}
if (!username || passwords[i] != form.pass.value) {
alert("Incorrect username or password!");
}
else {
alert("Welcome " + document.getElementsByName("user") + "!");
}
};
From the security point of view, as already been said this is very insecure. You should think the HTML and JS as information any client can see. So this kind of functionality is what you must do server side.
Also note that the alerts wont avoid the form of being submitted. If you want to avoid that, you should add return false;.

Basic Form Validation with JavaScript/HTML

I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.
First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.
You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer
The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}

Error: 'null' is null or not an object in IE8 not Chrome or Firefox

I downloaded code to password protect a page. It work OK in Chrome and Firefox but not in IE8. I'm on XP SP3.
It will be accessed by several others so I don't want to have to say 'Doesn't work in IE8 or x or y'
Unlike a previous question it works locally but not from the web. My home page has a link to a file containing the code below. It's at www.bscomputers.co.uk under Glenfest
Is there a fix for this please? I haven't got access to php etc and it's a low security thing so I want an in the page solution.
the code is as follows:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password', ' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") { //error on this line
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV += 1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.', 'Password');
}
if (pass1.toLowerCase() != "password" & testV == 3)
history.go(-1);
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Credit for the code to http://www.javascriptkit.com/ who don't seem to offer any help.
I am not quite sure if this is the problem with IE8, but you are redefining the pass1 variable in each loopthrough.
Try this in IE.
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password', ' ');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "letmein") { //error on this line
alert('You Got it Right!');
window.open('protectpage.html');
break;
}
testV += 1;
pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.', 'Password');
}
if (pass1.toLowerCase() != "password" & testV == 3)
history.go(-1);
return " ";
}
http://jsfiddle.net/ajY76/
And as NDM already noticed, this is no protection at all.

Javascript object is null or not object in IE

I have a form to which a checkbox is added by javascript, when the form is submitted it checks if the checkbox has been ticked or not. This works fine in Firefox or Chrome, but in IE7 or 8 it causes an error document.myform.mycheckbox.checked is null or not an object.
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.name = "mycheckbox";
checkbox.value= 291;
var div = document.getElementById("addcb");
div.appendChild(checkbox);
checkbox.checked = false;
In the form tag I have onSubmit="return CheckForm();", which works ok in Firefox or Chrome, but in IE7 or 8 it submits the form without checking the form or other form objects.
if (document.myform.mycheckbox.checked == false){
errorMsg += "\n\tAgree \t- Please Click I Agree Checkbox";
}
//If there is aproblem with the form then display an error
if ((errorMsg != "") || (errorMsgLong != "")){
msg = "_______________________________________________________________\n\n";
msg += "The form has not been submitted because there are problem(s) with the form.\n";
msg += "Please correct the problem(s) and re-submit the form.\n";
msg += "_______________________________________________________________\n\n";
msg += "The following field(s) need to be corrected: -\n";
errorMsg += alert(msg + errorMsg + "\n" + errorMsgLong);
return false;
}
return true;
I used the Developer tools to create a Brakpoint which reports the error:
document.myform.mycheckbox.checked is null or not an object
While creating it, give it an ID as well
checkbox.id = "mycheckbox";
and then to find it do a
if (document.getElementById("mycheckbox").checked == false)

Categories

Resources