I'm trying to call a function with onchange() in an input form.
When I check the console in Chrome, the code below returns:
ReferenceError: changingNow is not defined
In safari, it says:
ReferenceError: Can't find variable changingNow
Here's the code:
function changingNow() {
first_name=document.getElementById(first_name);
last_name=document.getElementById(last_name);
username=document.getElementById(username);
category=document.getElementById(category);
if ((first_name!=="")&&(last_name!=="")&&(username!=="")&&(category!="empty")) {
form1.process.disabled = false;
}
else {
form1.process.disabled = true;
}
document.getElementById('tweet').value = 'I just voted for '+first_name+' '+last_name+'('+username+')'+'in the '+category+' category!';
}
First Name<input type="text" name="first_name" id="first_name" class="first_name" maxlength="50" onchange="changingNow"/><br/>
Googling this seems to indicate that jQuery is responsible, but there's no jQuery on the page.
EDIT
Rob W is correct, I've already tried brackets, they're irrelevant in sorting this problem.
There are a lot of problems in your code. For starters, the lines where you get the values of your various text fields is incorrect:
first_name=document.getElementById(first_name);
getElementById expects a string. You aren't passing a string, you're passing an as-yet undefined variable named first_name. To make it a string, give some quotes! Second, you aren't using the var keyword, which affects the scope of the variable. Lastly, with those two errors corrected, you still aren't getting the value, you're getting the element -- getElementById gives you an HTMLElementObject. Further on, you try to treat this object as a string:
first_name!==""
As it stands, first_name will never equal an empty string because it is not a string, it is an object. Putting it all together, you want instead:
var first_name=document.getElementById('first_name').value;
This will give you the value of the text field with the id "first_name" as a string.
Further on, your if statement has way too many parenthesis!
if ((first_name!=="")&&(last_name!=="")&&(username!=="")&&(category!="empty"))
These parenthesis are not necessary, instead:
if (first_name !== "" && last_name !== "" && username !== "" && category!= "empty"){ }
// or my personal preference:
if (
first_name !== "" &&
last_name !== "" &&
username !== "" &&
category!= "empty"
){ }
Finally, I would suggest removing the inline onchange event and replacing it with a javascript assignment:
document.getElementById('first_name').onchange = changingNow;
This is just one way to apply an event, see this answer for more info on that.
Putting it all together:
var changingNow = function() {
var first_name = document.getElementById('first_name').value;
var last_name = document.getElementById('last_name').value;
var username = document.getElementById('username').value;
var category = document.getElementById('category').value;
var form1 = document.getElementById('form1');
if (
first_name !== "" &&
last_name !== "" &&
username !== "" &&
category!= "please choose a category"
){
// this line of code is not valid in regular JS...
//form1.process.disabled = false;
document.getElementById('tweet').value = 'I just voted for '+first_name+' '+last_name+' ('+username+')'+' in the '+category+' category!';
} else {
// this line of code is not valid in regular JS...
//form1.process.disabled = true;
document.getElementById('tweet').value = 'please complete the fields above!';
}
}
document.getElementById('first_name').onchange = changingNow;
document.getElementById('last_name').onchange = changingNow;
document.getElementById('username').onchange = changingNow;
document.getElementById('category').onchange = changingNow;
changingNow();
Try it out here: http://jsfiddle.net/yzbWr/
Documentation
document.getElementById on MDN - https://developer.mozilla.org/en/DOM/document.getElementById
addEventListener on MDN - https://developer.mozilla.org/en/DOM/element
Variable scope cheatsheet on MDN - https://developer.mozilla.org/en/JavaScript/Reference/Scope_Cheatsheet
It might be that you have function changingNow() defined AFTER you have inserted the <input> field, and because you don't execute it onchange but assign it to onchange (changingNow() vs changingNow), you end up assigining it an undefined
You could fix this by giving a global namespace to your app and then calling the method explicitly:
window.myApp = {};
window.myApp.changingNow = function(){
// your function code here
};
And then in your HTML:
<input type="text" ... onchange="window.myApp.changingNow">
Gentlemen (and ladies??) Our issue seems to have been solved. My issue was, pathetically, that <script type="text/javascript"> was omitting the 'text'.
Nevertheless, there are solutions. It seems the () are nessecary, but my thanks to Chris' excellent answer, and indeed his comments about getelementbyid are correct.
Yours etc,
Related
I'm learning how to program so bear with me. I pretty much need to verify if there are empty spaces in a form that needs to be filled out, I'm using javascript. I did the following but for some reason even if I fill out all the spaces it still tells me that there are empty spaces.
(This his how the HMTML for each id looks like)
<label for="txtNombre">Name</label>
<input type="text" id="txtName" placeholder="Name">
let inputName = document.querySelector('#txtName').value;
let inputLastName = document.querySelector('#txtLastName').value;
let inputPassword = document.querySelector('#txtPassword').value;
let inputConfirm = document.querySelector('#txtConfirm').value;
let inputDate = document.querySelector('#dDate').value;
function validateForm(){
let bError = false;
if(inputPassword === '' || inputConfirm === '' || inputName ==='' || inputLastName === '' || inputDate === ''){
bError = true;
showMessage(bError);
}else if (inputPassword === inputConfirm) {
inputPassword.classList.remove('borderError');
showMessage(bError);
} else{
inputPassword.classList.add('borderError');
bError = true;
showMessage2(bError);
}
}
function showMessage(pbError){
divMessage.innerHTML = '';
divMessage.classList.remove('error');
divMessage.classList.remove('correct');
let spanMessage = document.createElement('span');
let nodeMessage;
if(pbError === true){
divMessage.classList.add('error');
nodeMessage = document.createTextNode('Missing fields to be filled out');
}else{
divMessage.classList.add('correcto');
nodeMessage = document.createTextNode('Data saved');
}
spanMessage.appendChild(nodeMessage);
divMessage.appendChild(spanMessage);
divMessage.classList.remove('invisible');
}
Since your questions doesn't hold any of your html code, and since Im unsure if you javascript is the entire script, or if there is anything defined outside the scope of your functions, my answer is limited to the information you have provided.
First off, since you are a new developer. You should first of, learn
how to use the developer tools of the browser you are using (most
browsers have them). There should be a console there, which will log
all the errors that occurs in your javascript. This is the most
efficient way to debug your code.
As someone have commented on your question here, the most likely error, is that the variables you are trying validate as blank or not, are undefined variables. Thus, they will never match ""
You should refer to the value of the input fields before you check them.
Lets say you have a input field:
<input name="test" type="text" id="testinput" />
Then you define the variable that refers to the value of this input, and check its value:
var testInput = document.getElementById('testinput').value
if( testInput === "" ) //Do something
Note, there are several methods to refer to a DOM-element in javascript, getElementById is just one of them. You should do some research, and choose the solution that fits you best
assuming that you are storing the input value in those varialiables like inputPassword for example:
const inputPassword = document.getElementById('myInput').value
Your code should work as far as I can tell from what you have posted.
Hope it helps
I have a an onclick function, inside this function I want to create a condition for the way some elements are shown in the textarea. added this in the function:
bPlace = bookForm.txtPlace.value;
if (bPlace="null") {
bPlace="!."
}
bookForm.myText.value = bPlace
according to this condition when the value in txtPlace in myForm is not null it should show anything the user puts in. But when I test it, when I type something, instead of showing that, it still shows the (( !. )) in the textarea.
I should say I used "Undefined" instead of Null and still the same thing happened
Can you please tell me what am I doing wrong?
The problem is you are using assignment operator instead of comparision operator
The statement bPlace="null" will assign the string null to bPlace and will return it, which is a truthy value so the if block will always get executed.
bPlace = bookForm.txtPlace.value;
if (bPlace == "null") {
bPlace = "!."
}
bookForm.myText.value = bPlace
But since bPlace is a input value, I think what you are trying to do is if the input is left blank you want to put a default value in that case you can check
bPlace = bookForm.txtPlace.value;
if (!bPlace) {
bPlace = "!."
}
bookForm.myText.value = bPlace
Demo: Fiddle
Which can be further shorten to
bookForm.myText.value = bookForm.txtPlace.value || '!.';
Demo: Fiddle
I don't have much experience in JavaScript, so far I have this:
function loop() {
var authorDivs = document.getElementById('ctl00_MainContent_MCPObjectInfo_dvCreatorView').getElementsByTagName("div");
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (typeof divOfDiv.item(i) === 'undefined' || divOfDiv.item(i) === null) {
console.log("This is undefined or null");
}
else {
var realDivs = divOfDiv.item(i);
realDivs.item(i).textContent = "please work plz";
}
}
}
I get the following error from the console in FireFox: TypeError: realDivs is undefined on this line: realDivs.item(i).innerHTML = "please work plz";
Essentially what I have (in my mind) is a loop that goes through authorDivs and gets all of the divs within those divs and saves them in divOfDiv. I then check to see if the divs in divOfDiv are undefined or null, if they are not then those divs get saved in a variable realDivs which I then use to edit the innerHTML. That's what I'd ideally like to see happen, what is causing the error? What am I doing wrong?
Note: I do not have access to jQuery but only JavaScript.
Edit: I've added the changes suggested below and its fixed that -- thanks! But I'm now getting the following error: TypeError: realDivs.item is not a function
What is causing that? And on another note how do I know when I'm dealing with an array and when I'm dealing with an HTMLCollection? Do you just assume? I've never used a loosely typed language before so its new to me.
Well, you'll need to move that code inside the conditional block that is supposed to prevent it! Also, || "null" is not going to work as you expect, you'll need to check for || divOfDiv.item(i) === null explicitly.
So try
for (var i = 0; i < authorDivs.length; i++) {
var divOfDiv = authorDivs[i].getElementsByTagName("div");
if (divOfDiv.item(i) == null) {
console.log("This is undefined or null");
} else {
var realDivs = divOfDiv.item(i)
realDivs.item(i).innerHTML = "please work plz";
console.log(divOfDiv.item(i));
}
}
However, that still doesn't really work for two reasons:
The i index you use to access the i-th divOfDiv comes from the iteration over authorDivs - hardly what you want. Instead, use a second loop over all divOfDivs.
Your realDivs variable does hold a single <div>, which does not have an .item method. You'd just directly access its .innerHTML property.
So you should use
var authorDivs = document.getElementById('authorView').getElementsByTagName("div");
for (var i=0; i<authorDivs.length; i++) {
var divsOfDiv = authorDivs.item(i).getElementsByTagName("div");
for (var j=0; j<divsOfDiv.length; j++) {
var realDiv = divsOfDiv.item(j);
realDiv.innerHTML = "please work plz";
console.log(realDiv);
}
}
it will happen in case when your if (typeof divOfDiv.item(i) === 'undefined' || 'null') returns true. Then you never initialize realDivs (what would happen if condition was falsy). Later you try to call item function on that unitialized object
There are two problems in the code.
comparing DOM object with 'undefined' and null. If div tag is not available in authorDivs[i], it will return empty DOM array. So, comparision of empty DOM array with undefined and null is not good approach. We can use array length property for doing validation.
divOfDiv = authorDivs[i].getElementsByTagName("div");
if(divOfDiv.length > 0) { console statement}
As item(i) is already return single DOM element, item(i) of "realDivs" variable is not proper approach. In addition to this, innerHTML method needs to be used after validating whether realDivs contains DOM element. Please update the code as below.
var realDivs = divOfDiv.item(i);
realDivs ? (realDivs.innerHTML = "please work plz"): null;
Note : item(i) will return null if DOM is not available.
I've written a bit of JavaScript that reads the referring URL of a page and loops through an object to check for strings such as "google", "msn", "bing" etc. The resulting value is stored in a variable which is then passed to a server. Now this all works perfectly but my question is around detecting traffic directly to a site (i.e. people typing the URL in the address bar). How can I detect this?
I was thinking, that I could do something like:
var refURL = document.referrer;
var serverVar = "";
if (refURL === "") {
serverVar = 'direct traffic';
}
Should I be checking for "" (i.e. blank) or should I be checking if refURL is null?
If you dont want to do the way you are comparing now as in your code, You could use:
//check for blank, null or undefined
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
var refURL = document.referrer;
var serverVar = "";
if (isBlank(refURL)) {
serverVar = 'direct traffic';
}
Hope it helps
Just use if(!document.referrer) {}
All I want to be able to do is validate an email every time the user enters a new character into the input field. When the input field is empty, it shouldn't show anything, but when it contains letters, it should show where the invalid characters are.
My code works but doesn't show nothing when the input field is empty because it uses the nested 'else' instead of the one it should use. anyone help? thanks in advance. andyy
var tick = "<img src='images/tick.png' width='20' height='20'/>";
var cross = "<img src='images/cross.png' width='20' height='20'/>";
var email_element = document.contact_form.email_field.value;
function validate_email(id) {
if ( email_element != '' ) {
var letters = /^[A-Za-z]+$/;
if ( document.contact_form.email_field.value.match(letters) )
{
document.getElementById(id).innerHTML = tick;
valid = true;
} else {
document.getElementById(id).innerHTML = cross;
valid = false;
}
} else {
document.getElementById(id).innerHTML = '';
}
return valid;
}
The problem is most likely this line:
var email_element = document.contact_form.email_field.value;
You are assigning a global variable equal to the value of the email field, and then never updating that variable again. This does not create an "active" link to the current value of the field, it just stores the value as it was when that line was executed. Which in turn means that the first if statement in your function, if ( email_element != '' ), is evaluating a non-current value of the email field.
Move that line to be the first thing inside your function and then every time the function runs you'll get the latest (current) value of that field.
EDIT: Also, you are not assigning a value to valid in the non-nested else. You should declare valid as a local variable in the function and be sure to set it appropriately in every if and else branch (or default it to false when you declare it). As thomasrutter
said you are not currently declaring valid with the var statement in your function, which means it will be created as a global variable, which in turn means that when you don't give it a value in your non-nested else your function will return whatever value valid already had from the previous call. (And really, based on the code you've posted, you don't need the valid variable at all: you could just say return true; or return false; directly inside each branch of your if/else structure.)
Try replacing the expression email_element != '' with document.contact_form.email_field.value != '' as I suspect email_element is a reference to an element and will never be equal to ''. Better yet, create a local variable email_value and assign it the value of document.contact_form.email_field.value and use it in both places as in,
function validate_email(id) {
var email_value = document.contact_form.email_field.value;
if ( email_value != '' ) {
var letters = /^[A-Za-z]+$/;
if ( email_value.match(letters) ) {
document.getElementById(id).innerHTML = tick;
valid = true;
}
else {
document.getElementById(id).innerHTML = cross;
valid = false;
}
}
else {
document.getElementById(id).innerHTML = '';
}
return valid;
}
When setting email_element, you are getting the value once, by copy, because it's a string. So if when the page loads that field is blank, email_element is now set to '' and remains set to it until you set it again.
Tags are set by reference, so what you probably intended is:
var email_element = document.contact_form.email_field;
. . .
if(email_element.value != '')