jQuery function - set String parameter - javascript

I am creating a web page and I want to give a alert whenever I clicked a row of the generated table that is generated by the below code. In order to do that I am using setAlert(message) function.
My problem is that it only works when the parameter that is set to the function is a integer. it doesn't work when it is a String.
Help me solve this problem.
Thank you.
function getItemList(){
$('#tableItem').empty();
$.ajax({
url: 'ItemServlet',
data:{version:2},
type: 'post',
dataType: 'json',
success: function (data) {
$('#tableItem').append('<table class="table table-striped table-hover" id="table1">\n\
<thead><tr><th class="table-text-align-centre" style="width:10%">Item Code</th>\n\
<th class="table-text-align-centre" style="width:20%">Name</th>\n\
<th class="table-text-align-centre" style="width:50%">Description</th>\n\
<th class="table-text-align-centre" style="width:10%">Stock Count</th>\n\
<th class="table-text-align-centre" style="width:10%">Active</th></tr></thead><tbody class="table-hover"></tbody></table>');
var length = data.length;
for (i = 0; i < length; i++) {
var post = data[i];
$('#table1').append('<tr onClick="setAlert('+post['itm_code']+')"><td>' + post['it_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_description'] + '</td> \n\
<td class="table-text-align-centre">' + post['itm_stockcount'] + '</td> \n\
<td class="table-text-align-centre">' + post['active'] + '</td> \n\
</tr>');
}
}
});
}
function setAlert(message) {
var id = message+ "";
alert(id);
}

The issue here is that you are passing your parameters into the setAlert function without defining the quotes. Now because you are using " to define your onClick and your using ' to formulate you html, you need to use an apostrophe escaped \' to pass in the parameter.
So currently, if post['itm_code'] is 1, it will generate the following html with valid javascript:
<tr onClick="setAlert(1)"><td>
However if post['itm_code'] is a string "my string", it will render the following html with invalid javascript:
<tr onClick="setAlert(my string)"><td>
So the following line:
<tr onClick="setAlert('+post['itm_code']+')"><td>
should be changed to:
<tr onClick="setAlert(\''+post['itm_code']+'\')"><td>

Related

How do I make a button that, when clicked, displays data in node.js?

So I've created a button, along with a table that shows data from my database. However, I want that data to appear only when the button is clicked. So when the button is clicked, I want a random row from a specific table I have in my database appear.
`<button id="breakfast2">Breakfast</button>
<table id="mealTableContainer2">
<thead>
<tr>
<th id="mealname">Meal Name</th>
<th id="mealcalories">Calories</th>
<th id="mealtype">Type of Meal</th>
</tr>
</thead>
<tbody id="mealContainer2"></tbody>
</table>`
The only Javascript I currently have is for getting my database into that table, but I really only want it to appear when I click the breakfast button. I just can't figure out how; if someone could explain it to me very simply, I'd be appreciate it a ton!
console.log('Data2 received')
$.ajax({
url: 'http://localhost:5000' + "/read-recordsrandom",
type: 'get',
success: function(response) {
var data2 = JSON.parse(response);
if(data2.msg === "SUCCESS"){
console.log(data2.meal)
createMealTable2(data2.meal);
} else {
console.log(data2.msg);
}
},
error: function(err){
alert(err);
}
});
}
function createMealTable2(data2) {
var tableHTML2 = " ";
console.log("Test");
for(var i=0; i < data2.length; i++){
tableHTML2 += "<tr>";
tableHTML2 += "<td>" + data2[i].mealname + "</td>";
tableHTML2 += "<td>" + data2[i].mealcalories + "</td>"
tableHTML2 += "<td>" + data2[i].mealtype + "</td>";
tableHTML2 += "</tr>";
}
$('#mealContainer2').html(tableHTML2);
}
Hide it initially then display it
document.getElementById("breakfast2")
.addEventListener('click', function(event) {
document.getElementById("mealTableContainer2").classList.remove('hidden');
});
.hidden {
display: none;
}
<button id="breakfast2">Breakfast</button>
<table id="mealTableContainer2" class="hidden">
<thead>
<tr>
<th id="mealname">Meal Name</th>
<th id="mealcalories">Calories</th>
<th id="mealtype">Type of Meal</th>
</tr>
</thead>
<tbody id="mealContainer2"></tbody>
</table>
If I'm right, by default, the table is supposed to be hide. So you can first of all, hide the table with css
Change this line to hide the table
<table id="mealTableContainer2" style="display: none;">
After that, you will need to add event listener on the button "breakfast" in javascript to display the table on click
document.getElementById("breakfast2").addEventListener("click", function() {
document.getElementById("mealTableContainer2").style.display = "block";
});
Here is how you can ajax on click
NOTE: the `` are backticks used in template literal delimites and MUST be backticks
$(function() {
const createMealTable2 = data => {
$('#mealContainer2')
.html(data.map(meal => `<tr>
<td>${meal.mealname}</td>
<td>${meal.mealcalories}</td>
<td>${meal.mealtype}</td>
</tr>`)
.join("")
)
};
$("#breakfast2").on("click", function() {
$.ajax({
url: 'http://localhost:5000' + "/read-recordsrandom",
type: 'get',
success: function(response) {
var data2 = JSON.parse(response);
if (data2.msg === "SUCCESS") {
createMealTable2(data2.meal);
} else {
console.log(data2.msg);
}
},
error: function(err) {
alert(err);
}
});
})
})
<button type="button" id="breakfast2">Breakfast</button>
<table id="mealTableContainer2">
<thead>
<tr>
<th id="mealname">Meal Name</th>
<th id="mealcalories">Calories</th>
<th id="mealtype">Type of Meal</th>
</tr>
</thead>
<tbody id="mealContainer2"></tbody>
</table>
You need an event listener that listen for a click and than do the call to your database with asynchronous function. After the answer is returned just put it on the page using createElement or inner text of already existing html element.

