Value not increasing in table in while clicked in javascript - javascript

I have a table and when I clicked on leftmost column's number like 1,2,3... I want their respective rightmost column 0 to increase like 1,2,3,4,5...(Increase by 1 on every click.)
var ms=document.getElementById('message');
window.onload = build;
var myArray = ["Laurence", "Mike", "John", "Larry", "Kim", "Joanne", "Lisa", "Janet", "Jane"];
var message = document.getElementById('message');
function build() {
var html = "<h1>My Friends Table</h1><table>";
for (var x = 0; x < myArray.length; x++) {
html += '<tr data-row="' + x + '" data-vote="0"><td class="box" >' + (x + 1) + '</td><td>' + myArray[x] + '</td><td>0</td></tr>';
}
html += '</table>';
document.getElementById('output').innerHTML = html;
var elbox = document.querySelectorAll('#output .box');
var a;
var v;
for (var x = 0; x < elbox.length; x++) {
elbox[x].onclick = function () {
console.dir(this);
a = this.closest('[data-row]').getAttribute('data-row');
console.log(myArray[a]);
message.innerHTML = myArray[a] + " is on row #" + a;
v = this.closest('[data-vote]').getAttribute('data-vote');
v++;
console.log(v);
this.parentElement.lastElementChild.innerText=v;
}
}
}
td {
border: 1px solid #ddd;
padding: 10px;
}
<html>
<head>
<title>Complete JavaScript Course</title>
</head>
<body>
<div id="message">Complete JavaScript Course</div>
<div id="output"></div>
</body>
</html>
I have set v++ but why the value of v is not increasing? I am still seeing value as 1. To update the innertext,I have used
this.parentElement.lastElementChild.innerText=v;
Since <tr> is parent of td and i used this.parentElement.lastElementChild.innerText=v; why its just stuck to 1 on every click?Why it is not increasing after one?

Every time you click it is based on data-vote attribute value of the first td of the row.
You do modify the innerText of the right column but after that you should do something like this to modify the data-vote attribute also:
this.parentElement.firstElementChild.dataset.vote=v;

Related

Add button in javascript without using html

I'm trying to add a button in javascript file without using HTML bacsue I need to have it in the column inside the loop, but when I click on the button to call the function it shows the error that its looking on that button in HTML file!
how could I fix that?
function success(name) {
let info = "<div class='infoTable'>";
for (let i = 0; i < name.length; i++) {
info += "<div class='info'>";
info += "<div class='fcol'>" + (i+1) + "</div>";
info += "<div class='scol'>" + name[i].item + "</div>";
info += "<div class='fcol'>" + name[i].quantity + "</div>";
info += '<button onclick="deletee(\'' + name[i].ID + '\')"> Delete This<button />';
info += "</div>";
}
info += "</div>";
printItems.innerHTML = info;
}
this is the function
function deletee(id){
let url = "server/delete.php?id=" + id;
console.log(url);
fetch(url, { credentials: 'include' })
.then(response => response.text())
.then(getList)
}
this is the error
(index):1 Uncaught ReferenceError: deletee is not defined
at HTMLButtonElement.onclick ((index):1)
onclick # (index):1
The best solution in this case is using document.createElement: https://www.w3schools.com/jsref/met_document_createelement.asp
It's better practice than converting a string to DOM Elements.
Since you did not post all your code, we cannot assist further if we cannot see the function you are trying to execute.
The reason why I am suggesting using JS and not converting a string to DOM, is most IDE's will identify missing, misspelt, or incorrectly used functions. Which could've been your mistake.
Here is an example:
var colsToAdd = 5;
var rowsToAdd = 25;
function FillTable() {
//Get existing table or create a new one. Append to parent if create
var table = document.getElementById("testTable");
//Clear table
table.innerHTML = "";
//Create your rows using a for loop
for (var i = 0; i < rowsToAdd; i++) {
var row = document.createElement("TR");
table.appendChild(row);
//Create your columns using a for loop
for (var k = 0; k < colsToAdd; k++) {
{
var col = document.createElement("td");
row.appendChild(col);
if (k == colsToAdd - 1) {
var button = document.createElement("button");
button.type = "button";
//Button click event is an anonymous function
button.onclick =
function(r) {
return function() {
table.removeChild(r);
}
}(row)
button.innerHTML = "Delete";
col.appendChild(button);
} else {
col.innerHTML = "row " + i + " column " + k;
}
}
}
}
}
table {
border: 1px solid #000;
margin: 1em;
}
td {
border: 1px solid #000;
padding: 1em;
}
<div>
<h1>Heading</h1>
<button onclick="FillTable()">Fill table</button>
<table id="testTable">
</table>
</div>

HTML table display JQuery checkbox off-by-one and not preserving data

