/*
In this example you will still have the adding functionality, just with more rows in the
table. There will be multiple dom traversing examples, and some oops code.
*/
// find elements
var $table = $("#player-table")
var $nameInput = $("#name")
var $numberInput = $("#number")
// handle click event for the 'Create alert with name'
$("#output-name-button").on("click", function(){
// get the name input, there are two, so this will grab the first, not the second
var $name = $("#name")
// how to fix by narrowing your dom traversal
// $name = $("#name", $(this).parent())
var length = $name.length; // although there are 2, this will only show 1
var name = $name.val();
alert(`The name is ${name}, and the number of names is ${length}`);
});
// handle click event for the 'Add' Button
$("#add-button").on("click", function(){
var row = createRow($nameInput.val(), $numberInput.val());
$table.append(row);
});
//Dom traverse blunders 2, selecting all elements, and applying events to all instead of
//the one specific
/* $("button").on("click", function(){
var row = createRow($nameInput.val(), $numberInput.val());
$table.append(row);
});
*/
// dynamically add a row, this could be coming from an api call, or some javascript
function createRow(name, number){
var temp =
`<tr class=\"row\"><td class=\"cell\">${name}</td><td class=\"cell\">${number}</td></tr>`;
return temp;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.