Passing an id through a function parameter - javascript

Trying to get a value of a textbox by passing the ID into a function parameter. Should be easy but can't wrap my head around it.
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
Error Message
Error: Unable to get property 'value' of undefined or null reference

Your ID is 19, but you're passing numberbox19 to the Javascript function. There are also several syntax errors.
Try:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
And Javascript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
The good thing here is, if you ever decide to change the ID for any reason, you only have to change it in one place instead of two.

the id of your input is "19" not "numberbox19"

Related

Trying to clear an error prompt using JQuery

I am trying to clear an error icon on keydown.
** EDIT - adding the HTML **
<input class="validate" type="text" data-type="string" id="address" />
<input class="validate" type="text" data-type="number" id="zip" />
** END EDIT - Unsure if this will help shed some light **
Currently, the error displays using this function:
function validateFields(){
$(".validate").blur(function(){
var status = "";
var label = this.id;
var value = this.value;
if(value != ""){
status = "good";
console.log("status " + status);
}
else{
status = "error";
console.log("status " + status);
}
if(status == "good"){
label.html(label.html()+' ✅');
}
if(status == "error"){
label.html(label.html()+' ❌');
}
});
}
If status equals Error, show the error icon.
So now, I want to clear the error when the user keydowns. Here is my attempt:
function clearError(){
$(".validate").keydown(function(){
var datatype = $(this).data("type");
var label = this.id;
label.html(label.html()+' ');
});
}
Obviously, I am not having much success clearing the error using the above keydown function.
How can I make this work?
The label business with trying to keep the text inside is not very intuitive, so I added span to your label so you remove and add error symbols from the span in your functions. Additionally, you had some unnecessary code that could be removed in both functions. For example, your if statements checking status were unnecessary since you already checked if the value was empty (where you set the status), therefore you could move that code into the if statement checking for empty values.
We set each corresponding span's id to the id of the input with "Span" id="testSpan", so it can be easily accessible by the JS functions. Remember inside jQuery functions this always refers to the non-jQuery object, so you can use the JS vanilla methods on it.
This is what I could come up with:
$(".validate").blur(function () {
var id = this.id; // get id
if (this.value != "") { // check if input is empty
document.getElementById(id + "Span").innerHTML = '✅'; //set ok symbol
console.log("good");
} else {
document.getElementById(id + "Span").innerHTML = '❌'; // set error symbol
console.log("error empty text");
}
});
$(".validate").keydown(function () {
// if value is empty set error symbol, otherwise nothing (keep ok symbol)
if (this.value === "") document.getElementById(this.id + "Span").textContent = "";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="test">test<span id="testSpan"></span></label>
<input id="test" class="validate">
<label for="test2">test<span id="test2Span"></span></label>
<input id="test2" class="validate">

Not working, Javascript validating text input before button click

The code is suppose to validate an input and then execute a function when a button is clicked, but it is not working and the console does not suggest why. The only difference is that when you take away toString() on input it says it is not a function.
This is my first big project at university and not really sure which part is wrong?
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
const trimmed = input.toString().trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}
Function to be executed
function addRow() {
something...
}
validating if this function is true then execute this function.
function validate(){
if(check()){
addRow();
}
}
document.getElementById('input').addEventListener('input', check);
document.getElementById('btn').addEventListener('click', validate);
Html
<input type="text" id="input" class="input" autofocus autocomplete="off" placeholder="Add items in your list..">
<button id='btn' class="add">+</button>
Although the input variable is not declared in your code, I assume that it is supposed to represent the <input type="text"> element.
With the validation step you should validate the value of the input, not the input itself.
But your logic is still missing something. The else statement will never be reached. If the value is empty then the state will be set to '' and the function is stopped. If there is a value, and it has been trimmed, then you're always left with a string with a value in it and there for your value is truthy. So the else would not make without an if statement which would allow the value to be false when the validation is incorrect.
function check(evt){
const value = input.value;
if (!value) {
input.dataset.state = ''
return
}
// Trim the value.
const trimmed = value.trim();
if (trimmed) {
input.dataset.state = 'valid'
} else {
input.dataset.state = 'invalid'
}
}

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