editing value of inputfield using Javascript - javascript

So I have this code:
function resetAll(einde) {
if(einde !=1) {
if(beurt == 0) {
spelerbolletje.gewonnen += 1;
document.getElementById("bolletje").value = spelerbolletje.gewonnen;
} else {
spelerkruisje.gewonnen += 1;
document.getElementById("kruisje").value = spelerkruisje.gewonnen;
}
}
setVakjes();
resetVakjes();
}
somehow this sets the value for the value of the winner from 0 to NaN.
does someone know how to solve this?

What you do seems correct. I think the problem is that XX.gewonnen has not been initialized.
var a = {};
a.gewonnen += 1; // => gewonnen = NaN
So, ensure gewonnen is defined:
if(XX.gewonnen == undefined) XX.gewonnen = 0;
// rest of your code

Related

Unable to toggle div display using Javascript

I have written some vanilla JS in order to hide/display some divs, depending on the value of one of the fields in them.
My problem is that, while hiding them appropriately is working by default, trying to make them appear again, I am having issues as using getElementById is returning nulls.
I've googled and found numerous examples where similar code has worked and I cannot figure out why mine isn't actually working.
The JS I've written is below:
var hidden = false
document.addEventListener("keypress", function(event) {
if (event.key == '`') {
if (hidden == false) {
resultEntries = document.getElementsByClassName('result-row');
for (i = 0; i < resultEntries.length + 1; i++) {
var x = document.getElementById('root_cause_' + i)
if (x != null) {
var value = x.options[x.selectedIndex].value;
console.log('value' + value)
if (value == '') {
row = document.getElementById('line_' + i)
row.style.display = 'none';
}
}
}
hidden = true
} else {
resultEntries = document.getElementsByClassName('result-row');
for (i = 0; i < resultEntries.length + 1; i++) {
row = document.getElementById('line_' + i) // This is what is returning null
console.log(row)
row.style.display = 'block';
}
hidden = false
}
}
});
You overshoot your elements with the + 1 in the for loops
If you need this 1 based (not recommended) it is
for (let i = 1; i <= resultEntries.length; i++)
Also I think you can simplify this. Here is my guess without seeing the HTML
const resultEntries = document.querySelectorAll('.result-row');
document.addEventListener("keypress", function(event) {
if (event.key !== '`') return;
resultEntries.forEach((res, i) => {
let x = document.getElementById('root_cause_' + i)
if (x) {
let value = x.value;
console.log('value' + value)
document.getElementById('line_' + i).hidden = value === '';
}
})
});
Answering to save people from spending more time on this:
The issue was that my loop was starting from 0 while the elements were starting from line_1, meaning I was later on trying to alter the style of a null element.

JS function breaks upon entering no argument

Here is a simple function, that counts the price of engraving, based on the entered phrase length.
function engravePrice(phraseToEngrave) {
var pricePerWord = 11;
var wordsToEngrave = phraseToEngrave.split(' ');
if (phraseToEngrave.length === 0){
return 0;
} else if (phraseToEngrave.length > 0){
return wordsToEngrave.length * pricePerWord;
}
}
console.log(`Gift wrap and engraving price is: ${engravePrice('')} Q`);
It actually works pretty well:
engravePrice('Two words') //will return 22, as expected
engravePrice('') //will return 0, as expected
except for one specific situation:
engravePrice() //when it breaks, saying "cannot read property 'split' of undefined"
Is there a solution for that?
Thanks.
You need to check phraseToEngrave.for undefined, e.g.
function engravePrice(phraseToEngrave) {
if (!phraseToEngrave) return 0;
...
}
or in ES6, give it a default:
function engravePrice(phraseToEngrave = '') {
...
}
I would do it like this:
function engravePrice(phraseToEngrave) {
var phraseToEngrave = phraseToEngrave || '';
var pricePerWord = 11;
var wordsToEngrave = phraseToEngrave.split(' ');
if (phraseToEngrave.length === 0){
return 0;
} else if (phraseToEngrave.length > 0){
return wordsToEngrave.length * pricePerWord;
}
}
Which just converts it to an empty string if nothing is passed.

