Why can't I seem to get this function to implement properly? - javascript

I've got some code in an external .js file that goes like this:
function creditConfirm (){
textboxVType = document.getElementById('textboxType');
textboxVName= document.getElementById('textboxName');
textboxVNumber = document.getElementById('textboxNumber');
textboxVCode = document.getElementById('textboxCode');
textboxVAmount = document.getElementById('textboxAmount');
if (textboxVType && textboxVName && textboxVNumber && textboxVCode && textboxVAmount =! " "){
alert("Accepted");
//All items made null
}
else{
alert("Try again");
}
}
Then I also have some HTML code that goes like this:
<p1> Credit card type: </p1>
<input type = "text" id "textboxType">
<h1> </h1>
<p1> Name: </p1>
<input type = "text" id "textboxName">
<h1> </h1>
<p1> Number: </p1>
<input type = "text" id "textboxNumber">
<h1> </h1>
<p1> Security code: </p1>
<input type = "text" id "textboxCode">
<h1> </h1>
<p1> Donation amount: </p1>
<input type = "text" id "textboxAmount">
<button onclick="creditConfirm()">Confirm</button>
What I'm trying to do is if all the items are filled out to print the first text and if one is missing to print the second text and allow them to try again. However, when I go onto the website either fill out all the boxes or leave one unfilled and click the confirm button nothing happens. I'm at a very basic level of JavaScript and our teacher seemingly refuses to teach us so I may have just missed a really obvious mistake, can anyone spot anything that would lead to this not working

You are not checking the elements for values in your if statement properly.
In an if statement that has && (or ||) conditions, each condition must be complete and stand on its own.
Additionally, to check a form field for data, you must check its value property.
You also had =! instead of !=.
if(textboxVType.value !="" &&
textboxVName.value != "" &&
textboxVNumber.value !="" &&
textboxVCode.value !="" &&
textboxVAmount.value != "") {}

you're checking if the dom elements are truthy (that will always be true as long as you declare them in your html) rather then check if they have a value set
change your if to
if (textboxVType.value && textboxVName.value && textboxVNumber.value
&& textboxVCode.value && textboxVAmount.value){
alert("Accepted");
}

1) Operator =! doesn't exist. != does.
2) textboxVType textboxVName textboxVNumber textboxVCode textboxVAmount =! " " are 4 distinct conditions. You can't factorise condition such way. Instead, you have to write that way textboxVType.value != " " && textboxVName.value != " " && textboxVNumber.value != " " && textboxVCode.value != " " && textboxVAmount.value != " " The .value is used to access the value of the DOM elements you got.
3) If you want to check if a textbox is empty rather use != "" instead of != " " (that will only check if the textbox contains only a space)

While I appreciate you're just starting with JS, and this might be slightly above your comfort zone, you might be interested in a shortcut to writing down and checking all the values of the input ids separately:
Here we pick up all the inputs using querySelectorAll, and then check the value of each one with some. If any of them are empty then Accepted is alerted, otherwise Try Again.
function creditConfirm() {
const inputs = document.querySelectorAll('input');
const emptyField = [...inputs].some(input => input.value === '');
if (!emptyField) {
alert("Accepted");
} else {
alert("Try again");
}
}
Short demo on JSFiddle.

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

How do I use two document.InnerHtml in javascript?

I am trying to write a simple script to allow for a second box to open at the bottom of the screen when the form returns false. What I really wanted, is the form to jump to the top of the form when it returns false, but this code below is my second choice. But when I try to add a document.getElementById("...").innerHTML = ... for the second one, the form returns true every time and this doesn't work.
This code works with only one:
if (firstname == null || firstname == "") {
document.getElementById("err_firstname").innerHTML = "<span class='errorbar'>*Required Field</span>";
return false;
}
And this code is what I am trying to accomplish but not working; I need to not allow just one html box to open, but both:
if (firstname == null || firstname == "") {
document.getElementById("err_firstname").innerHTML = "<span class='errorbar'>*Required Field</span>";
document.getElementById("err_allerrors").innerHTML = "<span class='errorbar'>*You Must Fill Out All Required Fields</span> ";
return false;
}

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);
}
}

How can i retrieve a fields name

I have a simple javascript function to check if a field is not empty:
function notEmpty( field , alert_text ){
if (field.val() === "" ||
field.val() === null ||
field.length === 0) {
if ( alert_text ){
alert ( 'Error: please enter some text - ' + alert_text );
} // end if
field.addClass( 'hightlight' );
field.focus();
return false;
} // end if
else {
field.removeClass('hightlight');
return true;
} // end else
I want to get the name of field to show in the alert without using the alert_text argument. I tried a whole load of things, with no luck, so I've left the function as is and I'm using the alert_text argument to pass the field name. All my form input tags are something like this:
<input type= "text"
name= "artist"
id= 'artistfield'
size= "60"
tabindex= "1" />
So they all have 'name' defined. There must be a way to get it into my alert box but I can't figure it out yet. I'm sure it's easy, I'm just very new to this. Thanks.
You can retrieve the name with this:
field_name = field.attr('name');
You can use jQuery's attr() method to get the name (and almost any other HTML attribute):
function notEmpty(field) {
if (field.val() === "" || field.val() === null || field.length === 0) {
if (field.attr('name')) {
alert('Error: please enter some text - ' + field.attr('name'));
}
field.addClass('hightlight');
field.focus();
return false;
} else {
field.removeClass('hightlight');
return true;
}
}
You can use:
field.attr('name')
To get the name attribute from the field. You could change name for id if you wanted the fields ID for example.
To get the name-attribute of an element you can use the attr-function. It can get the value of any attribute.
Eg: http://jsfiddle.net/mqchen/LjFdC/

Categories

Resources