why these two functions don't want to run? [duplicate] - javascript

This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 9 years ago.
I really don't know why these two functions - leave() & do() - don't run !
function leave()
{
var x = document.getElementById("x");
if(x.value == "")
{
alert("please enter your name");
x.focus();
}
}
function do()
{
var y = document.getElementById("y");
if (y.value = "enter your name here")
{
alert("enter your last name");
y.focus();
y.select();
}
}
here is my code: http://jsfiddle.net/BsHa2
thanks in advance

you have 3 problems:
1- which is in your jsfiddle options you have chosen to wrap all your code in the onLoad, so the functions are not in the global context, you can fix it as I have in the code below.
2- this line would set the value to the value of y input:
if (y.value = "enter your name here")
change it to
if (y.value == "enter your name here")
3- the other probelm is do is a reserved word, DO NOT USE reserved word, although it would do what you want in some browsers.
window.leave = function leave()
{
var x = document.getElementById("x");
if(x.value == "")
{
alert("please enter your name");
x.focus();
}
}
window.check = function check()
{
var y = document.getElementById("y");
if (y.value = "enter your name here")
{
alert("enter your last name");
y.focus();
y.select();
}
}

First do is a keyword so you can't use it as a method name - rename it to something like check
Second for inline event hadndlers the methods must be in global scope - Select body/head in the second dropdown in left panel in the fiddle
Demo: Fiddle

do is a reserved keyword. You can't use it as function name. Rename it to something else.
Secondly, inline event handlers must be defined in global scope. In your fiddle you have to select Wrap in head option
Third, = is assignment operator, to compare either use == and ===, error in line (y.value = "enter your name here")
Use
function do1()
DEMO

do is a reserved keyword. You can't use it as function name.
Also, you have a mistake here:
if (y.value = "enter your name here")
you need to check for equality:
if (y.value === "enter your name here")
As an aside, you should really consider giving your variables meaningful names and using unobtrusive event handlers:
<form id="myForm">
<label for="firstName">First Name:</label>
<input type="text" name="input" id="firstName" size="20">
<br/>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" size="20" value="enter your name here">
<input type="button" id="check" value="Check!">
</form>
var firstName = document.getElementById("firstName"),
lastName = document.getElementById("lastName"),
checkButton = document.getElementById("check");
firstName.onblur = function(){
if (this.value === ""){
alert("please enter your name");
this.focus();
}
}
check.onclick = function(e){
e.preventDefault();
if (lastName.value === "enter your name here") {
alert("enter your last name");
lastName.focus();
}
}
fiddle

Related

Trying to get user input to print in a P element

I would like to be able to take user input of a first and last name and upon clicking a submit button update a P element with that first and last name. almost like "Hello firstname lastname!"
The code I've provided is what my click function currently looks like.
function newName(){
var Name = input.value;
if (Name==""){
document.getElementById("hello").innerHTML="Hello" + Name;
}
};
You need to use the trim() to remove blank spaces and then check the condition.
var firstName = document.querySelector('#firstName');
var lastName = document.querySelector('#lastName');
function updateName() {
if (firstName.value.trim() && lastName.value.trim()) {
document.getElementById("hello").textContent = `Hello ${firstName.value} ${lastName.value}`;
}
};
<input type="text" placeholder="Firstname" id="firstName" />
<input type="text" placeholder="Firstname" id="lastName" />
<button onclick="updateName()">Click</button>
<p id="hello">
</p>
function getName(){
let name = input.value;
if (name != ""){
document.getElementById("name").textContent = Hi ${name};
}
}
This would be the most concise way to do it. Since this is simple test function.
function newName(){
if(input.value !== undefined || ""){
document.getElementById("hello").innerHTML= 'Hello '+ input.value }
};
Your code should look like below. JS Fiddle here for quick reference: https://jsfiddle.net/sagarag05/5nteLzm6/3/
function newName(){
let fullName = input.value;
if (fullName != ""){
document.getElementById("fullName2").textContent = `Hello ${name}`;
}
}

