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.
Related
i just started to learn JS. I want to change my span tag's position with respect to time with JS setTimeout function. But it did not worked with this code. What am i doing wrong ?
function myFunction2() {
var j = 0;
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
var i = 0;
while (i <= 200) {
setTimeout(myFunction2, 20);
i++;
}
You need to declare j outside the function. Otherwise, you're always setting it to 0 every time the function is called.
Also, you're running all instances of the function at the same time, 20 ms after the loop. You should multiply the timeout by the loop index:
Full demo:
var j = 0;
function myFunction2() {
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
var i = 0;
while (i <= 200) {
setTimeout(myFunction2, 20 * i);
i++;
}
}
<span id="demo" style="position:absolute;left:0px;">Bu benim ilk paragrafım.</span><br> <button type="button" onclick="myFunction();">Try</button>
Or you could use setInterval() to run it repeatedly automatically.
function myFunction() {
var j = 0;
var int = setInterval(function() {
if (j > 200) {
clearInterval(int);
} else {
document.getElementById("demo").style.left = j + "px";
j++;
}
}, 20);
}
<span id="demo" style="position:absolute;left:0px;">Bu benim ilk paragrafım.</span><br> <button type="button" onclick="myFunction();">Try</button>
It seems like you are declare the J variable inside the function and set it to 0 every time. So every time when you call the function you're calling the timeout on same interval. And My solution is set the J Out side the function like a global variable and then try it.
var j = 0;
function myFunction2() {
document.getElementById("demo").style.left = j + "px";
j++;
}
function myFunction() {
for (var i = 0; i <= 200; i++) {
setTimeout(myFunction2, 20 * i);
}
}
It is not working because whenever you are calling myFunction2(), variable j is initialized with 0 again and technically you are assigning 0px to demo. So that's why it's not shifting.
As said , you need to declare j as a variable outside the function itself , then you eventually test it within the function .
I would use for (){} instead while () {}
here is another example :
let j;// declare j
function myFunction2() {
if (!j) {// has j already a value ?
j = 0;
}
document.getElementById("demo").style.left = j + "px";
j++; // now it has a value, it can be incremented from here anytime the function is called
}
function myFunction() {
for (let i = 0; i <= 200; i++) {
setTimeout(myFunction2, i * 20);// increment settimeout for each loop
}
}
#demo {
position: relative;
}
<div id="demo">test demo</div>
<button onclick="myFunction()">test myFunction</button>
Now, every time you call the function it increments the position of 200px away from lft. 1 click = 200px , 2click = 400px ;
Have fun coding ;)
Here is my code.
var i = 0;
var submenues = document.getElementsByClassName("submenu");
var click = 1;
function submenuvisible() {
if (click == 1) {
for (i; i < submenues.length; i++) {
submenues[i].style.display = "block";
}
click = 2;
return;
}
if (click == 2) {
for (i; i < submenues.length; i++) {
submenues[i].style.display = "none";
}
click = 1;
return;
}
}
Though when i onclick=submenuvisible() it works only 1 time. What am I doing wrong?
Your mistake is in your for loops.
Where you have: for (i; i < submenues.length; i++) {
You need to reset the variable i to 0 at the beginning of the for loops.
for (i = 0; i < submenues.length; i++) {
If you don't reset it, then i will remain at the same value it was after the first time you run your function. You could improve your code further by not making i a global variable, but overall, I hope this explains your issue.
I've 2 columns with checkboxes when one column is checked all respective are checked likewise in 2nd column but the problem is here, client wants when One column of checkbox is checked then 2nd column will be disable or throw alert message to check only one column at a time?
function SelectAll1(headerchk, gridId) {
var gvcheck = document.getElementById(gridId);
var i, j;
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length - 1; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
for (j = 1; j < inputs.length; j++) {
if (inputs[j].type == "checkbox") {
inputs[j].checked = true;
}
}
}
}
else {
for (i = 0; i < gvcheck.rows.length - 1; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
for (j = 1; j < inputs.length; j++) {
if (inputs[j].type == "checkbox") {
inputs[j].checked = false;
}
}
}
}
}
You can ch
I don't really know what you're trying to do without the HTML but here's a start you can build off.
var selected = $('.check:checked').length;
if (selected >= 1) {
$('.check').prop('disabled', true);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check" checked="checked">
<input type="checkbox" class="check">
<input type="checkbox" class="check">
From the little info given I assume this:
SelectAll1 clear or set all checkboxes in column 1.
SelectAll2 clear or set all checkboxes in column 2.
headerchk is a checkbox when clicked clears or sets all.
Do this change:
After each line in the code where SelectAll1(headerchk, gridId) is called you change it to SelectAll1(headerchk.checked, gridId).
Insert another line below this line with a negation:
SelectAll2(!headerchk.checked, gridId)
After each line in the code where SelectAll2(headerchk, gridId) is called you change it to SelectAll2(headerchk.checked, gridId).
Insert another line below this line with a negation:
SelectAll1(!headerchk.checked, gridId)
You only showed me the code for SelectAll1, so I assume SelectAll2 is the same when you not yet know how to make them different. Correct me if this is not the fact!
Continue by change the function SelectAll1 to the following:
function SelectAll1(header_checked, gridId) {
var gvcheck = document.getElementById(gridId);
var i, j;
for (i = 0; i < gvcheck.rows.length - 1; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
for (j = 1; j < inputs.length; j++) {
if (inputs[j].type == "checkbox") {
inputs[j].checked = header_checked;
}
}
}
}
The else-part and if is eliminated by moving the condition to the assignment that is eiher true or false. The .checked part is moved outside the function.
Do the same change in SelectAll2
Test if it works and report to me!
I have this javascript for loop:
for (var i=1; i <= 2; i++) {
$(".afterglowplayer"+i).click(function () {$.afterglowplayer+i.toggle(this); return false;});
}
I need to increment the number at the end of a jQuery variable name so that I get this:
$.afterglowplayer1.toggle(this);
$.afterglowplayer2.toggle(this);
I have tried using
$.afterglowplayer+i.toggle(this);
and
$.afterglowplayer+"+i+".toggle(this);
But it is not correct way... is it possible to increment the number at the end of a jQuery variable name?
You can use the let keyword
for (let i=1; i <= 2; i++) {
$(".afterglowplayer"+i).click(function () {
$('.afterglowplayer'+i).toggle(this);
return false;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='afterglowplayer1'>Foo</div>
<div class='afterglowplayer2'>Bar</div>
Read up on JavaScript closures.
for (var i=1; i <= 2; i++) {
(function(n) {
$('.afterglowplayer'+n).click(function () {
$('.afterglowplayer'+n).toggle(this); return false;
});
})(i);
}
$['afterglowplayer'+i].toggle(this);
I am attempting to create an online solver for the maximum subarray problem.
https://en.wikipedia.org/wiki/Maximum_subarray_problem
I planned on taking user-input numbers from a textbox and converting them into an int array in JS, however my JS does not seem to be running at all.
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<title> findMaxSum </title>
<script src="findMaxSum.js" type="text/javascript"></script>
</head>
<body>
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p> Enter numbers with spaces, i.e. "1 2 3 4 5": </p>
<input type="text" id="array"> <br>
<button id="sum">findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is: </p>
</body>
</html>
and my JS. note: the map(function(item)) part of the code is intended to break apart the string from the form into an int array.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Currently, when I type in numbers into the textbox and submit, the numbers disappear and nothing happens. Any help is greatly appreciated.
Your array variable is object. You have to split the value of <input type="text" id="array"> not the object element.
var array = document.getElementById("array");
array = array.value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Or simpler:
var array = document.getElementById("array").value.split(" ").map(function (item) {
return parseInt(item, 10);
});
Change your code -
function findMaxSum() {
var array = document.getElementById("array").value.split(" ").map(function(item) {
return parseInt(item, 10);
});
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
var loopSum = 0;
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
loopSum += array[i];
if (currentMax < loopSum) {
currentMax = loopSum;
} else if (loopSum < 0) {
loopSum = 0;
}
}
document.getElementById("answer").innerHTML = "The answer is: " + currentMax;
}
window.onload = findMaxSum;
Problem is you are using button inside form, which is by default of type submit type, that is the reason why the page goes blank, it gets submitted. So either you don't use form tag or make the button as button type.
<button id="sum" type='button'>findMaxSum!</button> <!-- type attribute added -->
Below is the sample updated code, hope it helps you.
"use strict";
function findMaxSum() {
var array = document.getElementById("array").value.split(/\s/);
var max = Math.max.apply(Math, array);
document.getElementById("answer").innerHTML = "The answer is: " + max;
}
window.onload = function() {
document.getElementById("sum").onclick = findMaxSum;
};
<h1> findMaxSum </h1>
<form id="formarray" action="">
<p>Enter numbers with spaces, i.e. "1 2 3 4 5":</p>
<input type="text" id="array">
<br>
<button id="sum" type='button'>findMaxSum!</button>
<br>
</form>
<p id="answer">The answer is:</p>
To achieve the solution of the problem, you need to make following changes.
Update the event binding place
window.onload = function() {
var sumButton = document.getElementById("sum");
sumButton.onclick = findMaxSum;
};
function findMaxSum() {
// remove the update binding code from here
// logic should come here
}
Resolve a JS error
document.getElementById("array").value.split(" ")
Update the html to avoid page refresh (add type)
<button id="sum" type='button'>findMaxSum!</button>
Update the logic to address the problem
var currentMax = 0;
for (var i = 0; i < array.length; i++) {
var counter = i+1;
while (counter < array.length) {
var loopSum = array[i];
for (var j = (i+1); j <= counter; j++) {
loopSum += array[j];
if(loopSum > currentMax) {
currentMax = loopSum;
}
}
counter++;
}
}
Here is a plunker - http://plnkr.co/edit/AoPANUgKY5gbYYWUT1KJ?p=preview