GetElementbyID and Innerhtml not working [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
I don't know what I'm doing wrong. This is a 2 part question. Please see code below. First, it keeps saying that the variable capitals is null. Second, I'm unable to get innerHTML working. I'm not sure why it isn't working. I know I have document.write which I'm not suppose to use so I'm working on understanding getElementbyId.innerHTML to work.
HTML
<form name="shares">
<table>
<tr><td>Enter information here:</td></tr>
<tr>
<td>Capital to Invest</td>
<td id="capitalr"><input type="text" name="capital"> </td>
</td>
</tr>
<tr>
<td>Price per share</td>
<td><input type="text" name="price" onchang="calculate();"></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Compute" onclick="calculate()"></td>
<tr><td>The quantity you can be:</td></tr>
<tr>
<td>No. of shares</td>
</tr>
<tr>
<td>Change</td>
</tr>
</table>
<p id="hello"></p>
</form>
JavaScript
var capitals = document.getElementById("capitalr");
var x = capitals.id;
var pps = document.shares.price.value;
function calculate () {
document.write("Capital = " + capitals +"<br>");
document.write("Price per share is = " + pps);
}
document.getElementById("hello").innerHTML="Hello";

1) The <tr> for your button doesn't have a </tr>.
2) There's a timing problem -- you need to put your code in a function that executes at onload time.
<body onload="fnonload();">
I suggest you use "console.log" statements as a debugging tool to see how your code is progressing. That's helped me a lot.

Related

Is there anyway to show serial number in a table? [duplicate]

This question already has an answer here:
How to display the index data in a *ngFor?
(1 answer)
Closed 1 year ago.
I'm currently new angular, so if there is any mistake in my implementation then please let me know,
This my HTML code from component.html file
<table id="table">
<tr>
<th>Sl.No.</th>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Skill</th>
<th>Gender</th>
</tr>
<tr *ngFor = " let i of counter()">
<td></td> <!-- To print the serial number here -->
<td>{{nameFromLocalStorage}}</td>
<td>{{emailFromLocalStorage}}</td>
<td>{{phoneFromLocalStorage}}</td>
<td>{{skillFromLocalStorage}}</td>
<td>{{genderFromLocalStorage}}</td>
<td>
<button (click)="delete()" ><img src="./assets/icon/trash.png"></button>
</td>
</tr>
</table>
Here is code for counter() from component.ts file
counter() {
//TO DO
//Implementation is remaining,
return new Array(20);
}
The counter is supposed to return a value, the value is to be captured by the html file in the *ngFor directive and based on that it should create the required number of rows. Then I wanted to display the serial number in the first column of the table.
According to the code above I'm able to get 20 rows.
Note:- I have seen the solution in CSS and doesn't wish to implement until its the only option left.
My question is that how do I get the serial number there.
From my understanding i in the *ngFor directive should starts from zero so, is there anyway to directly display the value of i it self.
I'll be very glad if you can help me learn and correct my mistake.
Thank you in advance.
Yes you can loop it as simple dont know what your serial no is, if its from array then just use CounterArr.Serial_No.
<tr *ngFor = " let CounterArr of counter();let i = index;">
<td>{{i+1}}</td>
<td>{{CounterArr.nameFromLocalStorage}}</td>
<td>{{CounterArr.emailFromLocalStorage}}</td>
<td>{{CounterArr.phoneFromLocalStorage}}</td>
<td>{{CounterArr.skillFromLocalStorage}}</td>
<td>
<button (click)="delete()" ><img src="./assets/icon/trash.png"></button>
</td>
</tr>

JavaScript getElementByID() for HTML Table [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 months ago.
Learning Javascript at the moment, so please bear with me. I created a table in my connected.html and I am trying to obtain the element between the <td> tags in my event-page.js. I used document.getElementByID("tokens"), however I get null, I want to get 12. I think I have to do more with document.getElementByID("tokens") I used .innerText and .innerHTML but those didn't work. Any help would be appreciated! Sorry for such a simple problem.
*Note: The function in event-page.js is called when a button is clicked by the user.
connected.html
<html>
<head>
</head>
<body>
<table>
<tr>
<td colspan="4" class="info">Tokens</td>
</tr>
<tr>
<td id="tokens">12</td>
</tr>
</table>
</body>
</html>
event-page.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse){
if (request.action.split(':')[0] === 'got-it'){
yt_name = (request.action.split(':')[1])
console.log(yt_name)
let table = document.getElementById("tokens")
console.log(table)
}
})
This Works, that means your EventListener are called before the DOM is loaded.
let table = document.getElementById("tokens")
console.log(table)
<table>
<tr>
<td colspan="4" class="info">Tokens</td>
</tr>
<tr>
<td id="tokens">12</td>
</tr>
</table>