I have some JavaScript code that should display a matrix of checkboxes. I want to list the column titles across the top, and then put rows where there is a column of checkboxes under each header, plus a left-hand column with row names under a blank header box. I'm going for the look on this page:
http://codepen.io/marclundgren/pen/hgelI
I wrote a Fiddle that almost works:
https://jsfiddle.net/bv01xvdf/
The first problem is that my table displays the checkboxes on a separate line from the cell with the row name. I checked my HTML, and it seems correct, but I'm wondering if I'm missing a <tr> or a </tr> somewhere. I add the row name cell like this (see the Fiddle for complete code):
var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
for (x = 0; x < chugNames.length; x++) {
// Add a row for each name.
target.append("<tr><td>" + chugNames[x] + "</td>");
for (y = 0; y < chugNames.length; y++) {
target.append("<td><input type=\"checkbox\" />");
checkbox = $('</input>', {
'type': 'checkbox',
'data-x': chugNames[x],
'data-y': chugNames[y],
});
target.append(checkbox);
target.append("</td>");
}
target.append("</tr>");
}
The other problem is that data-x and data-y return "undefined" when I access them later in my "on" method:
target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});
When I check a box, I get "checkbox changed chug intersection (undefined, undefined): true". It should print something like (Ropes, Cooking), depending on which box was checked.
Any help would be greatly appreciated.
When you append with jQuery the tag is automatically closed.
check the jsfiddle
Try this:
$(function() {
var target = $('#checkboxes');
var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
var i, x, y, checkbox, html;
html = "<table class=\"responsive-table-input-matrix\"><thead><tr><th></th>";
// Table column headers
for (i = 0; i < chugNames.length; i++) {
html += "<th>" + chugNames[i] + "</th>";
}
html += "</tr></thead><tbody>";
for (x = 0; x < chugNames.length; x++) {
// Add a row for each chug.
html += "<tr><td>" + chugNames[x] + "</td>";
for (y = 0; y < chugNames.length; y++) {
html += "<td>";
checkbox = '<input type=checkbox ';
checkbox += ' data-x=' + chugNames[x]
checkbox += ' data-y=' + chugNames[y]
checkbox += '/>'
html += checkbox;
html += "</td>";
}
html += "</tr>";
}
html += "</tbody></table>";
target.append(html).width(function() {
return $(this).find("input:checkbox").outerWidth() * chugNames.length
});
target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});
});
I fixed your jsfiddle here.
For the record, you had a few problems, an extra <th></th> in the opening string, an extra output of ChugName[x] and you didn't use the attr() jQuery function to get the data attributes properly.

Uncaught ReferenceError: variable is not defined on onclick function Javascript

