Currently I am displaying a table of values, where the last column provides an "Edit" and "Delete" option. For simplicity, when they edit a row, I am just clearing each column's innerHTML and placing input fields there instead. I need to also replace the Edit/Delete links with Save/Cancel, however I need to create these buttons with JS/JQuery, attach click handlers to them append them to the innerHTML.
While I have found similar examples, I am not quite clear on how to accomplish this and would appreciate any help.
function editRecord(line)
{
var zone = "<?= $data['zone']; ?>";
// Store the original field values
var valueName = document.getElementById("entryName" + line).innerHTML;
var valueTTL = document.getElementById("entryTTL" + line).innerHTML;
var valueAddress = document.getElementById("entryAddress" + line).innerHTML;
// Replace existing row value with input fields to make edits
document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + valueName + "'>";
document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + valueTTL + "'>";
document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + valueAddress + "'>";
// Create Save button with click handler
// Create Cancel button with click handler
// Append these to the element below (replacing the Edit/Delete)
document.getElementById("entryOptions" + line).innerHTML = "<input type='button' value='Save'> <input type='button' value='Cancel'>";
}
After further tinkering, I managed to figure it out. Here is the working code should it end up helping anyone else.
function editRecord(line)
{
var zone = "<?= $data['zone']; ?>";
// Store the original field values
var originalName = document.getElementById("entryName" + line).innerHTML;
var originalTTL = document.getElementById("entryTTL" + line).innerHTML;
var originalAddress = document.getElementById("entryAddress" + line).innerHTML;
// Replace existing row value with input fields to make edits
document.getElementById("entryName" + line).innerHTML = "<input type='text' value='" + originalName + "'>";
document.getElementById("entryTTL" + line).innerHTML = "<input type='text' value='" + originalTTL + "'>";
document.getElementById("entryAddress" + line).innerHTML = "<input type='text' value='" + originalAddress + "'>";
document.getElementById("entryOptions" + line).innerHTML = "";
var saveButton = $('<button/>', {
text: "Save",
id: 'btn_Save' + line,
click: function ()
{
// Save the changes
}
});
var cancelButton = $('<button/>', {
text: "Cancel",
id: 'btn_Cancel' + line,
click: function ()
{
document.getElementById("entryName" + line).innerHTML = originalName;
document.getElementById("entryTTL" + line).innerHTML = originalTTL;
document.getElementById("entryAddress" + line).innerHTML = originalAddress;
}
});
$("#entryOptions" + line).append(saveButton);
$("#entryOptions" + line).append(cancelButton);
}
Related
I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'
I am creating a dynamic tr/td based on json data using below code.
for (i = 0; i < dataPoolJSON.length; i++) {
html += "<tr id ='row" + i + "' value ='" + dataPoolJSON[i].msisdn + "'><td><div class='group'><label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" + dataPoolJSON[i].msisdn;
html += "</label></div></td><td class='hidden-xs'><a id='viewUsage" + i + "' class='viewUsage' onclick='viewDataPoolUsage(this," + dataPoolJSON[i].msisdn + ");return false;' href=''>View Usage</a>";
html += "<div class='pool-usage hidden'></div></td>";
html += "<td><span id='dataAllowed" + i + "'><select>";
if (dataPoolJSON[i].userSetting != null) {
html += "<option selected='selected' value='" + dataPoolJSON[i].userSetting.alertPercentageData1 + "'>" + dataPoolJSON[i].userSetting.alertPercentageData1 + "</option>";
}
html += "</select></span></td></tr>";
}
$('#data-pool tbody').html(html);
Now on click on radio button i need to fetch the msisdn value and current option selected value as but it is not giving me required answer. I am getting the current option selected value but not the msisdn.
function submitNewDataUsagealerts() {
var jsonSubmitData = [];
var selectedData = document.getElementsByName("msisdnSelected");
var i = selectedData.length-1;
for ( j=0; j <= i; j++ ) {
if(selectedData[j].checked) {
var valueCurrent = $('#dataAllowed'+selectedData[j].value).find('option:selected').val();
var row = $('#label'+selectedData[j].value).val();
item = {}
item [0] = valueCurrent;
item [1] = selectedData[j].value;
}
}
}
To get the "value" from a label, use .text() rather than .val().
var row = $('#label'+selectedData[j].value).text();
As your label includes an input and the required text, you can put the text inside a container so that it can be referenced without including the input:
The label code is currently (irrelevant code removed) :
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>";
html += dataPoolJSON[i].msisdn;
html += "</label>";
change this to:
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<span>" + dataPoolJSON[i].msisdn + "</span>";
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value + ">span").text();
Alternatively, move the input out of the label as you're already using label for=:
html += "<input id='numView" + dataPoolJSON[i].msisdn + "' type='radio' class='iradio_minimal' value='" + i + "' name='msisdnSelected'/>" ;
html += "<label id='label" + i + "' for='numView" + dataPoolJSON[i].msisdn + "' class='ch-control'>";
html += dataPoolJSON[i].msisdn
html += "</label>";
Then your selector can be:
var row = $('#label'+selectedData[j].value).text();
var msg = document.getElementById('lbltxt').innerHTML;
alert(msg);
<label id="lbltxt" style="display:none">Test</label>
HTML Code
<label id="mylabel" />
JS Code
var lavelValue = $("#mylabel").text();
I have dynamically generated table using jquery. I want a cell of the table be converted to a textbox when clicked.
$.each(proc_msg, function (i, item) {
trHTML += "<tr><td>" + item.hq_code + "</td><td id='hq_" + item.hq_name + "'>" + item.hq_name + "</td>";
trHTML += "<td><a href='#' id='hq_ed_" + item.hq_name+_"' onClick='dataAction(this.id);'>Edit</span></a></td>";
});
$('#tbl_hqlist').append(trHTML);
function dataAction(dataValue){
var sectionName=dataValue.substr(0,2);
var hq_zone=dataValue.substr(5);
var zone_id ="";
zone_id= zone_id.concat("'#",sectionName, hq_zone,"'");
var tempHTML ="<input type='text' id='" + zone_id + "' value='" + hq_zone + "' />";
$(zone_id).html(tempHTML);
}
This code is throwing up error where "zone_id" is not defined.
I have a button called "Add" which relates to each person in a list.
echo <td><input type=\"submit\" id=\"PlayerAdded".$id."\" value=\"Add\"
onclick=\"add('".$id."','".$name."','".$_SESSION['GameID']."');\"></input></td>";
When "Add" is clicked, I want to add the persons details to a table (working fine), and also add a new row including their name and ID into a table in my DB (this is my problem).
I am aware that PHP won't work in a JS function. I'm also aware that I should never access the database on my site from JS due to the security issues.
So how can I have a button which onclick calls a function which adds to the database?
I tried writing my function in PHP, but it wasn't doing anything when I clicked the button. See my function below:
function add(id,name,game){
var t = ("</td><td>");
var str = ("<tr id='Players" + id + "'><td>")
var ctr = ("</td></tr>")
var PID = ("<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id)
var Pnam = ("<input type='hidden' name='Name" + id + "' value='" + name + "'></input>");
var place = ("<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>")
var points = ("<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>");
var cash = ("$<input name='Cash" + id + "' placeholder=' 0'></input>");
var ticket = ("<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>");
var del = ("<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>")
$('#PlayerAdded').before(str+ PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// This is where I want to insert into the db. Similar to
// <?php
// $sql = "INSERT INTO results (`col`, `col2`, `col3`) VALUES ('$id', '$name', '$game')";
// mysqli_query($dbcon,$sql); ?>
//but I want to be able to do it inside this java script function.
}
Remove the bracket before the variables, which you have written for every variable in function.
Add the ajax piece at the end of your function code.
function add(id, name, game) {
var t = "</td><td>";
var str = "<tr id='Players" + id + "'><td>"
var ctr = "</td></tr>"
var PID = "<input type = 'hidden' name='ID" + id + "' value='" + id + "'></input>" + id;
var Pnam = "<input type='hidden' name='Name" + id + "' value='" + name + "'></input>";
var place = "<select name='Place" + id + "'><option value='17'>17th</option><option value='16'>16th</option><option value='15'>15th</option><option value='14'>14th</option><option value='13'>13th</option><option value='12'>12th</option><option value='11'>11th</option><option value='10'>10th</option><option value='9'>9th</option><option value='8'>8th</option><option value='7'>7th</option><option value='6'>6th</option><option value='5'>5th</option><option value='4'>4th</option><option value='3'>3rd</option><option value='2'>2nd</option><option value='1'>1st</option></select>";
var points = "<form action='leaderboards.php' method='post' target='_blank'><input type='hidden' name='playerid' value='" + id + "'></input><input type='hidden' name='name' value='" + name + "'></input><input type='submit' value='View'></form>";
var cash = "$<input name='Cash" + id + "' placeholder=' 0'></input>";
var ticket = "<select name='Ticket" + id + "'><option value='No'>No</option><option value='Yes'>Yes</option>";
var del = "<input type='button' value='Delete' onclick='remove(" + id + ")'> </input>";
$('#PlayerAdded').before(str + PID + t + Pnam + name + t + place + t + points + t + cash + t + ticket + t + del + ctr);
// making ajax call to insert.php and posting the data
$.ajax({
method: "POST",
url: "insert.php",
data: {
"id": id,
"name": name,
"game": game
},
beforeSend:function(){
// show something before data is saved to db.
}
}).done(function(msg) {
$("body").append(msg); //debugging purpose
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
}
insert.php
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
$id= $_POST['id'];
$name= $_POST['name'];
$game= $_POST['game'];
//write your connection logic
// never write bare queries there is a chance of sql injection.
//Instead use prepared statement, prepare your query then bind the above values to it, then excute.
//write your insert logic below.
}
?>
You need to post the values you want to insert to your database via AJAX, append this to your add() function:
$.post('insertnew.php', { id:id,name:name,game:game }, function(data){
alert(data);
});
insertnew.php:
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['game'])){
// sanitize your data here, then:
$id = $_POST['id'];
$name = $_POST['name'];
$game = $_POST['game'];
//connect to your db, or instead include your dbconnect.php
$link= new mysqli('localhost', 'my_user', 'my_password', 'world');
// check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//use prepared statement, prepare your query then bind the above values to it, then excute
$stmt = mysqli_prepare($link, "INSERT INTO results VALUES (?, ?, ?)");
mysqli_stmt_bind_param($stmt, $id, $name, $game);
if(mysqli_stmt_execute($stmt)){
echo "Record has been added successfully";
}else{
echo "Sorry, record could not be inserted";
}
}
?>
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/mysqli-stmt.bind-param.php
I have this code
(in script):
var response = [{
"A":"a2",
"B":"b2",
"C":"c2"
},
{
"A":"a3",
"B":"b3",
"C":"c3"
},
{
"A":"a4",
"B":"b4",
"C":"c4"
}];
$.each(response, function(i, item) {
$('<tr>').html(
//"<tr>" +
"<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody');
});
and I want to change one of column (just for exp it's will be "A") to be "edited" by text-box.
I am tring this:
... `"<td><input type="text">" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable tbody');`...
but it's not working.
any help please!
If i understood correctly,
Instead of creating <tr>, later adding contents to it using html() and finally appending to do the <table>, you can directly add everything altogether to the <table> using append() method.
$.each(response, function(i, item) {
$('#MyTable tbody').append("<tr>"
+"<td><input type='text' value='"+ response[i].A +"'/> </td><td><input type='text' value='"+ response[i].B +"'/></td><td><input type='text' value='"+ response[i].C +"'/></td>"
+ "</tr>");
});
Try saying This
var firstcell = "<td><input type="text" value="VALUE"</td>";
firstcell = firstcell.replace('VALUE', response[i].A);
Use this for first cell in each Row. After that append this in whole row.