Form Validation Vanilla JS

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.
What I Want to Do:
(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.
(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.
What I Have Done
(1) Created a mini version of the form with two inputs:
One that takes a first name, a space and a last name
One that takes a phone number set up the following way xxx xxx xxx
(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.
Where I am Stuck:
I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.
What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.
function checkForm()
{
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
function checkFirstName()
{
if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
console.log("Put a first Name and Last Name");
}
else
{
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber()
{
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
{
console.log("Please Put in a proper phone number");
}
else
{
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
};
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
See below code.
It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.
function checkForm() {
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var phoneCanSubmit, nameCanSubmit = false;
function checkFirstName() {
if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
nameCanSubmit = false;
console.log("Put a first Name and Last Name");
} else {
nameCanSubmit = true;
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber() {
if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
phoneCanSubmit = false;
console.log("Please Put in a proper phone number");
} else {
phoneCanSubmit = true;
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
if (nameCanSubmit && phoneCanSubmit) {
document.getElementById("myButton").disabled = false;
} else {
document.getElementById("myButton").disabled = true;
}
};
<form>
First Name:
<input type="text" id="name" onblur="checkForm()" />
<label id="nameErrorPrompt"></label>
<br />Phone Number:
<input type="text" id="phone" onblur="checkForm()" />
<label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.
window.addEventListener('load', function(e) {
var nameInput = document.getElementById('name');
var phoneInput = document.getElementById('phone');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(e) {
e.preventDefault(); //Stop the page from refreshing
getNextPage('Next page shown!!');
}, false);
nameInput.addEventListener('blur', function(e) {
checkName(this.value);
}, false);
phoneInput.addEventListener('blur', function(e) {
//Uncomment below to make this responsible only for checking the phone input
//checkPhoneNumber(this.value);
/*You could do away with diasbling and check the form
on submit, but if you want to keep the disable logic
check the whole form on the blur of the last item*/
checkForm();
}, false);
}, false);
function getNextPage(foo) {
console.log('Callback fired: ', foo);
//Do something here
}
function checkPhoneNumber(phone) {
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
console.log("Please Put in a proper phone number");
return 0;
}
else {
console.log("Thank you name entered");
return 1;
}
};
//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
console.log("Put a first Name and Last Name");
return 0;
}
else {
console.log("Thank You phone entered");
return 1;
}
};
function checkForm() {
var validCount = 0;
fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
var phoneNum = document.getElementById('phone').value;
var name = document.getElementById('name').value;
var myButton = document.getElementById('myButton');
validCount += checkPhoneNumber(phoneNum);
validCount += checkName(name);
console.log(validCount + ' of ' + fieldCount + ' fields are valid');
if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs
myButton.disabled = false;
}
else {
myButton.disabled = true;
}
}
HTML
<form>
First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
How about you start by making the onblur for each input return a boolean indicating if the field is valid.
Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.
If you really want the button to enable you can use the same pattern, but do
document.getElementById("myButton").disabled = !canSubmit;
and you will always want to call checkForm on field blur like you are now.
Also note you aren't scoping canSubmit locally right now.

Issue with Java script / Jquery validation?

I have one select box and one text box are there. I need to the validation like if both are selected I need alert like "Either select a name or pick the name", If I did not select both i need alert like "Please select a name or pick the name", If I select one of them I need alert like "Thank you for selecting the name". I did it by java script but I did not get the result. Can it be done by using java script / Jquery? Any suggestions
<body>
pick name:
<select id="ddlView">
<option value="0">Select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</br>
select name:
<input type= "text" name="raju" id="raju"></input>
<input type="button" onclick="Validate()" value="select" />
<script type="text/javascript">
function Validate()
{
var name = document.getElementById("raju");
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0 && (name==null || name== ' '))
{
alert("Please select a name or pick the name");
}
else if( (!(strUser==0)) &&(! (name==null || name== ' ')))
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
</script>
</body>
Here is your same validation using JQuery as you also mentioned:
function Validate()
{
var name = $("#raju").val();
var selected_name = $('#ddlView :selected').val();
if(selected_name == 0 && name == "")
{
alert("Please select a name or pick the name");
}
else if( !(selected_name == 0) && name != "")
{
alert("Either select a name or pick the name");
}
else
{
alert("Thank you for selecting the name");
}
}
Fiddle
Your problem is that you get the input, not the value.
Replace var name = document.getElementById("raju"); with var name = document.getElementById("raju").value;
Also, you compare the name with null and blank space. You must compare it with empty string. (name == '')
When you saw on my Jsfiddle code, I don't use oonclick attribute but a event listener on javascript (realy better for your html)..
document.getElementById("myBtn").onclick= function ()
One second poitn you have forget tu retrieve .value of you name input (so already return [HTML DOM object] and not null or a value.
var name = document.getElementById("raju").value;
Since your post was in pure JavaScript, I've decided to answer accordingly. As mentioned, you shouldn't check an empty string for " " but rather '' or "". Furthermore, you shouldn't even need to do that, since you can simply check if (str) { // string exists }. For your name variable, you're referring to an HTML element and not it's string value. So, all in all (a few errors), nothing majorly wrong here.
I've abstracted this process a tiny bit to give you an idea of how to validate many similar fields without a whole lot of repetitive code.
Note: You should find a way to replace your inline event handlers with unobtrusive handlers. Example:
document.getElementById('someButton').onclick = Validate;
That being said, here's a few suggestions:
var emptyString = function(str) {
if (str) {
return false;
}
return true;
};
var emptySelect = function(sel) {
if (parseInt(sel) !== 0) {
return false;
}
return true;
};
function Validate() {
var name = document.getElementById("raju").value;
var e = document.getElementById("ddlView");
var strUser = e.options[e.selectedIndex].value;
switch (true) {
case (!emptySelect(strUser) && !emptyString(name)):
alert('Either select a name or pick a name.');
break;
case (emptySelect(strUser) && emptyString(name)):
alert('Please select a name or pick a name.');
break;
default:
// Possibly some default validation
alert('Thanks for picking a name');
break;
}
}

JavaScript no response with validation

I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
Right after this post I am going to break it all down and start smaller. But in the meantime I figured another set of eyes couldn't hurt and it is very possible I am doing something horribly wrong.
HTML:
<form name="form" action="index.html" onsubmit="return construct();" method="post">
<label>Your Name:<span class="req">*</span> </label>
<input type="text" name="name" /><br />
<label>Company Name:<span class="req">*</span> </label>
<input type="text" name="companyName" /><br />
<label>Phone Number:</label>
<input type="text" name="phone" /><br />
<label>Email Address:<span class="req">*</span></label>
<input type="text" name="email" /><br />
<label>Best Time to be Contacted:</label>
<input type="text" name="TimeForContact" /><br />
<label>Availability for Presenting:</label>
<input type="text" name="aval" /><br />
<label>Message:</label>
<textarea name="message" ROWS="3" COLS="30"></textarea>
<label>First Time Presenting for AGC?:<span class="req">*</span></label>
<input type="radio" name="firstTime" value="Yes" id="yes" /><span class="small">Yes</span>
<input type="radio" name="firstTime" value="No" id="no"/><span class="small">No</span><br /><br />
<input type="submit" name="submit" value="Sign-Up" />
</form>
JavaScript:
function construct() {
var name = document.forms["form"]["name"].value;
var companyName = document.forms["form"]["companyName"].value;
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
if (validateExistence(name) == false || validateExistence(companyName) == false)
return false;
if (radioCheck == false)
return false;
if (phoneValidate(phone) == false)
return false;
if (checkValidForOthers(TimeForC) == false || checkValidForOthers(availability) == false)
return false;
if (emailCheck(email) == false)
return false;
}
function validateExistence(name) {
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you."); return false;
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function phoneValidate(phone) {
if (phone.length > 12 || phone == "" || !isNaN(phone))
alert("Please enter a valid phone number."); return false;
}
function checkValidForOthers(name) {
if (name.length > 40)
alert(name + " is too long for our form, please abbreviate."); return false;
}
function messageCheck(message) {
var currentLength = name.length;
var over = 0;
over = currentLength - 200;
if (name.length > 200)
alert(name + " is too long for our form, please abbreviate. You are " + over + " characters over allowed amount"); return false;
}
function radioCheck() {
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false)
return false;
}
function emailCheck(email) {
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
}
Am I calling my functions incorrectly? I honestly am not sure where I am going wrong.
I don't understand how to debug my code... I am using chrome and I am not receiving any errors in the console. Is there a way to set breakpoints to step through the javascript?
I realize i just threw a lot of code up there so thanks in advance for sifting through it.
Here is mistake:
Replace var email = document.forms["forms"]["email"].value;
by var email = document.forms["form"]["email"].value;
There are lot of places in your js :
var email = document.forms["forms"]["email"].value;
var phone = document.forms["forms"]["phone"].value;
var TimeForC = document.forms["forms"]["TimeForContact"].value;
var availability = document.forms["forms"]["aval"].value;
where you mistyped form as forms.
Is there a way to set breakpoints to step through the javascript?
Yes there is a way to set breakpoints:
Refer following links in order to know the method to set break-point in debugger console in Chrome:
LINK 1
LINK 2
The following should fix the immediate problem:
function construct(form) {
var
name = form["name"].value,
companyName = form["companyName"].value,
email = form["email"].value,
phone = form["phone"].value,
TimeForC = form["TimeForContact"].value,
availability = form["aval"].value
;
if (!validateExistence(name) || !validateExistence(companyName)) {
return false;
}
else if (!radioCheck) {
return false;
}
else if (phoneValidate(phone) == false) {
return false;
}
else if (!checkValidForOthers(TimeForC) || !checkValidForOthers(availability)) {
return false;
}
else if (emailCheck(email) == false) {
return false;
}
}
You had a typo in the form document.forms["forms"], where 'forms' doesn't exist. Instead of always traversing objects to get to your form, you can use this to pass the current element into your function.
<form action="index.html" onsubmit="return construct(this);" method="post">
If you're starting out it's also a good idea to make sure you set all your braces (i.e. curly brackets) as this will help you avoid getting confused with regards to alignment and brace matching.
Your first problem is the forms where you meant form. See here
But you have other problems with your validation code, for example:
if (name == null || name == ' ')
Here you are checking if name is null or name is a single space. I assume you wanted to check if the field is blank, but a completely empty string will evaluate as false in your condition, as will two spaces. What you probably want to do is something like this:
if (!name) {
// tell the user they need to enter a value
}
Conveniently (or sometimes not), Javascript interprets null, an empty string, or a string full of white space as false, so this should cover you.
You also have a whole host of other problems, see this:
http://jsfiddle.net/FCwYW/2/
Most of the problems have been pointed out by others.
You need to use braces {} when you have more than one line after an
if statement.
You need to return true when you pass you validation
tests or Javascript will interpret the lack of a return value as false.
Your radioCheck will only pass if both radio buttons are checked.
You where checking that your phone number was NOT NaN (i.e. it is a number) and returning false if it was.
I would suggest learning some new debug skills. There are ways to break down a problem like this that will quickly isolate your problem:
Commenting out code and enabling parts bit by bit
Using a debugger such as Firebug
Using console.log() or alert() calls
Reviewing your code line-by-line and thinking about what it is supposed to do
In your case, I would have first seen if name got a value with a console.log(name) statement, and then moved forward from there. You would immediately see that name does not get a value. This will lead to the discovery that you have a typo ("forms" instead of "form").
Some other errors in your code:
You are returning false outside of your if statement in validateExistence():
if (name == null || name == ' ')
alert("You must enter a " + name + " to submit! Thank you.");
return false;
In this case, you do not have brackets {} around your statement. It looks like return false is in the if(){}, but it is not. Every call to this code will return false. Not using brackets works with a single call, but I don't recommend it, because it leads to issues like this when you add additional code.
In the same code, you are using name as the field name when it is really the value of the field:
alert("You must enter a " + name + " to submit! Thank you."); return false;
You really want to pass the field name separately:
function validateExistence(name, field) {
if (name == null || name == ' ') {
alert("You must enter a " + field + " to submit! Thank you.");
return false;
} else if (name.length > 40)
alert(field + "value is too long for our form, please abbreviate.");
return false;
}
}
You are not calling radioCheck() because you are missing parentheses:
if (radioCheck == false)
In radioCheck(), you are using || instead of &&. Because at least 1 will always be unchecked by definition, you will always fail this check:
if (document.getElementById("yes").checked == false || document.getElementById("no").checked == false) return false;
And more...
My suggestion is to enable one check at a time, test it, and once it works as expected, move on to the next. Trying to debug all at once is very difficult.
replace var email = document.forms["forms"]["email"].value;
by
var email = document.forms["form"]["email"].value;
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var data; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(data)))
{
alert("data "+data);
}
else
{
alert("data is "+data);
}
}

Wrapper Function not working properly (Javascript)

I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/

Categories

Resources