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
Related
I've been looking at other questions trying to get my head around callbacks but I just can't make sense of it enough to use in my context. I'm writing a text based game which uses purely text input. When needed, I want the game to ask a question with a varying amount of answers and then wait until a valid response is given. Below is an example that doesn't work but explains what I'm trying to do. Can anyone provide me with any guidance? Thanks.
//main code
pEQUIP = ["foo", "foo", "foo"];
exItem = "ball";
function prompt(numPrompts, callback) {
//waits until user types a number <= numPrompts and presses enter, then returns the valid result entered
}
$('#gametext').append("<p>" + "What slot would you like to use to hold this item?" + "</p>");
//where a function would be stopping the code until a valid answer is given
if (prompt == "1") {
pEQUIP[0] = exItem;
} else if (prompt == "2") {
pEQUIP[1] = exItem;
} else if (prompt == "3") {
pEQUIP[2] = exItem;
}
//Just a quick n dirty way of testing it worked below:
$('#gametext').append("<p>" + pEQUIP[0] + pEQUIP[1] + pEQUIP[2] + "</p>");
//parses user info unsure if this could be used or would have to be copied
$(document).ready(function() {
$(document).keypress(function(key) {
if (key.which === 13 && $('#userinput').is(':focus')) {
var value = $('#userinput').val().toLowerCase();
$('#userinput').val("");
//playerInput(value); Is usually here, would lead to
//a switch which parses commands typed by the user.
//Unsure if it can be used for this problem as pausing
//the code I think would stop the switch?
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="gametext"></div>
<input id="userinput">
</body>
It appears as though you're thinking of functions incorrectly.
Functions are:
A series of steps that may return data when they're invoked. You
invoke a function by passing arguments to the function name, even if
the arguments are nothing () - a.e. alert(string) or myFunction()
Not comparable to anything but themselves. In your code you have prompt == "1" this isn't going to work. prompt is a function name and it isn't invoked so you are literally comparing the function itself to the string "1".
Able to return data when invoked. That data can be compared.
Note: Also, very importantly, prompt is the name of a default function(like alert or console) and you shouldn't overwrite it. It isn't considered a reserved keyword by the language but altering it will cause havok if any other library you're using, or any other programmer doesn't know it's been overwritten, and tries to invoke it.
prompt("this is a normal prompt");
Furthermore you have the document setup to check the value of the text box itself on keypress. You should probably change this to an event listener on the text box, but there isn't any reason to continuously loop a function beyond this while waiting for the box to match some predefined input.
The Flow is this:
type in the box
hit enter
check value
if value is 1 or 2 or 3 or any other acceptable answer do something
If that's all you need currently then you do not need to work so hard for the functionality when a single event listener could do the trick:
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
//do whatever
}
}
});
$("#input_box").on("keypress", function(e) {
if(e.keyCode === 13) {
let value = $("#input_box").val();
if(value === "1" || value === "2" || value === "3") {
console.log("accepted");
}
$("#input_box").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input_box">
I am using the following query to try to pull fields off of a User lookup on the Account. There is a field on the Account called Dedicated_Rep__c which is a user lookup. I am building my button off the opportunity, and I want to be able to pull the Opportunity's Account's Dedicated Rep's First Name, Last Name, and Email. Here's my code:
function getDedicatedAccountRep (oppId) {
var result = sforce.connection.query("select Account.Id, Account.Dedicated_CS_Rep__r.FirstName from Opportunity where Id = '" + oppId + "' ");
if(!result || result['size'] != 1) {
return null;
}
var DedRepRole = result.getArray('records')[0];
return DedRepRole.Account;
}
var dedicatedRep = getDedicatedAccountRep('{!Opportunity.Id}');
I am getting an error:
Cannot read property 'Dedicated_CS_Rep__c' of undefined
I am referencing the code later in the button and I am instantiating it by putting: dedicatedRep.Dedicated_CS_Rep__r.FirstName
Start with something like that (I prefer the Google Chrome's javascript console, you can open it with Ctrl+Shift+J; but feel free to use Firefox + Firebug or IE's developer tools...)
{!requireScript("/soap/ajax/29.0/connection.js")}
var result = sforce.connection.query("SELECT Account.Dedicated_CS_Rep__r.FirstName FROM Opportunity WHERE Id = '{!Opportunity.Id}'");
console.log(result);
debugger;
This will let you inspect the query result and play with the results. I think your problem is that the full expression can look like this:
result.records.Account.Dedicated_CS_Rep__r.FirstName
A lot can go wrong here. result should be OK and records should be always 1 row since we run it for one Opportunity (let's ignore crazy scenarios where somebody deleted the Opp between you navigating to the page and clicking the button... But still:
the Account can be blank (out of the box it's perfectly valid to have private Opportunities; maybe your organisation has marked the field as required).
And similarly in theory it's valid to have Account without the user.
So - you have 2 chances to hit null pointer exception:
Therefore properly protected code would have this orgy of null / undefined checks:
{!requireScript("/soap/ajax/29.0/connection.js")}
var result = sforce.connection.query("SELECT Account.Dedicated_CS_Rep__r.FirstName FROM Opportunity WHERE Id = '{!Opportunity.Id}'");
console.log(result);
if(result != null
&& result.records != null
&& result.records.Account != null
&& result.records.Account.Dedicated_CS_Rep__r != null){
alert(result.records.Account.Dedicated_CS_Rep__r);
// return result.records.Account.Dedicated_CS_Rep__r;
} else {
alert('Nope');
// return null;
}
I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.
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,
I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}