Form text field variable is showing undefined in Javascript - javascript

This is my first post, anyway I'll get straight to the point.
I have a form that when a user writes they're name in, Javascript saves the value to the global variable "ch_name". When I access this variable through an alert at any point on the site it always shows the correct value that I entered. However, it only works for alerts, when I try reference the user by using the variable it always shows as undefined.
I've tried re-ordering the code in case it hadn't loaded correctly and this hasn't yielded any results either. I've begun wondering whether I've referenced it right at all as I'm still fairly new to JavaScript.
As you'll probably find out my code is a mess but here's what I've got.
var ch_name; //my global variable
var data = new Array(); //I've taken a snippet out of an array of 8.
data[0] = '<p>Question 1</p>' + ch_name + "\n" + //ch_name is referenced on this line.
'<button onclick="results1()">Click Me</button>' + "\n" +
'<button onclick="results2()">Click Me</button>' + "\n" +
'<button onclick="results3()">Click Me</button>';
function charName(form) { //This is the code that changes the global variable ch_name.
ch_name = document.nameform.user.value;
ranData = Math.floor(Math.random() * data.length);
document.getElementById("placeholder").innerHTML = data[ranData];
}
The html snippet:
<form NAME="nameform" method="GET">
<p>Enter your character name:</p> <input type="text" name="user" value="" />
<input type="button" value="Start" onClick="charName(this.form)"/>
</form>
<div id="placeholder"></div>
Referencing the ch_name through an alert anywhere gives me the correct result, blank on page load and after the string is entered it gives the correct name. But anytime I reference it through the array variable it shows an undefined. This is not the full code but I'm certain there's no conflicts in variable names etc. I've scanned it a good few times, I'm certain it's just me being an idiot.
Is there a work around for this? I'm in a place ready to drop the whole code behind ch_name entirely to focus on other areas of the page.
Thanks for reading and any help.

I think that your problem is that when your data array is generated, ch_name doesn't have a value, so it comes out as blank. Even when you change ch_name, the data value won't be re-generated with the correct value.
A solution to this might be having a regenerate_data function that re-generates your data data array whenever you change the global character name.

The data won't change the way you seem to think.
I think for you the best bet would be to replace data Array with a function.
Now the ch_name parameter will be created dynamically every time you run the function. i.e. every time the button is pressed, which will update the data.
How do you change the data in a page?
var ch_name; //my global variable
function charName(form) { //This is the code that changes the global variable ch_name.
ch_name = document.nameform.user.value;
ranData = Math.floor(Math.random() * data.length);
document.getElementById("placeholder").innerHTML = getranData(ranData);
}
function getranData(num){
if(num==0)
return '<p>Question 1</p>' + ch_name + "\n" + //ch_name is referenced on this line.
'<button onclick="results1()">Click Me</button>' + "\n" +
'<button onclick="results2()">Click Me</button>' + "\n" +
'<button onclick="results3()">Click Me</button>';
else if (num==1) ; ///...and so on
}

Related

javascript compute mistake (calculator)

I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.
First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.
You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>
Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;

jquery dynamically generated .append() sometimes appends to wrong div

