Button onclick in function - javascript

I'm trying to solve this problem. First step is create a table after clicking on first button. Later the table is creating and one row has another button which should starting another function play() with arguments. For this example I just want to display ready in console but this is undefined. When I call this function by simply console.log outside the function then is working correctly. What is wrong with calling function play by button?
<table class="table">
<tr>
<th>Team A</th>
<th>Team B</th>
<th></th>
</tr>
</table>
<button onclick="create()">Create next Match</button>
const table = document.querySelector('.table');
const teams=[{
name: 'Real',
point: 10
},
{
name: 'Barca',
point: 20
}]
function create(){
table.innerHTML += `
<tr id="r1m1">
<td id="host">${teams[0].name}</td>
<td id="guest">${teams[1].name}</td>
<td id="host_score"></td>
<td id="guest_score"></td>
<td><button onclick="play(${teams[0]},${teams[1]})">Play</button></td>
</tr>`
}
function play(a,b){
console.log("ready");
}
console.log(play(teams[0],teams[1]))

You are mashing strings together, so teams[0] gets converted to [object Object] which not only doesn't contain the data you want, but also isn't syntactically valid JavaScript.
You might be able to manage with onclick="play(teams[0],teams[1])" but scope might trip you up (as teams and play must be globals, which are best avoided in general).
In general, your should use DOM methods like createElement, addEventListener and appendChild instead.

Don't use template substitution, just refer to the variables in directly in the onclick, just like when you call play() in the top-level code.
function create(){
table.innerHTML += `
<tr id="r1m1">
<td id="host">${teams[0].name}</td>
<td id="guest">${teams[1].name}</td>
<td id="host_score"></td>
<td id="guest_score"></td>
<td><button onclick="play(teams[0],teams[1])">Play</button></td>
</tr>`
}

Related

Passing a bgcolor value as a parameter to TD

I am using the following JavaScript code to populate a table. How can I pass the bgcolor value as a parameter to TD?
let template = `
<tr>
<td bgcolor="#00FF00">${"pump"+child.val().PumpID}</td>
<td bgcolor="#00FF00">${child.val().StartTime}</td>
<td bgcolor="#00FF00">${child.val().Duration}</td>
<td bgcolor="#00FF00">${child.val().GalsPumped}</td>
<td bgcolor="#00FF00">${child.val().Cycle}</td>
<td bgcolor="#00FF00">${child.val().Status}</td>
</tr>`;
table.innerHTML += template;
})
});
Basically I want to do this:
var color_variable = #ff00;
.
.
<td bgcolor=color_variable>${child.val().Status}</td>
It looks like you want to modify bgColor dynamically by altering the color_variable. If you're not using a framework (like Vue.js, React, or Angular) and if this is the behavior you want you might want to do something like that:
let themeOptions = {
color_variable: 'green'
}
function rerender() {
let template = `
<tr>
<td bgcolor="${themeOptions.color_variable}">${"pump" + child.val().PumpID}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().StartTime}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Duration}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().GalsPumped}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Cycle}</td>
<td bgcolor="${themeOptions.color_variable}">${child.val().Status}</td>
</tr>`;
table.innerHTML += template;
}
function changeColor(color) {
themeOptions.color_variable = color;
rerender();
}
changeColor('blue')
Of course, this is not the best code sample. You might want to modify it to suit your needs, but you get the idea. You can always use objects to pass a value by reference and modify the value later. But don't forget that you have to rerender the DOM.

I can't collect in Javascript

