inner html inside the forloop is not working - javascript

var draftloc = { ans: ["a", "b", "c"] };
for (var i = 0; i < draftloc.ans["length"]; i++) {
//draftloc.length === draftloc["length"]
console.log("draftloc for loop works");
//rcnounk is a element(div)
rcnounk.innerHTML += `<div class="ml-negative-20 mt-9">
<div class="ui check checkbox">
<input type="checkbox" name="example">
<label>${draftloc.ans[i]}</label>
</div>
</div>`;
}
for loop is working everything is defined but inner html not working

You need to get the DIV-elem from rcnounk.
rcnounk=document.getElementById('rcnounk');
With this it seems to work.
var draftloc = { ans: ["a", "b", "c"] };
for (var i = 0; i < draftloc.ans["length"]; i++) {
//draftloc.length === draftloc["length"]
console.log("draftloc for loop works");
rcnounk=document.getElementById('rcnounk');
//rcnounk is a element(div)
rcnounk.innerHTML += `<div class="ml-negative-20 mt-9">
<div class="ui check checkbox">
<input type="checkbox" name="example">
<label>${draftloc.ans[i]}</label>
</div>
</div>`;
}
<div id='rcnounk'>RC</div>

Related

Delete Element from the Page

the teacher asked us to design a website to teach children letters, when I click the generate button, it generates letters in a random way, and when I click on a letter, an image of something that starts with this letter is displayed. The problem is when I click on another letter, it displays an image of something that starts with this letter, but The old image of the other letter is still present on the page and is not deleted. What I want is when I click on a letter it displays an image of something that begins with this letter and when I click on another letter I want it to delete the old image and display only the image that begins with this letter
this is my JS code
var div2 = document.getElementById("div2");
var div3 = document.getElementById("div3");
var generate = document.getElementById("generate");
var input = document.getElementById("input");
var letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
// here to add the path of the each img to array to store it becuase we will need it leter
litterImg = [];
for (let i = 0;i < 26;i++) {
litterImg[i] = 'img\\'+i+'.jpg';
};
var randomLetter = [];
var getRandomLetter = [];
var linkImg = [];
var numberOfLitters;
generate.addEventListener("click",function(e){
numberOfLitters = input.valueAsNumber;
for (let index = 0; index < numberOfLitters; index++) {
let x = randomNumbers();
randomLetter[index] = document.createElement("input");
randomLetter[index].setAttribute("type","button");
randomLetter[index].setAttribute("value",letters[x]);
randomLetter[index].setAttribute("id", x);
randomLetter[index].setAttribute("class",x);
div2.appendChild(randomLetter[index]);
}});
// event to add the images when i click on a litter
div2.addEventListener("click",function(e){
for (let index = 0; index < 26; index++) {
if (e.target.id == index) {
linkImg[index] = document.createElement("img");
linkImg[index].setAttribute("src",litterImg[index]);
linkImg[index].setAttribute("width","1080px");
linkImg[index].setAttribute("height","720px");
div3.appendChild(linkImg[index]);
}
}
});
and this is my html code
<html>
<head>
<meta>
<title>Alphabet Learner</title>
</head>
<body>
<div id="div" class="div" style="text-align : center;">
<h1>Learn the English Litters </h1><br>
<label >Number of Litters: </label>
<input type="number" class="input" id="input" >
<input type="button" class="generate" id="generate" value="Generate">
<br><br>
<div id="div2" class="div2">
</div><br>
<div id="div3" class="div3"></div>
</div>
<script src="script.js"></script>
</body>
</html>
I have changed the script a bit more than it was needed, sorry for that. Anyway, it works!
The main part was to add the removal of element before the addition of a new one.
const generate = document.getElementById("generate");
const input = document.getElementById("input");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");
const letters = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
// here to add the path of the each img to array to store it becuase we will need it leter
const letterImg = [];
for (let i = 0; i < 26; i++) {
letterImg[i] = "img\\" + i + ".jpg";
}
generate.addEventListener("click", function () {
const numberOfLetters = input.valueAsNumber;
for (let i = 0; i < numberOfLetters; i++) {
const x = randomNumber();
const randomLetter = document.createElement("input");
randomLetter.setAttribute("type", "button");
randomLetter.setAttribute("value", letters[x]);
randomLetter.setAttribute("id", x);
randomLetter.setAttribute("class", x);
div2.appendChild(randomLetter);
}
});
function randomNumber() {
return Math.floor(Math.random() * 26);
}
// event to add the images when i click on a litter
div2.addEventListener("click", function (e) {
const index = e.target.id;
const linkImg = document.createElement("img");
linkImg.setAttribute("src", letterImg[index]);
linkImg.setAttribute("width", "1080px");
linkImg.setAttribute("height", "720px");
// remove old image
const old = document.querySelector('#div3 img');
old && old.remove();
// add new image
div3.appendChild(linkImg);
});
<body>
<div id="div" class="div" style="text-align: center;">
<h1>Learn the English Letters </h1><br>
<label>Number of Letters: </label>
<input type="number" class="input" id="input">
<input type="button" class="generate" id="generate" value="Generate">
<br><br>
<div id="div2" class="div2"></div>
<br>
<div id="div3" class="div3"></div>
</div>
</body>

