Here http://jsfiddle.net/SW5NH/5/ I created some automatically generated table (DOM + JavaScript).
I want to compare whether checkbox's Input1[z] value (true/false) is equal to Input2's[z] value.
If they are not equal value[z] should change.
Tried in several ways (below the table are some test results), but can not achieve it.
I would appreciate for any help/comments.
function valCheck() {
for (var y2 = 0; y2 < empl.length; y2++) {
var Id1 = 'Option1'+y2+'';
var Id2 = 'Option2'+y2;
var input1 = document.getElementById(Id1).checked;
var input2 = document.getElementById(Id2).checked;
var value = 'Value'+y2+'';
var valEntry = document.getElementById(value);
var debt = (input1==input2) ? 'no debt' : 'debt';
document.getElementById('tabinfo').innerHTML = Id1+input1+ ' ' +Id2+input2+ ' ' +(input1&&input2)+value+valEntry+ ' ' + debt;
document.getElementById(value).createTextNode(debt);
}
}
don't work
UPDATE: Solved. Solution in my last post.
Your comparsion is right but you should be using 'change' eventListener like this
document.addEventListener('change', valCheck, false);
Check this JSFiddle and share your suggestion.
Also use === instead of ==
Here what you need, DEMO HERE
function checkValue() {
var a = document.getElementById('a');
var b = document.getElementById('b');
if (a.checked != b.checked) {
document.getElementById('lab').innerHTML="Not equal";
}
else
document.getElementById('lab').innerHTML = "equal";
}
Thank You all.
My table works now and it rocks already :) It is still in progress, but there are waiting only some cosmetic amendments.
Here is the actual JSFidle http://jsfiddle.net/5tcPz/1
You are welcome to use it if you find it usefull.
My mistake was - document.createTextNode element can't have an ID, so the value of Element value[z] was null.
I solved it in such way:
var fifthCell = document.createElement('DIV');
fifthCell.id = "Value" + y + '';
fifthCellText = document.createTextNode('no debt');
fifthCell.appendChild(fifthCellText);
UPDATE.
http://jsfiddle.net/5dmrW finished table!!! This was my first JavaScript project after codeacademy and a lot of JS online tutorials :) It's a very simple, but I'm proud of it. Regards
Related
BACKGROUND
I am creating a dynamic, multiple-choice quiz written in JavaScript as a culmination to this course. I am following the parasitic inheritance pattern outlined in a follow-up post by the author of the course, and am having trouble completing the project.
PROBLEM
If you refer to this JSBIN, you will see that I have created functions to loadQuestion, displayQuestion, getUserAnswer, getCorrectAnswer, and checkAnswer. checkAnswer is where I am stuck. In this function id like to check if the returned value of getUserAnswer is equal to the returned value of getCorrectAnswer on the currently loaded question, and if so, just log a string to the console for now.
Question.prototype.displayQuestion = function(){
var questionToDisplay = '<div class="question">' + this.question + '</div><ul>';
choiceCounter = 0;
var quizDiv = document.getElementById('quiz');
this.choices.forEach(function(eachChoice){
questionToDisplay += '<li><input type="radio" name="choice" value="' + choiceCounter + '">' + eachChoice + '</li>';
choiceCounter++;
});
questionToDisplay += '</ul>';
quizDiv.innerHTML = questionToDisplay;
};
var i = 0;
Question.prototype.loadQuestion = function(){
if(i < allQuestions.length){
var quest = new MultipleChoiceQuestion(allQuestions[i].question, allQuestions[i].choices, allQuestions[i].correctAnswer);
quest.displayQuestion();
i++;
return quest.getCorrectAnswer();
}
};
Question.prototype.getCorrectAnswer = function() {
return this.correctAnswer;
};
Question.prototype.getUserAnswer = function(){
var radio = document.getElementsByName('choice');
for(var i=0; i < radio.length; i++){
if(radio[i].checked){
return radio[i].value;
}
}
};
//Non-functioning code, this is what im trying to figure out.
/*Question.prototype.checkAnswer = function(){
if(Question.prototype.loadQuestion() == Question.prototype.getUserAnswer()){
console.log('it worked!');
} else {
console.log('keep trying!');
}
};*/
//Load the first question
Question.prototype.loadQuestion();
var button = document.getElementById('next');
button.onclick = function(){
//get the user-selected radio input.
Question.prototype.getUserAnswer();
//Question.prototype.checkAnswer();
//load next question
Question.prototype.loadQuestion();
};
I am new to javascript (and programming) and suspect that the problem lies in some misunderstanding of how return values work?
Thank you!
Found the problem.
You're not adding 1 to the value of radio[i]. Remember that this is an array, and so all the indices will be decreased by 1 because we start counting from 0.
Here is your function:
Question.prototype.getUserAnswer = function(){
var radio = document.getElementsByName('choice');
for(var i=0; i < radio.length; i++){
if(radio[i].checked){
return +(radio[i].value) + 1;
}
}
};
I realize now the problem was more with my approach than any one error. I followed and improved upon an example of another student. Here is the repo for the project as it stands. The most important thing I've learned is how to encapsulate the variables I need all functions to have access too. In this case, a variable called currentQuestionIndex that increments and is available to all functions was important to the solution.
I have this code which manipulates the asp.net treeview html code.
This code gets run frequently, so its important that it runs as fast as possible.
I want to learn more about jquery selectors and improving its speed. So far I was able to get this code myself.
Some things I am not sure about is if you want the third child element, do I use [2] or .eq(2) or :nth-child(2)? Also what if I use $ to select something that was from an array of selected stuff, is this necessary, or is it already selected?
Does anyone know any tricks or hints I can do to improve my jquery select efficiency?
Thanks.
function showResultsOnTreeview(treeviewID, filenameDictionary) {
var sectionNodes = $("#" + treeviewID + " > table");
var numOfSections = sectionNodes.length;
var i, j, sectionName, divContainer, itemNodes, numOfItems, itemName, itemTag, itemPath;
for (i = 0; i < numOfSections; i += 1) {
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
divContainer.hide();
itemNodes = $('table', divContainer);
numOfItems = itemNodes.length;
for (j = 0; j < numOfItems; j += 1) {
itemTag = $('td', $(itemNodes[j])).eq(2);
itemTag.removeClass('treeViewResult');
itemName = getNameFromItem($(itemNodes[j]).text());
itemPath = filenameDictionary[itemName];
if (itemPath != null) {
if (itemPath.indexOf(sectionName + "/" + itemName) != -1) {
itemTag.addClass('treeViewResult');
divContainer.show();
}
}
}
}
}
There is some optimisation you can do. The first on is for sure to use .eq() instead of []. Like here, you hare creating a jQuery object :
var sectionNodes = $("#" + treeviewID + " > table");
But then later, you do this :
sectionName = $(sectionNodes[i]).text();
divContainer = $(sectionNodes[i]).next('div');
Here you are creating 2 more, unneeded, jquery object, you could just do this :
sectionName = sectionNodes.eq(i).text();
divContainer = sectionName.next('div');
Then, i do't know if you have a different way to do it, but if you can remove the "loop in a loop", that would be great.
After, instead of using context selectore ($('selector', $element)), use find. Context use find so it will reduce the number of function calls. Take this line for example :
$('td', $(itemNodes[j])).eq(2)
You are creating 2 jQuery object when you can do the same without an extra object and could use .find():
itemTag = itemNodes.eq(j).find('td').eq(2);
Basicly, use .find() instead of context and avoid creating unneeded jQuery object. Hope that will help.
Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});
I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.
I am not sure how to do this.
Here is a fiddle of the code I have thus far with comments.
http://jsfiddle.net/taoist/yPrab/1/
Thank you
Javascript Code
var applicationArea = document.getElementById("applicationArea");
var orangeButton = document.getElementById("orangeButton");
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy'; // I want each newly created div to have a numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
applicationArea.appendChild(newDivThingy);
};
Am I missing something, why not use a counter?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy' + (++counter);
// continue your stuff here
}
Libraries like underscorejs provide a uniqueid function for this. Otherwise its easy to implement one.
myNamespace.uniqueId = (function () {
var counter = 0; // in closure
return function (prefix) {
counter++;
return (prefix || '') + '-' + counter;
};
}());
Usage.
newDiv.id = myNamespace.uniqueId('newDiv');
Simply use a integer and increment it as each element is added.
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),
counter = 1;
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = "newDivThingy" + counter++;
applicationArea.appendChild(newDivThingy);
}
I have no doubt you have solution and may have forgotten this post.
BUT, I wold like to show a solution that is a compact format.
Note the counter is set to (counter++) so it will start at 1.
var orangeButton = document.getElementById("orangeButton");
var counter = 0;
orangeButton.onclick = function() {
document.getElementById('applicationArea')
.appendChild(document.createElement('div'))
.setAttribute("id", 'newDivThingy' + counter++);
// I want each newly created div to have a
// numeric value concatenated to it's ID.
// IE newDivThingy1 newDivThingy2 newDivThingy3
};
I'm trying to change the value of an input field with Javascript.
I tried everything, but nothing seems to works. I tried putting the 5 between quotation marks and using jquery. I also double-checked the array and everything.
Here is the input code:
<input type="number" id="id_[SOME_ID_HERE]" value="0">
and the loop used to update the values.
for (var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(3)).value = 5;
}
jsfiddle: http://jsfiddle.net/zkTud/
EDIT: Seems like it doesn't work with type="text" as well...
EDIT2: Thank you everyone who answered. My problem was actually something else.
The input was loaded from another page, and it took time and the for loop I had problem with (see above) was executed before the file was done loading.
All I did was to move the for loop as is to the callback function and it works now.
Thanks anyways!
I really appreciate the help I'm getting in this site! :)
The problem is that your call to substring is returning too much of the string, so there are no elements found by getElementById. Change it to this:
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
document.getElementById("id_" + val.substring(5)).value = 5;
}
Here's an updated fiddle.
The substring method (when called with one argument) returns the characters from the index specified to the end of the string. Since you are specifying index 3, you get "d_1", "d_2" etc. when actually you just want the number.
Alternatively, you could of course change the string to which you append the substring, but I think that would be more confusing to read (not immediately obvious which element will be returned):
document.getElementById("i" + val.substring(3)).value = 5;
demo http://jsfiddle.net/bY4EV/6/
sustring(3) gives d_1 : How to substring in jquery
hope this helps
code
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id_" + val.substring(5)).val("5");
}
Check this, JSFiddle , Updated and corrected your problem.
Code:
var shoppingCart = new Array();
shoppingCart[0] = "prod_1";
shoppingCart[1] = "prod_3";
shoppingCart[2] = "prod_2";
for(var i = 0; i < shoppingCart.length; i++) {
var val = shoppingCart[i];
$("#id" + val.substring(4)).val( "5");
}