I'm new to javascript, I want to place a code in my html page like the following, but I get a NaN error or no error. He just doesn't make the sums. My html page is in Turkish but I hope you will understand. Thanks in advance for your suggestions and help
in two different tables
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
it needs to show a total in another table
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
Here is the javascript:
{
var hb1= document.getElementById("Hizmet_Bedeli1").textContent; // If I use .value also, it doesn't work if I use .textContent as well.
var hb2= document.getElementById("Hizmet_Bedeli2").textContent; // .value de kullansam .textContent de kullansam düzelmiyor
var hizmet_toplam= parseInt(hb1) + parseInt(hb2); //parseInt de kullansam Number de kullansam Nan hatasıalıyorum... // If I use parseInt with Number, I get Nan error ...
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
I want to add the textContent of #Hizmet_Bedeli1 and #Hizmet_Bedeli2 together.
You are most probably not wrapping your tr and th tags in a table tag, which will cause your browser to not render the elements.
{
var hb1 = document.getElementById("Hizmet_Bedeli1").textContent;
var hb2 = document.getElementById("Hizmet_Bedeli2").textContent;
var hizmet_toplam = parseInt(hb1) + parseInt(hb2);
document.getElementById("Ham_Toplam").innerHTML = hizmet_toplam;
}
<table>
<tr>
<td id="Hizmet_Bedeli1">35</td>
<td id="Hizmet_Bedeli2">35</td>
<tr/>
<th scope="row" class="align-middle" id="Ham_Toplam"> </th>
</table>

Web Scraping Using data-title and Without Using Classes or Ids

I am trying to scrape a website the issue is that the specific elements do not have Classes or Ids, but they do have data-tile. I need help referring to these when I am choosing an element to scrape.
Here is the html that I am scraping.
<div data-v-1234567z="">
<table data-v-1234567z="" align="center">
<thead data-v-1234567z="">
<tr data-v-1234567z="">
<th data-v-1234567z="">User</th>
<th data-v-1234567z="" style="cursor: pointer;">Money</th>
<th data-v-1234567z="" style="cursor: pointer;">Watch Time (minutes)</th>
</tr>
</thead>
<tbody data-v-1234567z="">
<tr data-v-1234567z="">
<td data-v-1234567z="" data-title="User" class="user-cell">
<span data-v-821a25a2="" data-v-1234567z="" class="mini-user-display">
<img data-v-821a25a2="" src="https://image.com" class="mini-user-profile-image" />
<span data-v-821a25a2="" class="mini-user-name">user1234</span>
</span>
</td>
<td data-v-1234567z="" data-title="Money">100,000</td>
<td data-v-1234567z="" data-title="WatchTime">678</td>
</tr>
</tbody>
</table>
</div>
I need to scrape the Money, WatchTime, and username.
Here is the code that I am using for the scraper.
async function pageFunction(context) {
const $ = context.jQuery;
const results = [];
$('tbody').each(function() {
results.push({
userName: $(this).find(".mini-user-name").text(),
watchTime: $(this).find("data-title-watchTime").text()
});
});
return results;
}
There are many issues with this code the userName actually does return the usernames the issue is that there is no break in between all the names and it's just one big blob.
The other bigger issue is that I can't get any data back from watchTime, this is because I can't figure out how to properly select the WatchTime data-title in JavaScript.
I have looked for a few hours and I can't figure it out.
To get an element by data-attribute in JQuery you just call it like you would in CSS, watchTime in your case would be called like this:
watchTime: $(this).find('[data-title="WatchTime"]').text()
As for your code coming out as one blob you are pushing objects to an array, until you do something to iterate over your array of objects and convert them to a readable format it will just be a blob of data. Without seeing what is calling this function and how you're handling the returned data it's impossible to provide much assistance with that.
EDIT:
Here's an example of how you might want to return your data using template literals for a more readable output.
const results = [];
$('tbody').each(function() {
results.push(
`Username: ${$(this).find(".mini-user-name").text()}
WatchTime: ${$(this).find('[data-title="WatchTime"]').text()}
Money: ${$(this).find('[data-title="Money"]').text()}`
);
});
return results;
This would give an output like:
Username: user1234
WatchTime: 678
Money: 100,000

How to read a list of html tables in JavaScript

I have a list of HTML tables given by pandas data frame in the format of:
list_html =
[<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>score</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.776959</td>
<td>grade</td>
<td>grade</td>
</tr>
<tr>
<th>1</th>
<td>0.414527</td>
<td>class</td>
<td>class</td>
</tr>, ... , ... ]
I am trying to visualize this data in an html page and could not do it. I do not have enough experience in web development. My goal is to use JavaScript to loop through each item the list and visualize them below each other in html. It would be great if anybody can help!
This is what I tried so far, its probably completely wrong:
var list_html = list_html // list of html codes as a javascript variable.
var arrayLength = analysis.length;
for (var i in list_html) {
document.getElementById("analysis_1").innerHTML = list_html[i];
}
Given a valid array of strings list_html (actually list_html is not a valid array of strings, since the markup in each entry is not wrapped in quotes) and a container in the DOM with id "analysis_1" it's simply a matter of:
var container = document.getElementById('analysis_1');
for (var i = 0; i < list_html.length; i++) {
container.innerHTML += list_html[i];
}
UPDATE:
well... in your scenario there is no need at all for a loop, you can simply inject a single string by joining the elements in the array:
document.getElementById('analysis_1').innerHTML = list_html.join('');
fast and simple! :)
using jquery's selectors :
Give the 'td' which contains the data a class name, eg: 'MyTd';
Select them all: $(.MyTd).text()
Done!

Render 2 table rows in ReactJS

I want to achieve expandable row functionality for table.
Let's assume we have table with task names and task complexity. When you click on one task the description of task is shown below. I try to do it this way with ReactJS (in render method):
if (selectedTask === task.id) {
return [
<tr>
<td>{task.name}</td>
<td>{task.complexity}</td>
</tr>,
<tr>
<td colSpan="2">{task.description}</td>
</tr>
];
} else {
return <tr>
<td>{task.name}</td>
<td>{task.complexity}</td>
</tr>;
}
And it doesn't work. It says:
A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object
I tried also to wrap 2 rows in a div but I get wrong rendering.
Please, suggest correct solution.
The render() method on a React component must always return a single element. No exceptions.
In your case, I would suggest wrapping everything inside a tbody element. You can have as many of those as you want in a table without disrupting your row structure, and then you'll always return one element inside render().
if (selectedTask === task.id) {
return (
<tbody>
<tr>
<td>{task.name}</td>
<td>{task.complexity}</td>
</tr>,
<tr>
<td colSpan="2">{task.description}</td>
</tr>
</tbody>
);
} else {
return (
<tbody>
<tr>
<td>{task.name}</td>
<td>{task.complexity}</td>
</tr>
</tbody>
);
}

Categories

Resources