Today , i have been read all the topic about this but couldn't come up with a solution that's why i am opening this topic.
This is my function which creates the view and i am trying to have a onclick function which should directs to other javascript function where i change the textbox value.
<script type="text/javascript">
$('#submitbtnamazon')
.click(function(evt) {
var x = document.getElementById("term").value;
if (x == null || x == "" || x == "Enter Search Term") {
alert("Please, Enter The Search Term");
return false;
}
listItems = $('#trackList').find('ul').remove();
var searchTerm = $("#term").val();
var url = "clientid=Shazam&field-keywords="
+ searchTerm
+ "&type=TRACK&pagenumber=1&ie=UTF8";
jsRoutes.controllers.AmazonSearchController.amazonSearch(url)
.ajax({
success : function(xml) {
$('#trackList')
.append('<ul data-role="listview"></ul>');
listItems = $('#trackList').find('ul');
html = ''
tracks = xml.getElementsByTagName("track");
for(var i = 0; i < tracks.length; i++) {
var track = tracks[i];
var titles = track.getElementsByTagName("title");
var artists = track.getElementsByTagName("creator");
var albums = track.getElementsByTagName("album");
var images = track.getElementsByTagName("image");
var metaNodes = track.getElementsByTagName("meta");
//trackId ="not found";
trackIds = [];
for (var x = 0; x < metaNodes.length; x++) {
var name = metaNodes[x]
.getAttribute("rel");
if (name == "http://www.amazon.com/dmusic/ASIN") {
trackId = metaNodes[x].textContent;
trackIds.push(trackId);
}
}
for (var j = 0; j < titles.length; j++) {
var trackId=trackIds[j];
html += '<div class="span3">'
html += '<img src="' + images[j].childNodes[0].nodeValue + '"/>';
html += '<h6><a href="#" onclick="someFunction('
+trackId
+ ')">'
+trackId
+ '</a></h6>';
html += '<p><Strong>From Album:</strong>'
+ albums[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Artist Name:</strong>'
+ artists[j].childNodes[0].nodeValue
+ '</p>';
html += '<p><Strong>Title:</strong>'
+ titles[j].childNodes[0].nodeValue
+ '</p>';
/*html += '<p><Strong>Created:</strong>'
+ releaseDate
+ '</p>';*/
html += '</div>'
}
}
//listItems.append( html );
$("#track").html(html);
$("#track").dialog({
height : 'auto',
width : 'auto',
title : "Search Results"
});
// Need to refresh list after AJAX call
$('#trackList ul').listview(
"refresh");
}
});
});
</script>
This is my other function where i change the textbox value. it works actually with other values e.g. when i give hardcoded string value. I can see the value in the console but for some reason it gives me the error like :
here the string starts with B is AsinId where i take from amazon. I am definitely in need of help because i am totally stucked.
Uncaught ReferenceError: B00BMQRILU is not defined 62594001:1 onclick
<script type="text/javascript">
function someFunction(var1) {
tracktextbox = document.getElementsByName("trackId");
for (var i = 0; i < tracktextbox.length; i++) {
tracktextbox[i].value = var1;
}
$('#track').dialog('close');
}
</script>
The problem is '<h6><a href="#" onclick="someFunction('+trackId+ ')">', from the error it is clear that trackId is a string value, so you need to enclose it within "" or ''. So try
'<h6><a href="#" onclick="someFunction(\'' + trackId + '\')">'

dynamically creating a table and adding cells to the table through a function with Javascript

I am wondering how to create a function with a for loop which creates new cells / rows for the other for loop to call upon. The function should return newRow which should be a specified amount of cells. The idea is the html code displays 3 images per row, but if there is just 2 images then it only needs 2 cells. That is the first if / else statement.
Here is the code so far..
var cells = document.getElementsByTagName('td');
var cell = '<td>' + cells[0].innerHTML + '</td>';
//console.log(cell);
document.getElementById('searchBtn').onclick = search;
//specified as 3 per row
var NUMPERROW = 3;
//gets number from form text input
var num = document.getElementById("searchtxt").value;
function search(){
//var num = 4;
console.log(num);
//loop once per row
var htmlStr = '';
for (var i = 0; i < num; i = i + NUMPERROW){
//htmlStr += '<tr>' + cell + cell + cell + '</tr>;
if (num - i >= NUMPERROW) {
//displays a new row of 3
htmlStr += newRow(NUMPERROW);
}else { //less then 3 to display
htmlStr += newRow(num - i);
}
}
document.getElementById('thumbnails').innerHTML = htmlStr;
}
/*
*Returns the html for a new row.
* numToAdd: the number of cells to add for this row.
*
*/
//this function i do not know how to write
function newRow(cellsToAdd){
/////?????????? should be a for loop return new Row for the for loop above
}
}
Here is a simple function if you don't want to pass the values you can leave content out.
function newRow(numberOfCells, content)
{
var result = '<tr>';
for(var i = 0; i < numberOfCells; i++)
result += '<td>' + content[i] + '</td>';
result += '</tr>';
return result;
}

retrieving array value on mouseover with javascript

I'm trying to figure out a way to retrieve and display the value of a div tag that is created with a 2D array using JavaScript. I figured either onclick or onmouseover would work but neither would in this approach. I would like to avoid creating 49 functions that does the same thing (just displaying the 'cell' the mouse is over).
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(cellId)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
// ???
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Thanks!
You can simply get the cell id by passing this.id into the function.
Try this:
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
console.log(cellId);
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>
Right now you have set up each cell element to call the function displayMe whenever the mouseover event occurs. When you call that function, you are passing the variable cellId as an argument. The problem is when that function is called, cellId is not defined. You can see this error pop up in your browser's developer console ("Uncaught ReferenceError: cellId is not defined").
You probably want to pass the cell element's id property, which you define dynamically here: id='area" + i + j + "'. You can use the id property of an element to look up the element (as you have done already), and get the text it contains via textContent.
To pass the cell element's id property, you need to use the this variable, like so: this.id. this will refer to the element that is triggering the event. So, if you change your onmouseover value of your div element to this: onmouseover='displayMe(this.id)', it will pass the appropriate value to your displayMe function, allowing you to do something like this:
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
With these adjustments, your code will look like this in its entirety:
<style type="text/css">
.float {float: left;}
.clear {clear:both;}
div {border: thin solid blue; padding: 2px;}
</style>
</head>
<body>
<div id="grid"></div>
<div id="bucket" class="float"></div>
</body>
<script type="text/javascript">
var axisY = 7;
var axisZ = 7;
for (var i = 0; i < axisY; i++) {
for (var j = 0; j < axisZ; j++) {
document.getElementById('grid').innerHTML += "<div onmouseout='displayNone()' onmouseover='displayMe(this.id)' id='area" + i + j + "' class='float'>" + i + ":" + j + "</div>";
}
document.getElementById('grid').innerHTML += "<br class='clear' />";
}
function displayMe(cellId) {
document.getElementById('bucket').innerHTML = document.getElementById(cellId).textContent;
}
function displayNone() {
document.getElementById('bucket').innerHTML = "";
}
</script>

Categories