Javascript - How to select "x" row - javascript

I have this list made on sweetalert2
*** this is the code ***
function detalleTransf(matricula, bancoorigenTransf, cbu_cta_origen, titular_cta_origen, ultimos_digitos_cta_origen) {
var datosTransferencia = {{ datosTransferencia|json_encode|raw }} ;
let html = "<html><body>"
html += "<div class='table-responsive'><table class='table table-hover table-condensed no-border'>" +
"<tr class='encabezado-tabla'> <td class='text-center'>Seleccionar </td><td class='text-center'> Matricula</td><td class='text-center'> Banco de Origen</td><td class='text-center'>CBU Cuenta Origen</td><td class='text-center'>Titular Cuenta Origen</td><td class='text-center'>Últimos 5 Dígitos Cuenta Origen</td> </tr>";
for (let row of datosTransferencia) {
html += "<tr id='algo'><td class='text-center'><div class='radio'><input type='checkbox' name='check' value='value' id='regular' onclick='prueba()' ><label style='display: none'>" + "</div></label></td>";
html += "<td class='text-center'>" + matricula + "</td>";
html += "<td class='text-center'>" + row.transf_banco + "</td>";
html += "<td class='text-center'>" + row.transf_cbu + "</td>";
html += "<td class='text-center'>" + row.transf_titular + "</td>";
html += "<td class='text-center'>" + row.transf_ctaorigen + "</td></tr>";
}
html += "</table></div>";
html += "</body></html>";
return html;
};
with this function I select each cell of a specific row and insert it into an input field
function test() {
var value1 = document.getElementById("bancoorigenTransf").innerText.replace(/\s+/, "");
var value2 = document.getElementById("cbu_cta_origen").innerText.replace(/\s+/, "");
var value3 = document.getElementById("bancoorigenTransf").innerText.replace(/\s+/, "");
var input = $('#titularorigen666');
var input2 = $('#cbuorigen');
var input3 = $('#bancoorigen');
input.val(input.val() + value1 + ', ');
input2.val(input2.val() + value2 + ', ');
input3.val(input3.val() + value3 + ', ');
return false;
};
The error I have is that it always selects the first row only.
the only solution i could think of is to add a unique id to it in the for loop but i don't know how to do it or if there is a better solution

One answer to this question can be found here, if you are only interested in getting the nth row of a table via JavaScript:
var cells = document.getElementById('table').getElementsByTagName('td');
This will contain all your table cells. Use array notation to access a specific one:
cells[4]
Here's a quick demo which changes the background color:
http://jsfiddle.net/jackwanders/W7RAu/

Related

How to dispaly display() without deleting the other HTML