My program keeps outputting "undefined". I am trying to create a function that changes text on my webpage with a button that calls a function

I am trying to create a program that takes a user's input from the html and runs it through a for loop, and then displays the translated input. The problem is that the output just displays undefined. The function that translates the user's input in the inputbox is supposed to be called with the button in the html, but clicking it changes nothing, and the output just stays "undefined"
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
console.log(resultArray.join('').toUpperCase());
document.getElementById('input').innerHTML = input;
document.getElementById('output').innerHTML = resultArray.join('').toUpperCase();
console.log(resultArray);
}
function translateInput() {
let userInput = document.getElementById('input').value
let translateResult = whaleTalk(userInput);
updateOutput(translateResult);
}
function updateOutput(input) {
document.getElementById('output').innerHTML = input;
}
whaleTalk();
updateOutput();
<!DOCTYPE html>
<head>
<title>Whale Talk Translator</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="whaletranslator.css" rel="stylesheet" type="text/css" />
<style>
</style>
</head>
<body>
<header style="color: white;">Whale Talk Translator </header>
<h2>Input anything you want into the box below and hit the button to translate it.</h1>
<div class="translatorBox">
<input value="" id="input" type="text" class="inputBox" placeholder="Text to translate">
<br>
<div class="container">
<div class="center">
<button class="translateButton" onclick="updateOutput()">Translate</button>
</div>
</div>
<div class="container">
<div class="center">
<button class="reloadButton" onClick="window.location.reload();">Reload</button>
</div>
</div>
</div>
<p style="padding: 2em">Translated input:</p>
<div class="output">
<p id="output"></p>
</body>
<script src="whaletranslator.js" type="text/javascript"></script>
</html>
Your function returns undefined because you are not returning anything from it. Try this:
function whaleTalk() {
let input = document.getElementById('input').value
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (var i = 0; i < input.length; i++) {
for (var j = 0; j < vowels.length; j++) {
if (input[i] == vowels[j]) {
if (input[i] == 'e') {
resultArray.push('ee');
} else if (input[i] == 'e') {
resultArray.push('uu');
} else {
resultArray.push(input[i]);
}
}
}
}
return resultsArray.join('').toUpperCase()
}
Now when your translationResult variable will be the string that your updateOutput method will set to the innerHtml of the element with id 'output'. Instead of calling the two methods at the bottom you can now just call translateInput()
You haven't satisfied the argument for the method updateOutput, the "undefined" message is caused because the argument is not defined in your call

how to check more than one class name in js