Append datatables success but thead section gone

I'm try to use append to fill my table. Please take a look
<table width="100%" id="tbltbl" class="asoy table table-bordered table-striped">
<thead>
<tr>
<th width="1%">No</th>
<th width="14%">Outlet</th>
<th width="14%">Leader</th>
<th width="14%">Chief</th>
<th width="14%">RM</th>
<th> Action </th>
</tr>
</thead>
</table>
for default my table look like this
I run the onchange method and i receive this
[{"OutletCode":"K-BDIP3","Description":"BANDUNG INDAH PLAZA 3","NipLeader":"0802400","NipRM":"0802678"
,"NipChief":"-"},{"OutletCode":"K-CMHM2","Description":"KIOS CIMAHI MALL 2","NipLeader":"0802400","NipRM"
:"0802678","NipChief":"-"},{"OutletCode":"K-TSPA3","Description":"TASIK PLAZA ASIA 3","NipLeader":"0802400"
,"NipRM":"0802678","NipChief":"-"},{"OutletCode":"K-BDCW2","Description":"KIOS BANDUNG CIWALK 2","NipLeader"
:"0802400","NipRM":"0802678","NipChief":"-"}]
then i append it
function byarea(){
$(".asoy").empty();
var area = $("#pilihanarea").val();
var tipe = $('#tipe').val();
var formUrl = "<?=base_url();?>arealeader/finddata";
var angka = 1;
$.ajax({
url: formUrl,
type: 'POST',
data: {tipe:tipe,area:area},
success: function(data, textStatus, jqXHR){
var newdata = JSON.parse(data);
$.each(newdata, function(key, val) {
$('.asoy').append('<tbody><tr> <td>'+ (angka++) +'</td>' +
'<td>' + val.OutletCode + '</td>' +
'<td>' + val.NipLeader + '</td>' +
'<td>' + val.NipChief +'</td>' +
'<td>' + val.NipRM +'</td>' +
'<td>----</td>' +
'</tr></tbody></thead>');
});
}
});
}
and my table look like this
It seems I'm loosing my <thead>..</thead> section. Any solution for this ? thanks in advance...
Create an empty <tbody class="asoy"></tbody> just before the closing </table> tag and remove the class "asoy" from the <table> tag. Then remove the <tbody> tags from your call to append().
At the moment, your $(".asoy").empty(); is removing the entire table contents but you only want to clear the body, not the headers. Creating a <tbody> tag solves that problem while still allowing your function to be re-entrant (i.e. you can run it again later and it won't duplicate the contents).
Based on your code
$('.asoy').append('<tbody>
<tr> <td>'+ (angka++) +'</td>' +
'<td>' + val.OutletCode + '</td>' +
'<td>' + val.NipLeader + '</td>' +
'<td>' + val.NipChief +'</td>' +
'<td>' + val.NipRM +'</td>' +
'<td>----</td>' +
'</tr>
</tbody>
</thead>'); // <--- What this tag for?
I'm not sure but I think its a wrong tagging.
tbody should not be inside a thead unless your
header will consist of another table element

HTML form with lists generated thru Javascript using onchange event - not working as expected

I have a HTML form with a #List1, #Text1 and #List2. #List1 is generated through JSON via PHP from MySQL. #Text1 changes on user input. #List2 should also be generated through JSON from MySQL every time the user changes #Text1, using both the value selected in #List1 AND the contents of #Text1.
The data from the form is further used in PHP to generate a table with data via a query to MySQL.
I tried to use the onchange() event to generate #List2, but it doesn't work - #List2 remains empty after user input in #Text1, although the onchange() function is executed.
HTML
<div class="input_frm">
<form method="post" action="<?php print data_clean($_SERVER["PHP_SELF"]);?>">
<table class="input_tbl">
<tr>
<td class="a">Select county</td>
<td class="b"><select id="selJudet" name="Alfa" onchange="judetChg()"></select></td>
<td class="c"><input class="button_face" type="submit" value="Submit"></td>
</tr>
<tr>
<td class="a">Search zone as</td>
<td class="b"><input type="text" id="selText" name="Beta" maxlength="35" placeholder="Wildcard string" onchange="textChg()" /></td>
<td class="c"></td>
</tr>
<tr>
<td class="a">Select zone</td>
<td class="b"><select id="selZona" name="Gamma" onchange="zonaChg()"></select></td>
<td class="c"></td>
</tr>
</table>
</form>
</div>
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
});
});
function judetChg()
{
var selOption = document.getElementById("selJudet");
localStorage.setItem("selJudIndex", selOption.selectedIndex);
}
function textChg()
{
var selTextValue = document.getElementById("selText").value;
localStorage.setItem("selTextValue", selTextValue);
var selJudet = localStorage.getItem("selJudIndex");
//alert(selJudet);
var str_http = "/scripts/033B_GetJudetWildcdZona.php?judet=" + selJudet + "&textwildcd=" + selTextValue;
//alert(str_http);
$.getJSON(str_http, success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selZona").html("");
$("#selZona").append(str_options);
});
}
function zonaChg()
{
var selOption = document.getElementById("selZona");
localStorage.setItem("selZonaIndex", selOption.selectedIndex);
}
It works ! And now it seems very natural, considering it is based on events. (Just like in Visual Studio - only much harder to debug :)). The code might be improved to fire also on #List1.change - or not, depending on the logic of the form.
I had a single error in my PHP code, a $row['...'] variable which had an erroneous index which I did not notice, the error being there exactly because I copied the code from another script so as not to make mistakes !