Javascript undefined error on last iteration

When looping through this string, the alert prints out test 4 times (correctly) but then also prints "undefined" at the end. How do I make it doesn't return undefined.
This returns - undefinedCAFE ::
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate += patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
The match function doesn't have a return statement, so it returns undefined. This means that
alert(match("abcdef","CAfe"));
will always show an alert of "undefined" at least once. To not show the alert, call the function without using alert:
match("abcdef","CAfe");
Alternatively you can make the function return something, such as stringConcatenate, which would be computed for no reason otherwise.
try this
alert(match("abcdef", "CAfe"));
function match(string, pattern) {
var patternUpperCase = pattern.toUpperCase();
var stringUpperCase = string.toUpperCase();
var stringConcatenate;
var answer;
var i = 0;
for (var i = 0; i < patternUpperCase.length; i++) {
if (patternUpperCase.charAt(i) != undefined) {
if (patternUpperCase.charAt(i) >= 'A' && patternUpperCase.charAt(i) <= 'Z') {
stringConcatenate = stringConcatenate + patternUpperCase.charAt(i);
alert("test");
}
}
}
return stringConcatenate;
}
Last "undefined" valie is result of your function:
alert(match("abcdef", "CAfe"));
http://jsfiddle.net/sava/Dw7jm/

innerHTML javascript dynamic

I am currently having some issues with the innerHTML function in a little javascript project. Essentially, I have a few HTML form checkboxes which change a number (that is displayed on the same page) depending on whether they are checked or not. The idea is very much like an IP address. The result is a number between 0 and 255.
What I want to do however is that whenever the user clicks on a checkbox, I need that number to change dynamically. Idea resembles the concept that is used when we write a question on this forum. As you type, the text below changes dynamilly to show exactly what is changed as it changes.
My code isn't working too well. Could you help me please? It keeps giving me the message "undefined" instead of the sum. Thanks for your help.
JavaScript
function displayOctets01(){
var octet01 = new Array(8);
octet01[0] = document.getElementById('octect0101');
octet01[1] = document.getElementById('octect0102');
octet01[2] = document.getElementById('octect0103');
octet01[3] = document.getElementById('octect0104');
octet01[4] = document.getElementById('octect0105');
octet01[5] = document.getElementById('octect0106');
octet01[6] = document.getElementById('octect0107');
octet01[7] = document.getElementById('octect0108');
var firstOctect;
if(octet01[0]==true){
firstOctect+=1;
}
else if(octet01[1]==true){
firstOctect+=2;
}
else if(octet01[2]==true){
firstOctect+=4;
}
else if(octet01[3]==true){
firstOctect+=8;
}
else if(octet01[4]==true){
firstOctect+=16;
}
else if(octet01[5]==true){
firstOctect+=32;
}
else if(octet01[6]==true){
firstOctect+=64;
}
else if(octet01[7]==true){
firstOctect+=128;
}
document.getElementById("octets01").innerHTML = firstOctect;
}
else if(octet01[7]==true){
firstOctect+=128;
}
document.getElementById("octets01").innerHTML = firstOctect;
}
I suspect that something might be wron with how I am handling the variables.
DEMO: http://jsfiddle.net/3TyV3/
The first problem is that the firstOctet variable isn't initialized. That needs to be set to 0 at the beginning of your function. Also, without knowing the purpose of your program, it seems that you don't want to be using else if - you need to check every checkbox. Also, you shouldn't be comparing the element with == true, you should check its checked property Also, your jsFiddle was set to run onLoad, so the function wasn't globally available. Finally, you didn't have an element with the id "octets01" to output to. Try this:
function displayOctets01() {
var octet01 = [],
firstOctect = 0;
octet01[0] = document.getElementById('octect0101');
octet01[1] = document.getElementById('octect0102');
octet01[2] = document.getElementById('octect0103');
octet01[3] = document.getElementById('octect0104');
octet01[4] = document.getElementById('octect0105');
octet01[5] = document.getElementById('octect0106');
octet01[6] = document.getElementById('octect0107');
octet01[7] = document.getElementById('octect0108');
if (octet01[0].checked === true) {
firstOctect += 1;
}
if (octet01[1].checked === true) {
firstOctect += 2;
}
if (octet01[2].checked === true) {
firstOctect += 4;
}
if (octet01[3].checked === true) {
firstOctect += 8;
}
if (octet01[4].checked === true) {
firstOctect += 16;
}
if (octet01[5].checked === true) {
firstOctect += 32;
}
if (octet01[6].checked === true) {
firstOctect += 64;
}
if (octet01[7].checked === true) {
firstOctect += 128;
}
document.getElementById("octets01").innerHTML = firstOctect;
}
DEMO: http://jsfiddle.net/3TyV3/2/
Although I won't lie, I'd reorganize some things. Here's how I would do it:
window.onload = function () {
var checkboxes = document.querySelectorAll('[name="featuresOctet01"]'),
i;
for (i = 0; i < checkboxes.length; i++) {
addEvent(checkboxes[i], "click", clickHandler);
}
};
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
function clickHandler() {
var firstOctect = 0,
checkboxes = document.querySelectorAll('[name="featuresOctet01"]'),
i, cur;
for (i = 0; i < checkboxes.length; i++) {
cur = checkboxes[i];
if (cur.checked) {
firstOctect += Math.pow(2, i);
}
}
document.getElementById("octets01").innerHTML = firstOctect;
}
DEMO: http://jsfiddle.net/3TyV3/3/
It uses unobtrusive JavaScript by binding the events in JavaScript, not the inline HTML. I did use the click event instead of change because old versions of IE has weird behavior for it with checkboxes/radio buttons. The addEvent function is just a simple function for binding events in new browsers as well as old IE.
It selects all elements with the name "featuresOctet01" and adds the event to each. Then, in the handler, it loops through each checkbox, sees if it's checked, and then adds a value based on 2^i.
References:
addEventListener: https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
document.querySelectorAll: https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
Math.pow: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/pow

