I have use 2 functions i want when i click on button it should clear the output of first function result but it does not work when i use .innerHTML = ""; how to do it?
function HalfRightTriangle() {
for (var i = 1; i <=7; i++) {
for (var j = 1; j <i; j++) {
// document.write("*");
document.getElementById("result").innerHTML += "*";
} // end of inner for loop
document.getElementById("result").innerHTML += "<br>";
} // end of outer for loop
document.getElementById("result").innerHTML += "";
} // function end
If you're only using text, it may be better to just work with a variable, and then set it to innerHTML when done.
Something like this:
function HalfRightTriangle() {
var inner = document.getElementById("result").innerHTML;
for (var i = 1; i <= 7; i++) {
for (var j = 1; j < i; j++) {
inner += "*";
} // end of inner for loop
inner += "<br>";
} // end of outer for loop
document.getElementById("result").innerHTML = inner;
} // function end
Solution:
<script type="text/javascript">
function HalfRightTriangle() {
for (var i = 1; i <=7; i++) {
for (var j = 1; j <i; j++) {
// document.write("*");
document.getElementById("result").innerHTML += "*";
} // end of inner for loop
document.getElementById("result").innerHTML += "<br>";
} // end of outer for loop
} // function end
document.getElementById("result").innerHTML = "";
function HalfLeftTriangle() {
for (var i = 7; i >=1; i--) {
for (var j = 1; j <=i; j++) {
// document.write("*");
document.getElementById("result").innerHTML += "*";
} <!-- end of inner for loop -->
//document.write("<br>");
document.getElementById("result").innerHTML += "<br>";
} <!-- end of outer for loop -->
} // function end
document.getElementById("result").innerHTML = "";
</script>
</head>
<body>
<button type="button" onclick="HalfRightTriangle();"> Half Right Triangle </button>
<button type="button" onclick="HalfLeftTriangle();"> Half Left Triangle </button>
<br><br>
<div id="result"> Result Here </div>
if you use container control show your result then inner html work but if don't have container control then use val function of java script.
example
<div id=result>
<label id=result></label>
</div>
<script type=text/java script>
$('#result').html("")
$('#result').val("")
</script>
Related
I would like to know how to append to the DOM just once after these nested loops.
Also, the variable letters is dynamic, so I would need to 'reset' my appended grid when a new string is passed to letters
let letters = "abcdefghijkl"
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`
);
}
}
Thank you in advance!
EDIT
After the answer from T.J. Crowder I tried to incorporate my code to be able to populate my grid from the inputs, but when I unselect one of the inputs, that row isn't cleared.
let letters = 'abcdefghijkl';
let html = "";
$(".list-checkbox-item").change(function() {
let chosenLetters = $(this).val();
if ($(this).is(":checked")) {
arrayOfChoices.push(chosenLetters);
} else {
arrayOfChoices.splice($.inArray(chosenLetters, arrayOfChoices), 1);
}
letters = arrayOfChoices.sort().join(""); // Gives me a string with chosen letters ordered alphabetically
console.log(
`This is my string in var 'letters' ordered alphabetically (Need to clear grid after each instantiation or append after the loop): %c${letters}`,
"color: red; font-weight: bold; font-size: 16px"
);
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html += `<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
});
What am I doing wrong?
Assuming #music-grid is empty before you run this code the first time, build up the HTML in a string and then use html() to replace the contents of #music-grid rather than appending to it:
let html = "";
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html +=
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
You also see people building up the HTML in an array and using array.join("") at the end to get a single string, but with modern JavaScript engines it's really a wash either way...
Can someone please tell me what I'm doing wrong?
I think it's something with the string adding;
I've also tried:
var column = $("<td></td>")
instead of:
var column = $("<td>")
etc
and it's always the same result on the HTML : "[object Object]"
What am I doing wrong?
$(function() {
createTable(8);
});
function createTableColumn() {
var column = $("<td>");
return column;
}
function createTableRow(gameBoardSize) {
var columns = "";
var row;
for(counter = 0; counter < gameBoardSize; counter++) {
columns = columns + createTableColumn();
}
row = $("<tr>").append(columns);
return row;
}
function createTable(gameBoardSize) {
var rows = "";
for(counter = 0; counter < gameBoardSize; counter++) {
rows += createTableRow(gameBoardSize);
}
$("#gameboard-table").append(rows);
}
You are accidentally performing a string concatenation operation with += createTableRow.... Change rows to an array and use push instead
var rows = [];
for(counter = 0; counter < gameBoardSize; counter++) {
rows.push(createTableRow(gameBoardSize));
}
+ is for concatenating strings, not jQuery objects.
Just append directly to the jQuery objects:
function createTableRow(gameBoardSize) {
var row = $("<tr>");
for(var counter = 0; counter < gameBoardSize; counter++) {
row.append(createTableColumn());
}
return row;
}
function createTable(gameBoardSize) {
for(var counter = 0; counter < gameBoardSize; counter++) {
$("#gameboard-table").append(createTableRow(gameBoardSize));
}
}
Make sure you use local variables for loop counters. Otherwise, the for loop in createTableRow updates the counter in createTable, which causes that loop to end prematurely.
$(function(){
createTable(8);
var i=0;
$('td').each(function(){
i++;
$(this).text(i);
});
});
function createTable(number){
for(var count = 0;count<number;count++){
$('#gameboard-table').append('<tr>');
$('tr').append('<td>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="gameboard-table"></table>
just string concatenation and one append.
function createTable(rowsCount, columnsCount) {
var rows = "";
var cell = "";
var table = $("<table />")
for (var i = 0; i < columnsCount; i++) {
cell += "<td></td>";
}
for (var i = 0; i < rowsCount; i++) {
rows += "<tr>" + cell + "</tr>";
}
table.append(rows);
return table;
}
I have this code who works properly with for loop, how to made while and do/while loop to work properly on same way when i click on button?
<body>
<div>
<button onclick = "fun()">Click
</button>
<p id = "dr">
</p>
<script>
function fun() {
var str = "";
for (var i = 0; i < 11; i++) {
str = str + i + "<br/>";
document.getElementById("dr").innerHTML = str;
}
}
</script>
</div>
</body>
This sounds a bit like HW, so I won't give you the entire code.
However, you have this code in your for loop
for (var i=0; I<11; i++)
}
In that, I is never defined, so you should probably change it to i.
For changing it to a do{}..while() loop, remember that every for loop of the form for(a;b;c){d;} can be expanded to the while loop
a;
while(b){
d;
c;
}
and therefore to the do..while loop of
a;
do{
d;
c;
}while(b);
while:
function fun()
{
var str ="";
while( i < 11 )
{
str=str + i +"<br/>";
document.getElementById("dr").innerHTML =srt;
i++;
}
}
do/while:
function fun()
{
var str ="";
do
{
str=str + i +"<br/>";
document.getElementById("dr").innerHTML =srt;
i++;
}while( i < 11 );
}
I have a bit of an issue at the moment that I am hoping one of you can help me with. I have tried several things, and I just can't get it. I am trying to print a triangle of asterisks using JavaScript. The program is to ask the user for the amount of rows, and then the direction. I haven't even started with the direction yet because I can't get the rows to work. Odd thing is that I can get it to print out the triangle hard-coding the function call.
This is the JS file:
function myTriangle(){
var result = "";
var totalRows = document.getElementById('rows').value;
var direction = document.getElementById('UpOrDown').value;
for (var i = 1; i <= totalRows; i++){
document.writeln("count");
for (var j = 1; j <= 1; j++)
{
result += "*";
}
result += "<br/>";
}
return result;
}
var answer = myTriangle();
document.getElementById('myDiv').innerHTML = answer;
This is the HTML file:
<!DOCTYPE html>
<head>
<title>Lab 2</title>
<script src="scripts.js", "div.js"></script>
</head>
<body>
<form name="myForm">
<fieldset>
<legend>Input Fields</legend>
rows: <input type="text" id="rows" /><br>
direction: <input type="text" id="UpOrDown" /><br>
press: <input type="button" value="GO!" id="myButton"
onclick="myTriangle();"/>
</fieldset>
</form>
<div id="myDiv">
</div>
</body>
The output will be something like this:
*
**
***
****
*****
Generally there are four types of triangle -
1.)* 2.) *** 3.) * 4.) ***
** ** ** **
*** * *** *
Code for 1 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 2 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 3 -
var ast = [],
i, j = 4;
for (i = 0; i < j; i++) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
Code for 4 -
var ast = [],
i, j = 4;
for (i = j-1; i >=0; i--) {
ast[i] = new Array(j - i).join(' ') + new Array(i + 2).join("*");
console.log(ast[i]);
}
To print asterisk in document rather than console -
document.getElementById('anyElement').innerHTML+=ast[i] + '<br />';
document.writeln will completely wipe the page unless it's called while the page is loading.
Therefore it will destroy myDiv, causing the getElementById to fail.
Furthermore, I'm not sure what you're trying to achieve with that <script> tag, but it looks like you need two of them.
EDIT: Oh, and this: for (var j = 1; j <= 1; j++) will only ever iterate once.
EDIT 2: Here's my implementation of a solution.
This isn't a valid script tag.
<script src="scripts.js", "div.js"></script>
You need to break it up into two tags:
<script src="scripts.js"></script>
<script src="div.js"></script>
This is my solution, it uses es2015 .replace() but there is a nice
polyfill for es5 as well here:
var output = document.getElementById('output');
function triangle (size) {
for (var i = 1; i <= size; i++) {
output.innerHTML += '*'.repeat(i) + '<br>';
}
}
triangle(2);
This is a solution in ES3/5
var output = document.getElementById('output');
function triangle(size) {
var allLines = '';
for (var i = 1; i <= size; i++) {
var oneLine = createLine(i);
allLines += oneLine;
}
return allLines;
}
function createLine(length) {
var aLine = '';
for (var j = 1; j <= length; j++) {
aLine += '*';
}
return aLine + "<br/>";
}
output.innerHTML += triangle(3);
<div id='output'></div>
I've got a javascript function
<head>
<title>
Test
</title>
<script type="text/javascript">
function GetResult()
{
count = 0;
for(var i=0;i<10;i++){
for(var j=1;j<4;j++){
if (document.getElementById("label"+i+j).checked){
count +=1;
}
}
}
if (count!=10)
alert("Please answer all the questions");
else alert(count);
}
</script>
In the code there are a lot of radiobutton. ther look like
<input type="radio" name="q1" value="1" id="label01"/>
But my javascript function never shows alert.
The button that is supposed to call function is
<input type="button" value="Result" onclick="GetResult()"/>
Maybe button doesn't call GetResult?
To elaborate what Felix already said: Here is how you can check whether or not document.getElementById found the specified element (it will return null if it failed).
for (var i = 0; i < 10; i++) {
for (var j = 1; j < 4; j++) {
// Store the result in a local variable
var label = document.getElementById("label"+i+j);
// Include a check whether "null" got returned
if (label && label.checked) {
count +=1;
}
}
}
Try this:
function GetResult() {
var count = 0;
for (var i = 0; i < 10; i++){
for (var j = 1; j < 4; j++){
var label = document.getElementById("label" + i + j);
if (label && label.checked) {
count +=1;
}
}
}
if (count != 10) {
alert("Не все отвечено");
} else {
alert(count);
}
}
Added var to the count declaration.
Fixed up some general formatting.
The important bit: checked to see if document.getElementById() returned a value before checking that value's checked property.