how do i add functions to the events of dynamic elements in pure javascript?

My script dynamically writes HTML into my page. There are buttons that are written that I want to have onclick functions. Please don't suggest frameworks like jQuery since this is for my JavaScript development course. The assignment was to show that we know how to create, read and delete cookies. This script reads all cookies and displays their names and values with a delete button in a table. So far, the delete cookie function isn't called at all when you click any of the delete buttons. Thanks for your time.
document.getElementById("showCookies").onclick = function(){
var columnRight = document.getElementById('columnRight');
var cookies = document.cookie;
var cookiesContent = '<h1>Existing Cookies</h1>';
console.log(cookies);
cookies = cookies.split(";");
if(cookies.length > 0){
cookiesContent += '<table width="100%" cellspacing="1" cellpadding="10" border="0"> \
<thead> \
<tr> \
<th>Name</th> \
<th>Value</th> \
<th>Delete</th> \
</tr> \
</thead> \
<tbody> \
';
for(var i = 0; i < cookies.length; i++){
cookieAtts = cookies[i].split('=');
cookiesContent += "<tr> \
<td>" + cookieAtts[0] + "</td> \
<td>" + decodeURI(cookieAtts[1]) + '</td> \
<td><button onclick="deleteCookie(\'' + cookieAtts[0] + '\');">Delete</button></td> \
</tr>';
}
cookiesContent += "</tbody></table>";
}
columnRight.innerHTML = cookiesContent;
return false;
}
function deleteCookie(cookieName){
alert("Hello!");
return false;
}

Dynamic anchor tag inside <td>

I have a table and for one of the <td> I want to generate the <a> tags dynamically using JavaScript.
Writing a small snippet of the code.
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach (var item in list)
{
<tr>
<td>...</td>
<td>...</td>
<td> MyFunction(item.Parameter1) </td> // dynamic anchor tag
</tr>
}
</tbody>
</table>
JavaScript function.
MyFunction(Parameter1)
{
var aTag = "";
.....
..... //some formatting as per needs
aTag = '<a id="' + someId + '" alt="' + someAlt + '" title="' + someTitle + '" style ="color:Blue;text-decoration:underline;" href="#" onclick="fnAnotherFunction(' + P1 + ',' + P2 + ');">' + NameofTheTag + '</a>';
return aTag;
}
How can the string returning aTag form an <a> tag at the <tr> <td>..?
Is this possible or is their a better solution to this.
You could use .append() or .appendTo()
$('selectorForTD).append(MyFunction(item.Parameter1))`
or
var anch = MyFunction(item.Parameter1);
anch.appendTo($('selectorForTD');
I think this is what you're after.
Edit:
Since you're using jQuery, you could create your anchor element like:
MyFunction(Parameter1)
{
// var aTag = "";
.....
..... //some formatting as per needs
var aTag = $("<a>",{id:someID, alt:someAlt, title:someTitle}).css({ ...cssRules...}).click(function(e)
{
fnAnotherFunction(P1,P2);
});
return aTag;
}
Here's a quick fiddle to illustrate.

Categories

Resources