How can i give a limit to an append function with javascript?

I have an append button which appends endlessly if you click it endlessly.
Lets say i want this button to do this 10 times.
Let me tell you in fantasy code :p what i was thinking so that i can learn from my mistakes; ( i know its wrong but hey im learning)
thismany = 1;
appendbutton.onClick = "thismany = +1";
if{ thismany = <9}
appendbutton.onClick = disabled
thanks in advance
(function(){
var count = 1;
document.getElementById("the_node_id").onclick = function(){
if(count > 10){
return;
}
do_stuff();
count ++;
};
})()
UPDATE:
var count = 1;
addEvent(append, "click", function(/* someargument */){
if(count > 10){
return;
}
// if you need arguments that are passed to the function,
// you can add them to the anonymous one and pass them
// to appendFunction
appendFunction(/* someargument */);
count++;
});
This is straight javascript. You might also consider looking into a framework such as jQuery to make it easier for you.
This assumes your HTML for the button has id="appendButton" as an attribute.
var count = 0;
document.getElementById("appendButton").onClick = function(e) {
if( count >= 10 ) {
return false;
}
else {
count ++;
document.getElementById("id_of_thing_you_append_to").innerHTML += "Whatever you're appending";
}
}
Using your variable names:
var thismany = 0;
appendbutton.onclick = function() {
if (thismany++ < 10) {
// append things
}
};
Variable encapsulated:
appendbutton.onclick = function() {
if (this.count == undefined) {
this.count = 0;
}
if (this.count++ < 10) {
// append things
}
};

Categories

Resources