Assigning a value to a variable randomly, but not working - javascript

Im trying write JavaScript code which will generate a random number through a function then use that random number (between 1 and 6) to assign a value to the variable "background".
This is what I have:
function genBackground() {
var x=Math.floor((Math.random()*6)+1);
assignBG(x);
alert("test alert");
}
function assignBG(x) {
if (x === 1){
var background=blue;}
else if (x === 2){
var background=green;}
else if (x === 3){
var background=red;}
else if (x === 4){
var background=purple;}
else if (x === 5){
var background=yellow;}
else if (x === 6){
var background=orange;}
}
The alert "test alert" doesn't show, but does if but before the line "assignBG(x);". Have I done this bit wrong?

Are those "colors" defined previously in the code? Otherwise, you should write color = "white" and so on...
I'd also rewrite assignBG like this:
function genBackground() {
var x=Math.floor((Math.random()*6)+1);
var color = generateBG(x);
alert(color); // and do whatever you like with this color
}
function generateBG(x) {
var colors = ["blue","green","red","purple","yellow","orange"];
return colors[x];
}

Related

JavaScript (If statement) to insert image based on a value

I am using AutoMailMerge and I am trying to add a JavaScript to check if a field value is "1" then insert image in the image field.
var f = this.getField("Image1_af_image");
if (f.value == "1")
{
f.buttonImportIcon("C:/Users/EslamSamy/Desktop/MEWA Project/Files/Circles/Circle1.png");
} else if (f.value == "2")
{
f.buttonImportIcon("C:/Users/EslamSamy/Desktop/MEWA Project/Files/Circles/Circle2.png");
}
This link contains 3 processed files with this above code with 3 diffrent values for "Image1_af_image".
https://gofile.io/d/qMvnfu
This could help ;)
f.buttonImportIcon("C:/Users/EslamSamy/Desktop/MEWA Project/Files/Circles/Circle"+ f.value+".png");
This worked now : )
var f = this.getField("Image1_af_image");
var n = this.getField("Number");
if (n.value == "1")
{
f.buttonImportIcon("C:/Users/EslamSamy/Desktop/MEWA Project/Files/Circles/Circle1.png");
} else if (n.value == "2")
{
f.buttonImportIcon("C:/Users/EslamSamy/Desktop/MEWA Project/Files/Circles/Circle2.png");
}

javascript recursive function does not stop execution

Inside of my progress function, it will hit the base of the recursion, but the value im expecting to have returned does not change.
let graph = [[1,1,1],[1,1,1,],[1,1,1]]
function findPath(graph){
function progress(row, col){
if(row == graph.length-1 && graph[row][col]== 1) {
console.log('makes it here but does not return true !?')
return true;
}
//check right
if(graph[row][col+1] == 1) {
graph[row][col] = 2
progress(row, col+1);
}
// check left
if(graph[row][col-1] == 1) {
graph[row][col] = 2
progress(row, col-1);
}
// check down
if(graph[row+1][col] == 1){
graph[row][col] = 2
progress(row+1, col)
}
}
for(let i = 0; i < graph[0].length; i++) {
if(graph[0][i] == 1) {
if(progress(0, i)) {
return true;
}
}
}
return false;
}
console.log(findPath(graph))
This should return true, it hits the condition (logs the text) but then keeps moving, and always returns false.
Ok, recursion works with an stack, each call is stacked and just continues your execution after all the other call stacked after are done.
Like:
call1 -> call2 -> call3 -> callN
after reach the last call (callN), all the calls will be unstacket from back to front.
You just return true on the last call, but this value get lost when the function calls is unstacked
In other words, to your example works, you need to always return the value from the progress function.
I tried to adapty your code to work better:
let graph = [[1,1,1],[1,1,1,],[1,1,1]]
function findPath(graph){
function progress(row, col){
if(row == graph.length-1 && graph[row][col]== 1) {
return true;
}
//check right
if(graph[row][col+1] == 1) {
graph[row][col] = 2
var right = progress(row, col+1);
}
// check left
if(graph[row][col-1] == 1) {
graph[row][col] = 2
var left = progress(row, col-1);
}
// check down
if(graph[row+1][col] == 1){
graph[row][col] = 2
var down = progress(row+1, col)
}
// propagate result
return (right || left || down)
}
for(let i = 0; i < graph[0].length; i++) {
if(graph[0][i] == 1) {
if(progress(0, i)) {
return true;
}
}
}
return false;
}
console.log(findPath(graph))
I only look to the recursion part, and not for the problem it self, in my example, if in any path (right, left or down) i grab that value and pass back untill it reach my first function call. That way, the true value will be propagate until the end
Hope i have helped

Trouble with basic javascript

I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.

counting checkboxes from an javascript function

