https://jsfiddle.net/3vz45os8/7/
I've got this jsfiddle where I want to change the background color of the input text in a specific color if the word is well type and in another one if the word is not well type. It's currently doesn't work but I got no error in the console. If u guys could help me.
This is the js function, I log every step and didn't get an error:
function isCorrect() {
var test = document.getElementById('test').value;
if (test.value === "hello") {
test.classname = "correct"
return true;
} else {
test.classname = "incorrect"
return false;
}
}
var test = document.getElementById('test').value;
if (test.value === "hello") {
You're calling .value twice. Take it off the first line, because otherwise you'll be adding className (which should be camel-cased by the way) to a string value instead of the input element.
Here is the corrected code and a working copy:
function isCorrect() {
var test = document.getElementById('test');
if (test.value === "hello") {
test.className = "correct";
return true;
} else {
test.className = "incorrect";
return false;
}
}
It's correctly adding the class, but your CSS is being overridden so I just removed the default color for illustration.
You're doubling up on values:
var test = document.getElementById('test').value;
^^^^^^
if (test.value === "hello") {
^^^^^^
test is ALREADY the value of that input, which means it's a plain string. A string has no .value attribute, so you're doing undefined === "hello".
Also use className not classname
^ ^
You have a few errors:
The keyword is className not classname. Please change that.
You are already getting the .value. No need to call it again.
Corrected Code:
function isCorrect() {
var test = document.getElementById('test').value;
if (test === "hello") {
test.className = "correct"
//------------^
return true;
} else {
test.className = "incorrect"
//------------^
return false;
}
}
Related
Currently, my javascript is creating pages dynamically, so when the user clicks X, the new html code is generated for that option, if B then vice versa.
Although, I'm getting "undefined" errors. Even though I do check for the variables before they're passed into the function.
My current non-working prototype looks like this
var appName;
if(evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null){
appName = evt.target.getAttribute("appName");
}
Before that, I've tried using something which looks like this
var appName = evt.target.get("appName");
if (typeof appName != typeof undefined && appName !== false) {
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
That still returns undefined.
Lastly, I tried more or less the same approach but it still returns
Uncaught TypeError: Cannot read property 'getAttribute' of undefined
The code for the following looks like that :
var appName = '';
if(evt.target.hasAttribute("appName")){
appName = evt.target.getAttribute("appName");
}
else appName = 'boo';
How would I check if the attribute is actually set and I can proceed if not then I would like to pick alternate course for the code.
Thanks for your help and time spent.
evt.target is undefined, which means that you need to check for that before trying getAttribute(). This is one of the options you have, mostly depending on what your "alternate course for the code" is:
var appName;
if(evt && evt.target && ( evt.target.getAttribute("appName") != "" || evt.target.getAttribute("appName") != null )){
appName = evt.target.getAttribute("appName");
}
You could check if something is undefined by doing this (Copied from here):
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof always returns a string. Also, there's a difference between comparing with "double equals" and "triple equals" so you might want to check this out.
I have provided the sample snippet.
you have tried evt.target.getAttribute instead try evt.getAttribute
Try like this.
function findAttr(e){
if (!e.hasAttribute("appName")) {
console.log("No attribute");
} else {
console.log(e.getAttribute("appName"));
}
}
<div onclick="findAttr(this)">is attr present?</div>
<div onclick="findAttr(this)" appName="test">is attr present?</div>
If you have an alternate state for your element determined by the presence/absence of an attribute then use .toggleAttribute()
function editMode(e) {
const clicked = e.target;
const editor = document.querySelector('.editor');
if (clicked.matches('.mode')) {
clicked.classList.toggle('on');
clicked.classList.toggle('off');
editor.toggleAttribute('contenteditable');
if (clicked.matches('.off')) {
editor.focus();
} else {
editor.blur();
}
}
return false;
}
document.querySelector('.mode').onclick = editMode;
.editor {
min-height: 32px
}
.mode {
float: right;
display: inline-block;
width: 100px;
}
.on::before {
content: 'READ/WRITE';
}
.off::before {
content: 'READ ONLY';
}
<fieldset class='editor'></fieldset>
<button class='mode on'></button>
I am new to JavaScript and I have written the code below, which is supposed to be taking the input of a form field (in that case of the lastname) and in case it is empty, it will not allow me to be redirected to next page. However, it doesnt work.. Does anybody know why or how I could fix it? Thank you in advance!
window.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("form");
form.addEventListener("submit",
function(e) {
validate(e);
e.stopPropagation();
if (invalid == true) e.preventDefault();
},
false);
var invalid = false;
function validate(e) {
var lname = document.getElementById("lastName");
invalid = testField(lname);
return invalid;
}
function testField(field) {
if (field.value == undefined || field.value == " ")
invalid = true;
else
invalid = false;
return invalid;
}
}
}
This is wrong:
if (field.value == undefined || field.value == " ")
You're comparing the value to a string containing a single space. If the field is empty, it won't match this.
There's also no need to compare with undefined, the value is always defined.
So it should be:
if (field.value == "")
You might want to trim the field first, in case they just type a bunch of spaces:
if (field.value.trim() == "")
The main problem is making a comparison against ' ' space. That's not correct because you want to validate whether that value is empty.
So, you need to compare as follow: field.value.trim() === ""
Good, I think your code could be reformatted, for example you don't need to compare boolean values, they are already a boolean, so you can use them directly in your conditions, i.e:
if (invalid == true) //See? the invalid variable is a boolean.
So, use it as follow:
if (invalid)
Another potential code to be reformatted:
//Here you want to evaluate and assign a boolean, well you just have to assign the result of that condition.
function testField(field) {
if (field.value == undefined || field.value == " ")
invalid = true;
else
invalid = false;
return invalid;
}
Do the following:
function testField(field) {
return invalid = field.value == undefined || field.value == " ";
}
And finally, this code doesn't need that global variable invalid, so you can remove the invalid variable:
function(e) {
validate(e);
e.stopPropagation();
if (invalid == true) e.preventDefault();
}
Access that function as follow:
function(e) {
e.stopPropagation();
if (validate(e)) e.preventDefault();
}
Your code after be reformatted:
window.addEventListener("DOMContentLoaded", init, false);
function init() {
var form = document.querySelector("form");
form.addEventListener("submit",
function(e) {
e.stopPropagation();
if (validate(e)) e.preventDefault();
},
false);
function validate(e) {
var lname = document.getElementById("lastName");
return testField(lname);
}
function testField(field) {
return field.value === undefined || field.value.trim() === ""
}
}
See?, now your code is cleaner.
There are some pieces of your code to be reformatted, but this is a good start.
I can't seem to get my code to check which user role I've selected from the drop down. I don't often use for this so I'm kind of running into some trouble with it I think. Let me know if I'm missing something? I left the console.log()'s in but they haven't returned anything.
var userRole = "";
if ($('select[name=custom1]').find(':selected').val("") === "Healthcare Practitioner") {
return userRole = "SR-Practitioner";
console.log(userRole);
} else {
return userRole = "SR-Educator";
console.log(userRole);
};
A return statement is an exit point of a function. Everything after the return statement won't be executed. One exception is code that are wrapped in a try finally block. Therefore the console.log won't be executed.
Like #MDeSchaepmeester wrote: a .val(arg) call is a setter not a getter. Please read the documentation of .val(): http://api.jquery.com/val/
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
return "SR-Practitioner";
} else {
return "SR-Educator";
};
or
var userRole = '';
if ($('select[name=custom1]').find(':selected').val() === "Healthcare Practitioner") {
userRole = "SR-Practitioner";
} else {
userRole "SR-Educator";
};
console.log(userRole);
I am trying to make a function for java script that evaluates the text within a form and updates a label next to the form with either Valid entry or Invalid entry.
I have the code working here so far
function validateText(form) {
if(form.value == '') {
document.getElementById("reasonLabel").innerHTML = "Invalid Entry";
return false;
}
else{document.getElementById("reasonLabel").innerHTML = "Invalid Entry";}
var re = /^[\w ]+$/;
if(!re.test(form.value)) {
document.getElementById("reasonLabel").innerHTML = "Invalid Entry";
return false;
}
document.getElementById("reasonLabel").innerHTML = "Valid Entry";
return true; }
However I want to use this function and apply it to all forms inside my html each form has a corresponding label next to it.
My question is how do I pass in a label and edit its value without using .getElementByID()
Sorry if this is an obvious question I am very new to javascript.
If you have the label (which had to have been gotten using document.getElementById() or something similar in the first place), you can use it as a normal variable, like in the following:
function validateText(form, label) {
if(form.value == '') {
label.innerHTML = "Invalid Entry";
return false;
}
else{
label.innerHTML = "Invalid Entry";
}
var re = /^[\w ]+$/;
if(!re.test(form.value)) {
label.innerHTML = "Invalid Entry";
return false;
}
label.innerHTML = "Valid Entry";
return true;
}
Then label could be gotten by passing something like document.getElementById("reasonLabel") into the function.
You can pass the label's DOM object (returned from getElementByID) as a parameter, just like any other value.
I'm having problems with this function I've made, the first part is called fine but after the first if statements nothing else is being called. I've used JSfiddle, but it doesn't indentify a serious problem.
I usually work with PHP not JS so I'm wondering if there is something simple I am missing here?
function validatequestion(form){
var e = document.getElementById("chooseqtype");
var strQtype = e.options[e.selectedIndex].value;
if(strQtype == "default"){
alert("Please select a question type");
return false;
}
if(strQtype == "textquestion"){
fail = validatetextq(form.textquestiondesc.value)
if(fail == "") return true
else {
alert(fail);
return false;
}
}
if(strQtype == "videoquestion"){
fail = validatevideoq(form.videoquestiondesc.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
//everything above works, after this point nothing seems to get called
var a = document.getElementById("chooseatype");
var strAtype = a.options[a.selectedIndex].value;
if(strAtype == "textanswer"){
//get the value of the number of text answers select box
var t = document.getElementById("choosetextnumber");
//put the value in variable strQtype
var strTextno = t.options[t.selectedIndex].value;
if(strTextno == "2tanswers"){
fail = validatetexta1(form.textanswer1.value)
fail += validatetexta2(form.textanswer2.value)
if(fail == "") return true;
else {
alert(fail);
return false;
}
}
}
}
If strQtype can only be one of the 3 values you are testing for then there is no way you can ever get to the second part of your code because you always return from each of those if statements.
EDIT:
What you need to do is not return when fail == "". Since you're just returning true I assume you don't need to return a value, just verify that the validation was successful. What you should do then is only test for failure, e.g. if (! fail=="" ) (syntax is prob wrong, javascript is not my first lang.) and in that case do your alert.
Or you could always just write 3 different functions, one to test each menu item, which is what I would probably do.