Unable to access a dynamically generated dropdownlist item. It comes as undefined

I am working on a webpage which has a tabstrip depending on number of people in a deal. As it can be 1 for one deal and 3 for another, I have created the drop down items dynamically using a loop index.
<tr>
<td align="right">
<spring:messagecode="label.borrower.employer.status" />:
</td>
<td align="right">
<kendo:dropDownList name="employmentStatus${requestScope.loopIndex}"
dataTextField="text" dataValueField="value" style="width: 100%;"
select="employmentStatusOnClick(${requestScope.loopIndex})"
change="updateEmploymentInfo">
<kendo:dataSource data="${borrowerEmploymentStatus}"></kendo:dataSource>
</kendo:dropDownList>
</td>
I am able to see the drop down lists according to the number of people in a deal. However, this jsp is included in another main jsp and the "change" and "select" functions are in that main jsp. When a value is selected on a drop down, I want to capture it and then perform some operations.
<script>
function employmentStatusOnClick(index) {
console.log(exp.loopCounter);
console.log("counter: "+index);
var employmentStatusVal = $("#employmentStatus"+index).data(
"kendoDropDownList").text();
console.log(employmentStatusVal);
}
</script>
For output, I can see that the value of index is coming correctly. However, even before the page is fully loaded, i get the error that "TypeError: Cannot read property 'text' of undefined"
Things I have Tried So far:
1) Tried to add the script inside ready() function, but it then gives me an error that employmentStatusOnClick is not defined
2) Tried different variations of concatenating the index value with the base name of the drop down list
3) Tried passing the value into a variable and then putting it into the .text() function
4) Latest, I have even tried hardcoding the value of index as 0 to see if it works for the first case, but i still get the undefined error.
I suspect that it has to do something with the loading of the elements. For some reason, it is trying to run this code, even before the element name has been generated. I discussed with a friend and he suggested me to remove the select events and just use the change event instead. Tried that..no effect.
Now, I am planning to remove kendo drop-downs and just use javascript dropdowns as a last resort. Can you please suggest what could be the problem?
Update - HTML Code of the div from Browser:
<div id="tab-employment">
<table>
<tbody><tr>
<td>
<table border="1">
<tbody><tr>
<th>Employer Name</th>
<th>Occupation</th>
<th>Employment Status</th>
<th>Hiring Date</th>
</tr>
<tr align="center">
<td>Roagres</td>
<td>Assistant</td>
<td>Current</td>
<td>2018-03-12 11:59:06.0</td>
</tr>
</tbody></table>
</td>
<td style="width: 1%"></td>
<td>
<table style="display: inline-block;">
<tbody><tr>
<td align="right">Employment Status:</td>
<td align="right"><input name="employmentStatus0" style="width: 100%;" id="employmentStatus0"><script>jQuery(function(){jQuery("#employmentStatus0").kendoDropDownList({"dataTextField":"text","dataValueField":"value","change":employmentStatusOnClick(0),"dataSource":{"data":[{"text":"--Select--","value":"--Select--"},{"text":"Employed","value":"Employed"},{"text":"Self-Employed","value":"Self-Employed"},{"text":"Retired","value":"Retired"},{"text":"Seasonal","value":"Seasonal"},{"text":"Student","value":"Student"},{"text":"Unemployed","value":"Unemployed"},{"text":"TEST","value":"TEST"}]}});})</script></td>
</tr>
<tr>
<td align="right">Industry Sector:</td>
<td align="right"><input name="industryStatus" style="width: 100%;" id="industryStatus"><script>jQuery(function(){jQuery("#industryStatus").kendoDropDownList({"dataTextField":"text","dataValueField":"value","change":industryStatusOnClick,"value":"1","dataSource":{"data":[{"text":"--Select--","value":"8443"},{"text":"Agriculture/Fishing/Forestry/Mining","value":"8444"},{"text":"Food/Foodservice/Hospitality","value":"8445"},{"text":"Arts/Entertainment/Recreation/Sports","value":"8446"},{"text":"Insurance, Accounting and Banking","value":"8447"},{"text":"Design/Creative","value":"8448"},{"text":"Construction & Skilled Trades","value":"8449"},{"text":"Education and Training","value":"8450"},{"text":"Government/Public Administration","value":"8451"},{"text":"Engineering/Architecture","value":"8452"},{"text":"Manufacturing/Production/Operation","value":"8453"},{"text":"Medical and Healthcare","value":"8454"},{"text":"Media/Telecommunication/Communication","value":"8455"},{"text":"Religion","value":"8456"},{"text":"Legal Services","value":"8457"},{"text":"Emergency and Protection","value":"8458"},{"text":"Real Estate","value":"8459"},{"text":"Professional, Scientific, and Technical Services","value":"8460"},{"text":"Information Technology","value":"8461"},{"text":"Transportation and Utilities","value":"8462"},{"text":"Sales/Marketing/Retail","value":"8463"}]}});})</script></td>
</tr>
<tr>
<td align="right">Express Occupation:</td>
<td align="right"><input name="expressOccupation" style="width: 100%;" id="expressOccupation"><script>jQuery(function(){jQuery("#expressOccupation").kendoDropDownList({"dataTextField":"text","dataValueField":"value","change":expressOccupationOnClick,"value":"1"});})</script></td>
</tr>
<tr>
<td align="right">Other - Specify:</td>
<td align="right"><input type="text" id="otherSpecify" name="otherSpecify" disabled="disabled" class="k-textbox" style="width: 100%;"></td>
</tr>
<tr>
<td colspan="2">
<div id="empStatusMsg" style="margin: 0 0 0 0; color: red; width: 300px; float: right;"></div>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
So guys, finally I was able to figure this out. Seems like the issue was with the kendo tag libraries or atleast my implementation of them. Before the page was even loaded, the change event was being fired up.
Therefore, I removed the change event from the kendo tag definition and rather used the jquery on change event nested inside document.ready(). After this it started working fine.