This JavaScript function is in the webpage I am calling:
function getChecked(button, form) {
var name;
for (i = 0; i < document.forms['CheckForm'].list.length; i++) {
name = "Check" + (i+0);
if(document.forms['CheckForm'].list[i].checked == true) {
if(name == "Check0")
form.Check0.value = "2437315";
else if(name == "Check1")
form.Check1.value = "2437104";
else if(name == "Check2")
form.Check2.value = "2434936";
else if(name == "Check3")
form.Check3.value = "2434574";
else if(name == "Check4")
form.Check4.value = "2433541";
else if(name == "Check5")
form.Check5.value = "2426021";
}
Sometimes there are 6 checks, sometimes 7 sometimes 3, I need help in counting how many Check(Somenumber) there is and then build an post field with Check0=0&Check1=0&Check2=0 and so on.
I am not setting each check to different value, I need to count how many Checkboxes there are and then set them to 0, I am using PHP to cURL the page.
In javascript you can do something like this:
var form = top.document.forms.CheckForm;
var numFormElements = form.length;
var counter = 0;
for( i = 0; i < numFormElements && !foundItem; i++ )
{
var obj = form[i];
if( obj.type == 'checkbox' )
{
counter++;
}
}
alert( counter ); // or whatever else
I should add... I don't think that there's any way that a server-side language can know the type of input. That information has to be grabbed from the user's web browser through a client-side means.
You could just simply build the string as you go. There are other ways to do this (which I would suggest using jQuery with it and cycling through using "this"). Here is what I would do with your existing code.
//set a string
var values = '';
if(name == "Check0") {
form.Check0.value = "2437315";
values += 'Check0=' + form.Check0.value;
} else if(name == "Check1") {
form.Check0.value = "2437315";
values += 'Check1=' + form.Check1.value;
}

Next/Previous button throws error

I keep getting the following error when I try to insert values by clicking the Next button on values that are already entered in.
Unable to get the value of the property '0': object is null or undefined.
I believe the error is happening at the last value in the array. I indicated the line below with a comment in the code. I want it to get the next value in the array but there isn't one created yet (it gets the next value just fine if the next value is not the last one in the array).
I think that is the reason it's throwing an object null. However, I can't seem to check for the null/undefined and set it using statements such as result[count+1][0] == undefined because it doesn't work! It always throws an error no matter what I do.
Some help would be much appreciated.
Test case:
Insert a value in text box 1 and text box 2
Click Next
Click Previous (in order to edit the values inserted above)
Change the values in the text boxes to something else
Click Next -- error happens
Code:
<html>
<head>
<script type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
var result = new Array();
var count = 0;
var input1 = new Array();
var input2 = new Array();
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
</script>
<li>text 1</li>
<input type="text" id="txt1"/>
<br>
<li>text 2</li>
<input type="text" id="txt2"/>
<br>
<input type="button" id="btn" value="next" onclick="move('next')" />
<input type="button" id="btnprevious" value="previous" onclick="move('prev')" />
<br>
<input type="text" id="txtresult"/>
</body>
</html>
You can add a check like this:
if (typeof result[count++] === "undefined") { /* do or do not */ };
Right before:
document.getElementById("txt1").value = result[count++][0];
function move(direction) {
if(direction == 'next')
{
var rate1 = [document.getElementById("txt1").value];
var rate2 = [document.getElementById("txt2").value];
if (result.length == count){
if (rate1 == '' || rate2 == '') {
alert('you need to put in a value');
}
else {
result.push([[rate1], [rate2]]);
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count++;
}
}
else {
try{
(result[count][0]) = document.getElementById("txt1").value;
(result[count][1]) = document.getElementById("txt2").value;
if( result[ ++count ] ) // this checks for undefined
{
document.getElementById("txt1").value = result[count][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count][1];
}
else
{
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
count--; // decrement counter
}
}catch(err) {
alert(err.description);
}
count++;
}
}
if (direction == 'prev')
{
if(count <= 0)
{
alert("no more elements");
}
else
{
var prev_val1 = (result[count - 1][0]);
document.getElementById("txt1").value = prev_val1;
var prev_val2 = (result[count - 1][1]);
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}
why do you do count++ in these 2 lines?
document.getElementById("txt1").value = result[count++][0]; //error happening here. trying to show next value but there isn't one created yet.
document.getElementById("txt2").value = result[count++][1];
seems like interpreter first increment the count and then try to get item of result which is undefined...
as i undestand pressing previous must "set cursor" to previous vaues so you can change previously entered values... in this case you shouldn't increment counter in these lines.. just remove ++
I don't get why you embedded the arrays three deep. I cleaned up some of the code and made the names more understandable (at least to me).
Regardless, when you were on the last value in the array, count++ didn't exist. Also, don't use count++ as this will increment your count var. Don't use ++ to simplify unless you truly know what you're doing and want to increment. Also, tricky shortcuts will confuse people trying to read your code, so try to be as explicit as possible. (There are exceptions to this statement, as in, you don't need to write for a person who has never coded before)
Here is working javascript:
var result = new Array();
var count = 0;
function move(direction) {
if(direction == 'next') {
var box1 = document.getElementById("txt1").value; //why did you wrap these as arrays?
var box2 = document.getElementById("txt2").value; //
if (result.length == count){
if (box1 == '' || box2 == '') {
alert('you need to put in a value');
} else {
result.push([box1, box2]); //why did you wrap individual numbers in arrays?
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
} else {
try{
result[count][0] = document.getElementById("txt1").value;
result[count][1] = document.getElementById("txt2").value;
if(result[count+1]) { // need this because if on last value in the array, count+1 will not exist yet
document.getElementById("txt1").value = result[count+1][0]; //do not do ++. this will increment count here. don't be tricky with ++
document.getElementById("txt2").value = result[count+1][1]; //because it will confuse others and lead to off by 1 errors
} else {
document.getElementById("txt1").value = '';
document.getElementById("txt2").value = '';
}
}
catch(err) {
alert(err.description);
}
}
count++;
}
if (direction == 'prev') {
if(count <= 0){
alert("no more elements");
} else {
var prev_val1 = result[count - 1][0];
var prev_val2 = result[count - 1][1];
document.getElementById("txt1").value = prev_val1;
document.getElementById("txt2").value = prev_val2;
count--;
}
}
document.getElementById("txtresult").value = result;
}

Categories