Javascript while and do/while loops - javascript

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 );
}

Related

write a loop into html div with JS

I don't understand why this code is not working, could you help me please ?
I want that when you click on the button, the "theloop" div get filled with yo 0 , yo 1 etc... till the number you inputed
<p>
enter how many time you want the loop to repeat
<input id="nloop">
</p>
</br>
<button onclick="displayLoop()">
Try it
</button>
<p id="theloop"></p>
<script>
var nloop = document.getElementById("nloop").value;
var theloop = document.getElementById("theloop")
function displayLoop () {
for (var i=0; i<nloop; i++) {
theloop.innerHTML = "yo" + i;
}
}
</script>
You have many Syntax error + code error
<p>enter how many time you want the loop to repeat <input id="nloop"></p> </br>
<button onclick="displayLoop()">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop")
function displayLoop(){
var nloop = document.getElementById("nloop").value;
theloop.innerHTML = '';
for (var i=0; i<nloop; i++){
theloop.innerHTML = theloop.innerHTML + "yo" + i+ "<br/>";
}
}
</script>
You need to get the value of nloop when you call the function or the value will be the value when the script is loading, so an empty value.
If you affect something to innerHtml it will erase the content of the innerHtml.
I added BR only for the style you can ignore that.
You missed few syntax checks that I have corrected:
<p>enter how many time you want the loop to repeat <input id="nloop" /></p>
</br>
<button onclick="displayLoop();">Try it</button>
<p id="theloop"></p>
<script>
var theloop = document.getElementById("theloop");
function displayLoop () {
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
theloop.innerHTML = "yo" + i;
}
}
</script>
<script>
function displayLoop()
{
var nloop = document.getElementById("nloop").value;
for (var i=0; i<nloop; i++)
{
document.getElementById("theloop").innerHTML += "yo" + i;
}
}
</script>
This is working fine now :)

JS function looping double as expected

This is Javascript code for some quiz i am making.
In my case table.length = 2, and function is repeating 2 times with parameter for first table and second.
But why command shows 4 times in console?
console.log("Hello");
.
function start(){
var brojac =0;
var table = document.getElementsByTagName("table");
for (i =0; i<table.length ; i++){
jednoPitanje(i);
brojac += parseInt(jednoPitanje(i))
}
console.log("Sakupili ste ukupno " + brojac + " bodova");
}
function jednoPitanje(x) {
var odgovori ="";
var table = document.getElementsByTagName("table");
var tableN = table[x];
var input = tableN.getElementsByTagName("input")
var brojInputa = tableN.getElementsByTagName("input").length;
//Uzima bodove,kategoriju i index tocnih odgovora
var bodovi =tableN.classList[2];
var kategorija =tableN.classList[1];
var tocni = tableN.classList[0];
console.log("Hello");
//Iteracija kroz sve checkboxsove u tablici
for (j =0; j<brojInputa ; j++){
if(input[j].checked==true){
odgovori += tableN.getElementsByTagName("input")[j].value;
}
}
if(odgovori == tocni){
}
else{bodovi = 0;}
return bodovi;
}
You are calling console.log("Hello"); in the function jednoPitanje(). You call this function twice inside your loop:
jednoPitanje(i); // <-- this cause console.log() to run
brojac += parseInt(jednoPitanje(i)) // <-- this also causes the console.log()
and since your loop runs twice it prints four times.
It's not immediately clear if you need that function to run twice, but if you don't, you can just remove the first call:
for (i =0; i<table.length ; i++){
brojac += parseInt(jednoPitanje(i))
}
or if you prefer the extra clarity:
for (i =0; i<table.length ; i++){
var bodovi = jednoPitanje(i);
brojac += parseInt(bodovi)
}

Clear Div Content Inside Function

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>

Output object values in javascript

