Javascript simple UDF - javascript

I'm now developing one JS UDF which seems following coding.
<script>
<!--
function alertmsg()
{
alert("Hello World");
}
for(p=1; p <= 2; p++)
{
alertmsg();
}
-->
</script>
Normally, Alert Msg will be came out two times because of loop count is 2. What I want is Alert Msg will be came out only one time even loop count is 3. Any idea will be appreciated in advance.

You only want to execute the piece of code once in the loop? Do something like this:
var executed = false;
for(var i = 1; i <= 2; i++)
{
if (!executed) {
alertmsg();
executed = true;
}
}

Or perhaps this?
<script type="text/javascript">
function alertmsg() {
alert("Hello World");
}
for (var p = 0; p < 3; p++) {
if (p == 2) {
alertmsg();
}
}
</script>

Related

How to increment a number within a variable name in jQuery

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

Cant get my foor loop working

Why isn't this working?
var i = 0;
for (i < 1) {
if ($(".button[name=commit]").val() == "remove"){
i = 1;
}
}
I get this error message saying: unexpcted token ) at line 2.
Here you go with a solution using while loop
var i = 0;
while (i < 1) {
if ($(".button[name=commit]").val() == "remove"){
i = 1;
}
}
Here you go with a solution using for loop
for (var i=0; i<1;) {
if ($(".button[name=commit]").val() == "remove"){
i = 1;
}
}
Hope this will help you.
while(!$(".button[name=commit]").val() == "remove");
it was not working since for() needs 3 commands: Initialization, guard and last action: for(init;guard;action)

Simulate the look of typing, not the actual keypresses, in javascript

I'm trying to write a simple function that will make it appear as though someone is typing in a textarea
-- This is my function (forgive me if its atrocious, but I don't normally use javascript) ---
The console.log() part works fine, but for some reason I cannot get this script to update the dom the way I would expect...
function type(string) {
value = "";
el = document.getElementById("typeArea");
for (var i = 0; i < string.length; i++) {
value += string[i];
//$("#fbw > textarea").val(value);
el.textContent = value;
console.log(value);
sleep(160);
}
sleep(2000);
}
I appreciate any insight you can give me.
jsFiddle Demo
All you were missing was a construct instead of Sleep. The js approach for accomplishing this is to use a timeout and a recursive call in order to iterate through your string
function type(string,element){
(function writer(i){
if(string.length <= i++){
element.value = string;
return;
}
element.value = string.substring(0,i);
if( element.value[element.value.length-1] != " " )element.focus();
var rand = Math.floor(Math.random() * (100)) + 140;
setTimeout(function(){writer(i);},rand);
})(0)
}
You can do something like this using setTimeout function.
Codepen
$(function(){
simulateTyping('looks like someone is typing...', '#txt')
function simulateTyping(str, textAreaId) {
var textArea = $(textAreaId);
var currentCharIndex = 0;
function typeChar(){
if (currentCharIndex >= str.length)
return;
var char = str[currentCharIndex];
textArea.val(textArea.val() + char);
currentCharIndex ++;
setTimeout(typeChar, 500);
}
typeChar();
}
})

javascript function doesn't return any result

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.

Scoring a Javascript Quiz Script

Hi I some javascript code written to quiz the user on 5 questions and then in theory output their score. As far as I can tell the questions are being scored, I just can't figure out how to output the response. I am having no issues fetching the correct html elements and displaying them. I believe the issue is in the looping elements of the window.onload function. The code is below,
<script type="text/javascript">
var rand = 0;
var right = 0;
window.onload = function () {
reset();
Rrand();
var rangQ = document.getElementById('area').getElementsByClassName('divide');
correct = document.getElementsByTagName('a'), i = 0;
for (i; i < correct.length; i++) {
if (correct[i].className == 'correct') {
correct[i].onclick = function () {
right++;
reset();
Rrand();
}
}
else if (correct[i].className != 'correct') {
correct[i].onclick = function () {
right--;
reset();
Rrand();
}
}
}
}
function Rrand() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
rangQ[rand].style.display = '';
rand++;
}
function reset() {
var rangQ = document.getElementById('area').getElementsByClassName('divide');
for (var i = 0; i < rangQ.length; i++) {
rangQ[i].style.display = 'none';
}
}
document.write(right);
</script>
window.onload is not executed immidiately. you are writing output, but variable right is changed after that.
you need to either move line
document.write(right);
into window.onload as last line (or after loop) or figure out other way that will be best for you

Categories