var students = [
["test", "test", "test"],
["test", "test", "test"]
];
students.sort();
function display() {
for (i = 1; i < students.length + 1; i++) {
document.write("<tr>");
document.write("<td>" + (i) + "</td>");
document.write("<td>" + students[i - 1][0] + "</td>");
document.write("<td>" + students[i - 1][1] + "</td>");
document.write("<td>" + students[i - 1][2] + "</td>");
document.write("<td><input type='number' class='form-control' id='quiz" + i + "' ></td>");
document.write("<td><input type='number' class='form-control' id='reqt" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='exam" + i + "'></td>");
document.write("<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>");
document.write("</tr>");
}
}
function AddData() {
var AddName;
var AddCourse;
var AddBDay;
var Data;
AddName = document.getElementById('Addname').value;
AddCourse = document.getElementById('AddCourse').value;
AddBDay = document.getElementById('AddBDay').value;
if (AddName != "" && AddCourse != "" && AddBDay != "") {
Data = [AddName, AddCourse, AddBDay];
students.push(Data);
console.log(students);
display();
} else {
alert("Invalid Input");
}
}
document.write is very very old-school and it's very rarely used any more for many reasons.
You can either create a string variable that you can then add (concatenate) new strings to, or you can use more modern methods like in the example below which uses map to iterate over the array to create a new array of strings, and then join that array up into one HTML string.
const students = [
["test", "test", "test"],
["test", "test", "test"]
];
function getHtml(students) {
return students.map(arr => {
return `
<tr>
<td>${arr[0]}</td>
<td>${arr[1]}</td>
<td>${arr[2]}</td>
</tr>
`
}).join('');
}
const table = document.querySelector('table');
table.innerHTML = getHtml(students);
<table></table>
You haven't posted any HTML, but assuming you have a <table id="x"> or <tbody id="x">, modify the display function as below:
function display() {
let html = '';
students.map((item, i) => {
html += "<tr>";
html += "<td>" + (i+1) + "</td>";
html += "<td>" + item[0] + "</td>";
html += "<td>" + item[1] + "</td>";
html += "<td>" + item[2] + "</td>";
html += "<td><input type='number' class='form-control' id='quiz" + i + "' ></td>";
html += "<td><input type='number' class='form-control' id='reqt" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='exam" + i + "'></td>";
html += "<td><input type='number' class='form-control' id='pg" + i + "' readonly></td>";
html += "</tr>";
});
document.getElementById("x").innerHTML = html;
}
Also, document.write is rarely to never used. More here.
element.innerHTML is generally used when you want to perform some DOM manipulation as a result of an API call or any other event, as in your case.

Bootstrap Datatable is no longer functioning after loading content via Ajax

Before some one says its a duplicate question, i know it is. I've just not been able to find anyone's script that looks similar to mine and as i'm completely new to JavaScript and JQuery (used to php) i don't really know what I'm doing.
My datatable worked perfectly having the data loaded using php (before the page had loaded) but now its loaded after the page load, the table has lost all of it's filtering and pagination.
Here is how my table is loaded.
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<?php echo $tableheader;?>
</tr>
</thead>
<tfoot>
<tr>
<?php echo $tableheader;?>
</tr>
</tfoot>
<tbody id="data"> <!--data will be inputed here-->
</tbody>
</table>
</div>
This is the script that gets the data and puts it into the table.
<script>
//call ajax
var ajax = new XMLHttpRequest ();
var method = "GET";
var url = "data_assets.php";
var asynchronous = true;
setInterval(function(){
ajax.open(method, url, asynchronous);
//sending ajax request
ajax.send();
}, 250)
//receiving response from data_assets.php
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
//convert JSON back to array
var data = JSON.parse(this.responseText);
//console.log(data); //for debugging
//html value for <tbody>
var html ="";
//looping through the data
for (var a = 0; a < data.length; a++) {
var asset_number = data[a].asset_number;
var id = data[a].id;
var room = data[a].room;
var _location = data[a]._location;
var sku = data[a].sku;
var qty = data[a].qty;
var _value = data[a]._value;
var date = data[a].date;
var po_number = data[a].po_number;
var purchaced_from = data[a].purchaced_from;
var notes = data[a].notes;
var total = data[a].total;
//storing in html
html += "<tr>";
html += "<td style='vertical-align: middle;'>" + asset_number + "</td>";
html += "<td style='vertical-align: middle;'>" + id + "</td>";
html += "<td style='vertical-align: middle;'>" + room + "</td>";
html += "<td style='vertical-align: middle;'>" + _location + "</td>";
html += "<td style='vertical-align: middle;'>" + sku + "</td>";
html += "<td style='vertical-align: middle;'>" + qty + "</td>";
html += "<td style='vertical-align: middle;'>" + _value + "</td>";
html += "<td style='vertical-align: middle;'>" + total + "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>" + date + "</td>";
html += "<td style='vertical-align: middle;'>" + po_number + "</td>";
html += "<td style='vertical-align: middle;'>" + purchaced_from + "</td>";
html += "<td style='vertical-align: middle;'>" + notes + "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>";
html += "<a href='?id=" + id + "&room=" + room + "&asset=" + asset_number + "&location=" + _location + "&sku=" + sku + "&qty=" + qty + "&value=" + _value + "&date=" + date + "&po=" + po_number + "&where=" + purchaced_from + "&notes=" + notes + "#editModal' class=''><i class='far fa-edit fa-lg'></i></a>";
html += "</td>";
html += "<td style='text-align: center; vertical-align: middle;'>";
html += "<a href='?id=" + id + "&room=" + room + "&asset=" + asset_number + "&location=" + _location + "&sku=" + sku + "&qty=" + qty + "&value=" + _value + "&date=" + date + "&po=" + po_number + "&where=" + purchaced_from + "&notes=" + notes + "#duplicateModal' class=''><i class='far fa-clone fa-lg'></i></a>";
html += "</td>";
html += "</tr>";
}
//replacing the <tbody>
document.getElementById("data").innerHTML = html;
}
}
</script>
If anyone could show me how to get this working in my example it would be greatly appreciated, I really want to load all of my tables on this site like this so i dont need to have a refresh on saving data (This refreshes every 250ms so the data in the table is always up to date with the database).
Update:
Right i took out my 250ms refresh and now the table works perfectly! is anyone now able to help me with my next issue. How do i get the table to refresh when new data is entered into the database, without refreshing the whole page
I suggest creating the table structure in HTML or PHP (not Javascript). Then load the data into the table with ajax. Those DOM elements are not readily available to javascript unless the event to create the elements is bound to an element that already exists like body or document or some other parent element of the table.
UPDATE:
I personally don't have much experience with DataTables plugin. So the plugin will automatically create your DOM elements (table structure) based on either the data object returned from ajax or by properties you specify. DataTables does use jQuery's ajax() method to make ajax calls however you should not override the success callback. There is a proper way to use their API when making ajax calls as specified in the documentation. There is also a proper way to reload data on an interval to refresh your tables.
Please check out this fiddle.
The ajax url, method, data properties must of course be updated to fit your application (this was the only way to simulate ajax call on jsFiddle. Please note you will have to have properly formatted JSON.
Did you tried to explicitly set pagelength property on Datatables?
$('#datatable').dataTable( {
"pageLength": 50
} );

jquery append not working but working in another function

So.. I have 2 jquery functions that append something to a table.
the first one doesn't work , the second function does work? while in the first function my HTML var is filled with the good information to append, it just doesn't append it??
function buildTable(data) {
var html = "";
$.each(data, function (key, value) {
html += "<tr>";
html += "<td><a class='delete'><i class='fa fa-thrash'></i></a></td>";
html += "<td class='key'>" + key + "</td>";
html += "<td class='val'>" + value + "</td>";
html += "<td></td>";
html += "</tr>";
//$(".table > tbody").prepend(html);
//$(".addrow").append(html);
//$("#parameterTable > tbody").append(html);
});
$('.addrow').prepend(html);
//$(".formTable ").prepend(html);
}
Second function (the one that does work)
function addNewParameter() {
if(!added) {
var html = "<tr>";
html += "<td></td>";
html += "<td><input type='text' class='parameter1' name='Parameter1'></td>";
html += "<td><input type='text' class='parameter2' name='Parameter2'></td>";
html += "<td><a class='save'><i class='fa fa-save'></i></a><a class='undoAdd'><i class='fa fa-undo'></i></a></td>";
html += "</tr>";
$(".addrow").append(html);
added = true;
} else {
showWarning("u heeft al een parameter toegevoegd, sla deze eerst op.");
}
}
The HTML where I need to append it
<table class="formTable table table-striped table-bordered table-hover dataTable" id="parameterTable">
<thead>
<tr>
<td class="col-md-2"></td>
<td class="col-md-4">
Naam
</td>
<td class="col-md-4">
Waarde
</td>
<td class="col-md-2"></td>
</tr>
</thead>
<tbody class="addrow">
</tbody>
</table>
I have been struggling with this for a while, any help would be nice
Have you tried it like this?
function buildTable(data) {
var html = "";
$.each(data, function (key, value) {
html += "<tr>";
html += "<td><a class='delete'><i class='fa fa-thrash'></i></a></td>";
html += "<td class='key'>" + key + "</td>";
html += "<td class='val'>" + value + "</td>";
html += "<td></td>";
html += "</tr>";
});
$('.addrow').append(html);
}
Proper usage of jQuery does not require ending tags:
function addNewParameter() {
if (!added) {
var newHtml = $('<tr>');
newHtml.append($('<td>'));
newHtml.append(
$('<td>').append(
$('<input>'.addClass("parameter1").attr({"name":"Parameter1","type":"text"}))
)
);
html.append(
$('<td>').append(
$('<input>').addClass("parameter2").attr({"name":"Parameter2","type":"text"})
)
);
html.append(
$('<td>').append(
$('<a>').addClass('save').append(
$('<i>').addClass("fa fa-save")
),
$('<a>').addClass('undoAdd').append(
$('<i>').addClass("fa fa-undo")
)
)
);
$('.addrow').append(newHtml);
added=true;
}
else {
showWarning("u heeft al een parameter toegevoegd, sla deze eerst op.");
}
}
It was a problem with a bootstrap dialog , after the dialog was loaded and then the append function it worked

How to pass data into function, inside HTML tags?

I fixed the problem by calling a function, that graps the id of the table row it is placed in :)
I have this piece of code sorting some different stuff into a table, that works fine. The problem is to pass data into a function called inside HTML tags, like so:
See reference here
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+data.isOpen+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>";
output += "<td><b>" + data.name + "</b></td>";
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>";
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription(data.description)'/></td>";
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic(data.image)'/></td>";
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>";
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers(data.teams)'/></td>";
output += "<td>" + prizes(data.prices) + "</td>";
output += "</tr>";
});
output += "";
$('#data_insert').append(output);
});
All I do in the function is to console the data, and I get error "data is not defined"
This is the full script https://github.com/Jakobtottrup/OptekSemester2/blob/master/Web/public/js/tournaments_admin.js
// list tournaments
$.when(document, getTournamentsData()).done(function(){
var output = "";
$.each(tournamentsData, function(key, data){
output += "<tr class='data_row "+convertBoolean(data.isOpen)+"' id='"+data._id+"'>";
output += "<td>" + (key+1) + "</td>"; // index
output += "<td><b>" + data.name + "</b></td>"; // navn
output += "<td>Start: " + data.begintime + "<br>Slut: " + data.endtime + "</td>"; // start/slut
output += "<td><input class='btn btn-primary' type='button' value='Se beskrivelse' onclick='showTourDescription("+data.description+")'/></td>"; // beskrivelse TODO
output += "<td><input class='btn btn-primary' type='button' value='Se billede' onclick='showPic("+data.description+")'/></td>"; // billede
output += "<td>Max antal: "+ data.max_teams +"<br>Tilmeldte: "+ data.teams.length +"</td><br>"; // hold
output += "<td><input class='btn btn-primary' type='button' value='Se deltagere' onclick='showMembers("+data.teams"+)'/></td>"; // medlemmer
output += "<td>" + prizes(data.prices) + "</td>"; // præmier
output += "</tr>";
});
I've taken your code, and as you've done in the HTML strings themselves, concatenated in the event handlers too. Should be all you need to do.
UPDATE: Looks like you are passing data as string. See if that works
$.each(tournamentsData, function(data) {
onclick='showTourDescription(" + data.description + ")

Working with JSON input

I'm trying to get a JSON input with AJAX and load it in a select control.
but when I run it :\ It stuck on "Downloading the recipes....".
anyone see the problem maybe? (I tried couple of changes but nothing work so far)
1 more issue can anyone think on a shorter way to do the
ConvertToTable(targetNode)
cuse it's way to long and complex, I think :\
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
document.getElementById("span").style.visibility = "visible";
document.getElementById("span1").style.visibility = "hidden";
document.getElementById("button").style.visibility = "hidden";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = xmlhttp.responseText;
result = eval('(' + result + ')');
txt = "<select onchange='ShowRecipeDetails(this)'>";
for (i = 0; i < result.length; i++) {
txt = txt + "<option VALUE=" + result[i].recipe + ">" + result[i].recipe + "</option>";
}
txt = txt + "</select >";
document.getElementById("span").style.visibility = "hidden";
document.getElementById("span1").style.visibility = "visible";
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("POST", "http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=json", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send();
}
function ShowRecipeDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var field = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://food.cs50.net/api/1.3/recipes?&output=json&id=" + field,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data[0]));
}
});
}
function ConvertToTable(targetNode) {
var table = "<table border = 1 borderColor =green>";
table += "<tr>";
table += "<td>" + "ID" + "</td>";
table += "<td>" + targetNode.id + "</td>";
table += "</tr>";
table += "<td>" + "Ingredients:" + "</td>";
table += "<td>" + targetNode.ingredients + "</td>";
table += "</tr>";
table += "<td>" + "Name:" + "</td>";
table += "<td>" + targetNode.name + "</td>";
table += "</tr>";
table += "<td>" + "Size:" + "</td>";
table += "<td>" + targetNode.size + "</td>";
table += "</tr>";
table += "<td>" + "Unit" + "</td>";
table += "<td>" + targetNode.unit + "</td>";
table += "</tr>";
table += "<td>" + "VEGETARIAN:" + "</td>";
table += "<td>" + targetNode.VEGETARIAN + "</td>";
table += "</tr>";
table += "</tr>";
table += "</table>"
return table;
}
</script>
and the HTML:
<button id="button" type="button" onclick="loadXMLDoc()" >Get all recipes</button>
<br />
<span id="span" style="visibility:hidden">Downloading the recipes....</span>
<span id="span1" style="visibility:hidden">Please choose a recipe ID to view</span>
<div id="jsonDiv"></div>
<div id="myDiv"></div>
<div id="TableDiv"></div>
The HarvardFood API also supplies a JSONP version. So if you change your URL to this:
http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=jsonp&callback=parseResponse
you can create a parseResponse function to handle the data that comes back, and you can do the AJAX by inserting a script tag.
The problem is that you're running afoul the Same Origin Policy.
I see that you've updated the question to use jQuery AJAX. That offers a jsonp data type, which might be easier than adding a script tag.

Categories