I have an ObjectHtmlInputElement:
for($array as $a){
echo '<input type="checkbox" name="check[]" value="'.$a.'">';
}
Javascript:
function myForm(){
var theForm=document.getElementById("myCheck");
var a = theForm.elements['check[]'];
for( var i=0; i<a.length; i++){
if(a[i].checked){
alert( a[i].value );
return true;
}
}
}
This script checks if atleast one checkbox is checked then return true(there can also be more checkboxeses checked).What i need is to output in the alert() , each checkbox that have been checked(each object value that passes 'a[i].checked'). a[i].value , outputs only the first value, so i need something else.
Based on 'dec' and 'vijay' s answer i managed to find a solution:
var checkedCheckboxes="";
for( var i=0; i<a.length; i++){
if(a[i].checked){
checkedCheckboxes += a[i].value;
}
}
for( var i=0; i<a.length; i++){
if(a[i].checked){
alert('Checked: ' + checkedCheckboxes);
return true;
}
}
Indeed the loop was stopped because of return true as dec said.And the solution was to make another loop,and insert all values in a variable so i can use it in the alert.
The first value seems to match a[i].checked and then you return and no other element is tested. So remove return true.
Try this:
function myForm() {
var theForm = document.getElementById("myCheck");
var a = theForm.elements['check[]'];
var checkedCheckboxes = "";
for (var i = 0; i < a.length; i++) {
if (a[i].checked) {
checkedCheckboxes += a[i].value + ", ";
}
}
if (checkedCheckboxes.length > 0) alert(checkedCheckboxes);
return checkedCheckboxes.length > 0;
}
http://jsfiddle.net/p5upLprk/1/
with jquery you can do:
function isThereAtLeastOneCheckActive() {
var res = false
$(':checkbox').each(function() {
if (this.checked) {
res = true
alert(this.val())
// .text() can also be used
}
})
return res
}
As you are beggining, maybe you find strange the absense of ;
There is no need for them in js: https://mislav.net/2010/05/semicolons/

javascript array timed

I'm missing some little thing.. prints the array but doesn't wait in between lines.
<script type="text/javascript">
function showLines()
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML=arr;
setTimeout('showLines()',duration);
}
</script>
That's because your just printing out the whole array, try this.
function showLines(_index) {
var arr =["Hi!", "Welcome!", "Hello!"], html = '', i, index = _index || 0,
newIndex;
for (i = 0; i < index && i < arr.length; ++i) {
html += arr[i] + "<br />";
}
document.getElementById("quotes").innerHTML=html;
newIndex = index + 1;
if (newIndex < arr.length) {
setTimeout(function() {showLines(newIndex);}, 2000);
}
}
That should do the trick.
If you only want one at a time then replace
for (i = 0; i < index && i < arr.length; ++i) {
html += arr[i] + "<br />";
}
with
document.getElementById("quotes").innerHTML=arr[index];
The line
document.getElementById("quotes").innerHTML=arr;
will convert arr into a String by joining it with commas. Therefore, you will see
Hi!, Welcome!, Hello!
This function is idempotent, which is probably not what you are going for. I think what you're missing is an index that lets you know which element of the array you are on the next time the function is executed, and replaces the content of the quotes element with the next item in the array.
Most answers here are re initializing your array on each iteration.It makes no sense to do that. You should do it like this:
<script type="text/javascript">
function showLines(){
var arr =
[
"Hi!",
"Welcome!",
"Hello!"
], i = 0;
(function showLinesHelper(){
document.getElementById("quotes").innerHTML += arr[i++]+'<br />';
if(i < arr.length)
setTimeout(showLinesHelper, 2000);
})();
}
</script>
This way it works, and your array, and i are only initialized once.
EDIT In response to comment:
<script type="text/javascript">
function showLines(){
var arr =
[["Hi!", 3000],
["Welcome!", 500],
["Hello!", 1000]]
, i = 0;
function showLinesHelper(){
document.getElementById("quotes").innerHTML += arr[i++][0]+'<br />';
if(i < arr.length)
setTimeout(showLinesHelper, arr[i][1]);
}
setTimeout(showLinesHelper, arr[0][1]);
}
</script>
You never asked him to wait. You're just calling the same function every 2 seconds.
Try with showLines(i), innerHTML += arr[i], and setTimeout(showLines,duration,i++)
<script type="text/javascript">
function showLines(i)
{
arr =
[
"Hi!",
"Welcome!",
"Hello!"
]
var duration=2000;
document.getElementById("quotes").innerHTML += arr[i];
i++;
setTimeout(showLines,duration,i);
}
</script>
First of all, you should wrap your code in an onload or domready function. jQuery is good at this. You should use window.onload = myfunc; to do this.
Your code should look like this:
<script type="text/javascript">
var init = function () {
var myarray = ["Hi!","Welcome!","Hello!"], index = 0, printline = function () {
document.getElementById("quotes").innerHTML += myarray[index];
if (index + 1 < myarray.length) {
setTimeout(printline, 2000);
}
index++;
};
printline();
}
window.onload = init;
</script>

Categories