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>');
Related
I am trying to use an if statement inside of another if statement and I simply can't figure out how to get the second if statement to work. The second if statement applies all style changes to the first element (school) in the array. I would like the second if statement to apply the correct styling to all items in the array based on the json data ([school.status]).
I've tried switching to a for statement, tried moving the if statements around and nesting them differently, tried async and moving different parts of the formulas in and out of the code blocks. I've tried running a second forEach statement after the append but I couldn't get that to work either. I think I lack an understanding of how this process works, beyond just the code part, but more the logical operator, and after hours of searching for a straight forward answer, and it being almost 4AM, I figured I would just ask here.
schools.forEach(function(school, index) {
dashboardItemStatus = $(".dashboard-item-status");
if (App.hasClass("mainDash")) {
App.append(
'<div class="dashboard-item"><h5 class="mb-1">' +
[school.name] +
"</h5>" +
'<p style="margin-bottom: -2px">' +
[school.address.street] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.address.city] +
"," +
" " +
[school.address.state] +
" " +
[school.address.zip] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.phone] +
"</p>" +
'<p style="margin-bottom: -2px">' +
[school.principal] +
"</p>" +
'<p style="margin-top: 8px;background-color: #FFF;padding: 8px 14px;border-radius: 5px;" class="dashboard-item-status" id="dashboardItemStatus">' +
[school.status] +
"</p>" +
"</div>"
);
}
if (school.status == "Normal Operation") {
dashboardItemStatus.addClass("dashboard-item-status-normal");
} else if (school.status == "Full Change") {
dashboardItemStatus.addClass("dashboard-item-status-change");
}
});
So, I suppose the expected results are anytime one of the statuses is "Full Change" the dashboard-item-status-change class is applied, and the dashboard-item-status-normal class is applied to any status that has "Normal Operation". That data is an array that is coming from a json file. That part works just fine. The forEach function works fine and the information displays correctly on the screen. Now though, I need to be able to affect the elements that show the status individually based on the status itself. Right now, as stated above, no matter what status I attempt to affect, the channges all occur on the first element in the array, which I guess makes sense, but I have no idea how to fix it. If I console.log() the names and statuses of the schools inside the second if statement, they display correctly so I know I can find the right values, I just don't know how to affect them. Maybe map or something may work but I honestly don't know how to use that correctly. Any help is really appreciated.
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"
I have a simple web page where I dynamically add new text elements with a JS function. However I want the displayed text to retain its leading whitespace (so I can do print several lines with controlled indentation). It is currently rendered without it (I can still see it in the inspector). This is my message adding function: (The first parameter is a CSS hint)
function printMessage(cls, text){
var cont = document.getElementById('container');
cont.insertAdjacentHTML('beforeend', '<div class="' + cls + '">' + text + '</div>');
window.scrollTo(0,document.body.scrollHeight);
}
A typical call might be printMessage('help', ' Type help to get help');. The two leading spaces in the second argument are not shown. Any clues?
I checked a lot on Hrefs but couldn't get something related.
I am trying to do this in code behind which is actually a custom control class
writer.Write("<a href='javascript:document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
now this gets me something like this on hover of above anchor 'document.location.href?Test one=2013' and when i click it, this throws an obvious javascript error 'SyntaxError: missing : in conditional expression' because it takes it as a conditional operator and hence finds : missing.
I simply want that document.location.href (current url) should be calculated and the value put in where i use it.
I know that i may simply call a javascript function and inside that function i set the href but can i do it this way?
Try this:
writer.Write("<a href='javascript:window.location = document.location.href?" + filter.ParameterName + "=" + filter.QueryValue + "'>" + filter.UserVisibleValue + "</a>| ");
Note that you might have to escape values as needed otherwise JavaScript will become invalid. To prove that above approach works, you can copy-paste following simpler example in any HTML page and see it working:
bla
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
}