React doesn't take well the td colSpan attrib [duplicate]

This question already has answers here:
React colspan not working
(6 answers)
Closed 5 years ago.
I'm trying to use a <table>...</table> inside React. I have this:
<table>
<tbody>
<tr>
<td> ... </td>
<td> ... </td>
</tr>
<tr>
<td colSpan={2}> ... </td>
</tr>
</tbody>
</table>
React ignores colSpan. I've been dealing with this for a while. I found some question like this here in Stackoverflow, and the answers are to camelcase the colspan, but it doesn't work for me. It goes the same in <th colSpan={2}>...</th> What am I missing here?
It's
<td colSpan='2'>
Not
<td colSpan={2}>

Why does this Javascript only run once per page?

I have this Try-it-Yourself section to my website but for some reason when I am wanting to have more than one Try-it-Yourself section it will only work for the one at the top of the page. So if I had three of them on a page the top one would work in the way I want but the next two would do nothing.
I have the following HTML:
<div class="tryit">
<table>
<tr>
<td>Try It Yourself</td>
</tr>
<tr>
<td><textarea id="input" rows="10" cols="47"></textarea></td>
</tr>
<tr>
<td><input onclick="update();" type="button" value="Update"></td>
</tr>
<tr>
<td><iframe id="output" name="output" width="600" height="300" ></iframe></td>
</tr>
</table>
</div>
And the following Javascript:
function update()
{
var tryitoutput = document.getElementById('input').value;
window.frames['output'].document.documentElement.innerHTML = tryitoutput;
}
Thank you.
As others mentioned, this is happening because there can't be more than one HTML element with same value of ID attribute. In your case javascript only finds the first element, that's why it doesn't work on later Update buttons. The simplest approach would be to set different ID attribute values for different "Try it yourself" boxes:
Slightly modify your JS, see following jsFiddle example
function update(tryItIndex) {
var tryItOutput = document.getElementById('input-' + tryItIndex).value;
window.frames['output-' + tryItIndex].document.documentElement.innerHTML = tryItOutput;
}
That's because you are referring to the textarea and the output by id which means it will always just retrieve the first one. A quick fix would be having unique id's for these fields and send the names as parameters to the update function like update(inputId, outputId)

Categories