I have a block of jquery that builds a form with more than 40 element using a loop to .append() div elements that load .ajax() json.
9 out of 10 times the form renders as expected. However randomly some of the elements will suffer from two types of errors
the dom element will be created but not displayed (does not show in source)(on deeper investigation, it seems the elements are always generated, just wrong parent (2))
the dom element is placed as a child to the wrong parent.
for example below, id3 should be attached to delta[14] but is instead generated at beta[3] OR id3 should be at gamma[6] but does not display at all
the format of build is
hard code
<div id="alpha">
<div id="beta"></div>
<div id="gamma"></div>
<div id="delta"></div>
</div>
doAppendStuff(beta, ajaxUrletc1);
doAppendStuff(beta, ajaxUrletc2);
...
doAppendStuff(gamma, ajaxUrletc10);
doAppendStuff(gamma, ajaxUrletc11);
...
doAppendStuff(delta, ajaxUrletc20);
doAppendStuff(delta, ajaxUrletc21);
dynamic
function randId(baseID) {
return baseID+"_"+Math.round(new Date().getTime() + (Math.random() * 555));
}
var id1= randId("myIdOne");
var id2= randId("myIdTwo");
var id3= randId("myIdThree");
function doAppendStuff(elemId, ajaxUrletc){
$('#' + elemId).append(
'<div id="' + id1 + '" >' +
'<div id="' + id2 + '">' +
'<select id="' + id3 + '"></select>' +
'</div>' +
'</div>'
);
... // log id1, id2,id3
... //do .ajax stuff + callback on id3
I have added callbacks to each loop to ensure that the .append is fired and no errors are generated complaining that the element does not exist.
Running a trace I can see the dynamic id for each element is being generated.
The code itself works as expected as the other 9/10 times it renders as expected.
notes
The random errors apply to different elements each time. no particular logic on what element fails.
I have separated the ajax calls from the dom element creation so there should be no bottleneck on the element creation
All ajax calls are initiated as expected in the correct order. Some take longer but the other elements generate as expected without waiting. All data is successfully returned.
Is there any know issues with generating multiple dom elements by calling the same function repeatedly OR is there a listener I could add to ensure the element is correctly generated in the desired position before proceeding to the next call via a callback.
UPDATE
After adding logging of the id1,id2,id3, the logs confirm that the correct dynamic ids are being assigned. It seems however that either the var in memory is being replaced with a previous value or the js engine is placing in the wrong generated position due to timing.
UPDATE 2
After some more debugging, we changed the random string and upped the number from
return baseID+"_"+Math.round(new Date().getTime() + (Math.random() * 555));
to
return baseID+"_"+Math.round(new Date().getTime() + (Math.random() * 99999));
and the problem has not reoccurred. So it looks like it could be either a random ID collision with the same string being generated twice or somehow reused when the function is reinitialised. The interesting thing is the ID's are not sequential, it will often skip several rows before reusing the same ID.
So we have cured the problem, but still do not understand what caused the issue, any thoughts are welcome.
If you want a unique value, then we're talking about GUID's.
Create GUID / UUID in JavaScript?
However, if you would have placed an underscore or other value between the time and random number, I'd suspect you'd have seen fewer collisions.
time + random = some future period in time.
Imagine getting a random 100 and then 100 ms later getting a random 0.
"abc1506110581013_100" != "abc1506110581113_0"
while
"abc1506110581113" == "abc1506110581113"

Unclear code in Javascript

I spent 4 hours trying to figure out what's going on in the following code. I can hardly understand it, since I haven't programmed Javascript yet.
Javascript:
function pincheck() {
var n = 123456789123,
t = md5(n + " " + $("#wert").val()),
e = $("input[name='some_hash']").val();
$.post("https://url-test.com/site?check=" + t, {some_hash: e}, function(n) {
$("#inputWert").html(n == t ? "<span style='color:green; font-weight:bold'>OK</span>"
: "<span style='color:red; font-weight:bold'>NOT OK</span>")
})
}
Corresponding HTML-form:
<form action="https://url-test.com/site" method="post" accept-charset="utf-8">
<div style="display:none">
<input type="hidden" name="some_hash" value="2cb6beab7ac4240043b20674a3dce6a5" />
</div>
<input type="text" id="wert" name="wert" placeholder="WERT" onchange="pincheck()">
<div id="inputWert">Please input</div>
<input type="submit" value="Submit" />
<h2>Please explain<br/><textarea name="explain" style="width: 650px;height: 100px;" placeholder="Explanation"></textarea><br/>
</form>
My thoughts were:
The function pincheck() checks if n==t
But since t is a md5 hash, it
can never be equal to n, which is a digit number.
Is this correct? If wert=000, will be the value of the variable "t" an MD5 of the string "123456789123 000"? I hope I explained correct.
The background of my question refers to our university IT-security task. We have to guess some number, and then enter it into the text form, whos id should be "wert" I guess.
I hope someone can help me. Thank you in advance!
When the user types something into the WERT input field, the Javascript takes the user's input, puts 123456789123 at the beginning of it, calculates the MD5 hash of this, and assigns that to t. e is set to the contents of the hidden some_hash value.
Then it performs an AJAX query, sending t and e to the url-test.com/site script. t is sent in the check URL parameter, while e is sent in the some_hash POST data.
The server script returns back a string. If that string matches t, then it displays a green OK. If they don't match, it displays a red NOT OK.
My guess is this is part of a CAPTCHA test. The hidden input is a code that indicates which image was displayed. On the server, this code can then be used to look up the MD5 hash of the text in the image.
Simply, the Javascript is setting 3 variables (using the var keyword), then making an HTTPS POST call using jquery.
Picture the code like this line by line:
// Set n to a seemingly arbitrary number
var n = 123456789123;
// Set t to an MD5 hash using n and whatever the value of the "wert" element is
var t = md5(n + " " + $("#wert").val());
// Set e to the value of the element with a name of "some_hash"
var e = $("input[name='some_hash']").val();
// Makes a POST call to a URL built using the above variables
// Format $.post(URL, data(in JSON format), callback function)
$.post(
"https://url-test.com/site?check=" + t,
{some_hash: e},
function(n) {
// Set the HTML body of the "wert" element
// If n (returned by the POST call) is equal to t, set font color to green, otherwise set font color to red
$("#inputWert").html(n == t ? "<span style='color:green; font-weight:bold'>OK</span>" :
"<span style='color:red; font-weight:bold'>NOT OK</span>")
}
);
Let's take your code in pieces: the "pincheck" function starts out by setting three variables: n (123456789123), t. which uses the javascript MD5 hash function with an initial string of n + some spaces + whatever value you enter into the "wert" field on your form. Finally, you retrieve the value of a hidden field called "some_hash" and store that in the variable "e"/ You then initiate a post to your server passing a key-value pair of "some_hash" (the key) and the value of the hidden field. When the post returns, it calls the anonymous function at the end of the post statement, passing in the returned value from the post operation as the (local to the anonymous function) variable "n". This "n" is a different variable from the one defined at the opening of the pincheck function. The anonymous function then checks to see if the value returned from the post operation is the same as the one calculated using the javascript MD5 function. If they are the same, then the first span tag is displayed, if they are not equal, then the second span tag is displayed. Hope this helps.

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Javascript- Setting Input Value

EDIT: As this question turned out to be quite a bit different than originally stated, please refer instead to HTML- Altering Input Value
I have an input element that I am trying to set while I'm creating a pair of tables (the value should reflect the total value of the row). However, the statement is not working for some reason. The basics of the code are as follows:
prevTotalElt = $('#TimeSheetTable #ProjectData #projectBody #' + curProj + '_total');
alert(prevTotalElt.val() + '\n' + prevTotalVal);
prevTotalElt.val(prevTotalVal);
This code is in an if statement, and the alert message appears as expected with the proper values. The weirdest bit is that the same statement executes at the end of the loop (to take care of the final total element in the table) and works perfectly. I can't really understand what the issue is here, but any help would be appreciated.
EDIT: Due to requests, here is the line that creates the input element I am trying to set:
$('#TimeSheetTable #ProjectData #projectBody').html($('#TimeSheetTable #ProjectData #projectBody').html() +
'<tr><td align="center"><input id="' + curProj + '_total" type="number"' +
'align="center" value="' + tmpInd + '" style="width:17px; border:none;" disabled></td>');

Categories