<script src="https://code.jquery.com/jquery-1.12.4.min.js">
var answers = ["A","C","B"],
tot = answers.length;
function getScore(){
var score = 0;
for (var i=0; i<tot; i++)
if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..
score += 1; // increment only
return score;
}
function returnScore(){
$('p').html('Score: ' + getScore() + '');
}
</script>
here in this line,
if($("input[class='question0']:checked").val()===answers[i]) //TODO add another classes like question1,question2,etc..
how to check for more than one classes? question+i is possible? or how to mention many classes? thanks in advance senior!
You can just format i into your string like so:
for(let i = 0; i < tot; i++) {
if($(`input[class='question${i}']:checked`).val() === answers[i])
score++;
}
In general you can use string literals like so using the backtick character `:
let variable = "value";
console.log(`A sentence containing a ${variable}`);
This is the way to select multiple classes in JQuery
$("input[class*=question]")
Try the full code
var answers = ["A", "C", "B", "D"];
var inputList = $("input[class*=question]");
inputList.change(returnScore);
function getScore() {
var score = 0;
inputList.each(function (i) {
if ($(this).val() === answers[i] && $(this).is(":checked")) score += 1;
});
return score;
}
function returnScore() {
$("p").html("Score: " + getScore() + "");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div>answers = ["A", "C", "B", "D"]</div>
<div>
<input class="question0" type="checkbox" id="question0" value="A"/>
<label for="question0">This is Question 0, value: A</label>
</div>
<div>
<input class="question1" type="checkbox" id="question1" value="C"/>
<label for="question1">This is Question 1, value: B</label>
</div>
<div>
<input class="question3" type="checkbox" id="question3" value="R"/>
<label for="question3">This is Question 3, value: R</label>
</div>
<div>
<input class="question4" type="checkbox" id="question4" value="F"/>
<label for="question4">This is Question 4, value: F</label>
</div>
<p></p>

Unable to highlight the value in select tag using angularjs

********below is the code in html file********
<div class="form-group">
<label for="" class="col-sm-2 control-label">Count:</label>
<div class="col-sm-10">
<select class="form-control" ng-model="selectedItem"
ng-options="obj.name for obj in listObj">
</select>
</div>
</div>
******code in js******
var listCount = [];
for(var i=1;i<6;i++){
var obj = {
"name":i,
"value":i
};
listCount.push(obj);
};
$scope.listObj = listCount;
****// response Iam getting name and value in between 1 to 6****
scope.selectedItem= {"name":response.name,
"value":frac.convert(response.value, false).numerator
};
You should use:
for(var i = 0, len = $scope.listObj.length; i < len; i++) {
if(response.name === $scope.listObj[i].name) {
$scope.selectedItem = $scope.listObj[i];
break;
}
}
If you want to select an item, $scope.selectedItem should refer to that item in $scope.listObj array.

jquery: Paste a set of elements over another set of elements / merging elements

I have 2 sets of elements:
<div class='container container1'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
</div>
</div>
<div class='container container2'>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>mountain dew</div>
<div class='coffee'></div>
</div>
</div>
I want to paste container1 over container2 such that any replacements are over written and any uniques to each container are put left alone and put together.
The result should be:
<div class='container container-result'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
<div class='coffee'></div>
</div>
</div>
The elements can have any arbitrary hierarchy / depth. What's the best way to do this?
Thanks in advance.
Since your question is tagged jQuery here's a slightly shorter answer using that library:
function copy(from, to) {
from.children().each(function() {
var match = to.children("." + this.className.split(' ').join('.'));
if(match.length) {
if(match.children().length == 0) {
match.replaceWith(this);
} else {
copy($(this), match);
}
} else {
to.append(this);
}
}).end().remove();
from.remove();
}
Then you'd just call it like this:
copy($(".container1"), $(".container2"));
You can give it a try here, the result is:
<div class="container container2">
<div class="cars">
<div class="sedans"></div>
<div class="vans"></div>
</div>
<div class="drinks">
<div class="soda">coke</div>
<div class="coffee"></div>
<div class="juice"></div></div>
<div class="colors">
<div class="blue"></div>
<div class="red"></div>
</div>
</div>
Note that the class name is still container2 if you want to replace that just add this to switch the class after the copy() call:
$(".container2").toggleClass("container2 container-result");
The match is based on all classes the element contains, so if an element has class="car blue" and there's a corresponding class="blue car" it'll choose that one to overwrite.
This isn't the most efficient route since you're firing up the selector engine on the children each iteration, but unless you're doing lots of elements, it should be pretty quick.
With regard to unique merging I can't help you there, but if your app by any chance happens to be in PHP then you can use php's array_merge function to merge them before outputting the HTML.
ReplaceWith is a nice jquery function to replace aka "paste" over, it may will help you with half of your solution.
This appears to do what you wanted:
<div class='container container1'>
<div class='colors'>
<div class='blue'></div>
<div class='red'></div>
</div>
<div class='drinks'>
<div class='soda'>coke</div>
<div class='juice'></div>
</div>
</div>
<div class='container container2'>
<div class='cars'>
<div class='sedans'></div>
<div class='vans'></div>
</div>
<div class='drinks'>
<div class='soda'>mountain dew</div>
<div class='coffee'></div>
</div>
</div>
<div class='container container-result'>
</div>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getContainerArray(containers, level) {
level = level || 0;
var result = [];
for (var i=0; i<containers.length; ++i) {
var el = containers.eq(i);
var obj = { "class": el.attr("class") };
if (level == 0) {
obj.items = getContainerArray(el.children("div"), 1);
} else {
obj.text = el.text();
}
result.push(obj);
}
return result;
}
function mergeContainers(containerArray) {
var result = [];
function indexOfClass(name) {
for (var i = 0; i < result.length; ++i) {
if (result[i]["class"] == name) {
return i;
}
}
return -1;
}
for (var i = 0; i < containerArray.length; ++i) {
var obj = containerArray[i];
var name = obj["class"];
var index = indexOfClass(name);
if (index < 0) {
result.push(obj);
} else if (obj.items != null) {
result[index].items = mergeContainers(new Array().concat(result[index].items, obj.items));
}
}
return result;
}
function getHtml(objArray) {
var result = [];
for (var i = 0; i < objArray.length; ++i) {
var obj = objArray[i];
result.push("<div class=\"", obj["class"], "\">");
if (obj.text != null && obj.text != "") {
result.push(obj.text);
}
if (obj.items != null) {
result.push(getHtml(obj.items));
}
result.push("</div>");
}
return result.join("");
}
var html = getHtml(mergeContainers(getContainerArray($("div.container1>div,div.container2>div"))));
$("div.container-result").append(html);
</script>
This answer:
Does exactly what you asked for.
Handles repeated mergings, if div class container-result already exists.
Merges any number of container divs.
Uses jQuery and is more efficient than some other solutions.
See it in action at jsfiddle.net.
/*--- Get all "container" divs but exclude any "container-result" divs.
*/
var zContainers = $("div.container").not ("div.container-result");
if (zContainers && zContainers.length)
{
//--- Get or create the results div.
var zResultDiv = $("div.container-result");
if (!zResultDiv || !zResultDiv.length)
{
zResultDiv = zContainers.parent ().append ("<div class='container container-result'></div>");
zResultDiv = $("div.container-result");
}
//--- Move the container's contents to the master container, preserving order.
zContainers.each (function () {$(this).children ().appendTo (zResultDiv);} )
//--- Kill the old container(s).
zContainers.remove ();
RecursivelyMergeDivsByClass (zResultDiv);
}
function RecursivelyMergeDivsByClass (jNode)
{
/*--- Get a list of the direct-child div's class names.
Sort and winny out a list of duplicates.
*/
var zDirectChildDivs = jNode.find ("> div");
var aClassList = zDirectChildDivs.map (function () {return this.className;} ).get ();
aClassList.sort ().unshift (0);
for (var J = aClassList.length-1; J > 0; J--)
if (aClassList[J] != aClassList[J-1]) aClassList.splice (J, 1); // Delete items without duplicates.
aClassList.splice (0, 1);
/*--- For any duplicates, copy the contents into the first instance, preserving order.
For exact duplicate nodes, the first (oldest) version is kept and the remaining are discarded.
*/
for (var J = aClassList.length-1; J >= 0; J--)
{
var zDupClasses = zDirectChildDivs.filter ("." + aClassList[J]);
var zFirstDiv = zDupClasses.first ();
zDupClasses = zDupClasses.not (zFirstDiv);
zDupClasses.each (function () {$(this).children ().appendTo (zFirstDiv);} )
zDupClasses.remove ();
RecursivelyMergeDivsByClass (zFirstDiv)
}
}

Categories