How to get value from td hidden field through jquery - javascript

I have a dynamic table. I am trying to get a value of a hidden field which is order_id, but I am getting only the first id. If I click on the 3rd or 4th etc button I still get the order_id of the first td. Below is my code :
<tr>
<td>id</td>
</tr>
<tr>
<td>
<input type="hidden" id="hid" value="<?php echo $id; ?>">
<input type="button" id="sends" value="Send" onclick="sendemails();">
</td>
</tr>
<script>
function sendemails(){
var sends = $('#sends').val();
var hid = $('#hid').val();
alert(hid);
}
</script>

You can use another solution
<tr>
<td>id</td>
</tr>
<tr>
<td>
<input type="hidden" id="hid" value="<?php echo $id; ?>">
<input type="button" id="sends" value="Send" onclick="sendemails(<?php echo $id; ?>);">
</td>
</tr>
<script>
function sendemails(hid){
alert(hid);
}
</script>
And note that attribute "id" had to be UNIQUE.

The issue is because you are presumably repeating that row in the table, which will result in the id of both the button and input being repeated throughout the page, which is invalid. You need to use classes, attach your events in JS and then traverse the DOM to find the related hidden input. Try this:
<tr>
<td>id</td>
</tr>
<tr>
<td>
<input type="hidden" class="hid" value="<?php echo $id; ?>" />
<input type="button" class="sends" value="Send" />
</td>
</tr>
$(function() {
$(document).on('click', '.sends', function() {
var sends = $(this).val();
var hid = $(this).prev().val();
alert(hid);
});
});
Note that I used a delegated event handler as you stated the table is dynamically generated.

Try add "this" in onclick event like this: onclick="sendemails(this);" and get this on your function.
Try:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>id</td>
</tr>
<tr>
<td>
<input type="hidden" id="hid" value="hid">
<input type="button" id="sends" value="Send" onclick="sendemails(this);">
</td>
</tr>
</table>
<script>
function sendemails(btn){
var sends = btn.value;
var hid = $("#" + btn.id).closest("td").find("#hid").val()
alert(hid)
}
</script>

Related

How to pass a Javascript variable to PHP to store in MYSQL database

I'm trying to pass a javascript variable to PHP so when I submit my form, it will save the variable in my MYSQL database.
Heres the HTML:
function replyLink(element) {
document.getElementById('displayForm').style.display = "block";
var replyId = element.getAttribute("data-replyid");
console.log(replyId)
}
function closeLink() {
document.getElementById('displayForm').style.display = "none";
}
<a href='javascript:void(0);' data-replyid='1' class='replyLink' onclick='replyLink(this)' />[Reply]</a>
<div id='displayForm' style='display:none;'>
<div id='replyTitle'>
<label>Write a reply</label>
<a href='javascript:void(0);' onclick='closeLink()' />[Close]</a>
</div>
<form action='' method='POST' accept-charset='utf-8' enctype='multipart/form-data'>
<table id='postForm'>
<tr>
<td class='replyForm_title' sty>Name</td>
<td><input type='text' name='commentName'></td>
</tr>
<tr>
<td class='replyForm_title'>Comment</td>
<td><textarea cols='48' rows='4' wrap='soft' name='commentText'></textarea></td>
</tr>
<tr>
<td></td>
<td><input type='submit' name='commentBtn' value='Reply' onclick='submitForm()'></td>
</tr>
</table>
</form>
</div>
If you run the code, you can see that the form pops up, and returns the data-attribute value of '1'. I'd like to insert that variable 1 into a MYSQL database. Would anyone guide me? Thanks. (ALSO, code snippet runs. So you have an understanding of how it works.)
Add a hidden input to the form, and put replyId into its value.
Then in PHP use $_POST['replyId'] to get the value.
function replyLink(element) {
document.getElementById('displayForm').style.display = "block";
var replyId = element.getAttribute("data-replyid");
document.getElementById('replyId').value = replyId;
console.log(replyId)
}
function closeLink() {
document.getElementById('displayForm').style.display = "none";
}
<a href='javascript:void(0);' data-replyid='1' class='replyLink' onclick='replyLink(this)' />[Reply]</a>
<div id='displayForm' style='display:none;'>
<div id='replyTitle'>
<label>Write a reply</label>
<a href='javascript:void(0);' onclick='closeLink()' />[Close]</a>
</div>
<form action='' method='POST' accept-charset='utf-8' enctype='multipart/form-data'>
<table id='postForm'>
<tr>
<td class='replyForm_title' sty>Name</td>
<td><input type='text' name='commentName'></td>
</tr>
<tr>
<td class='replyForm_title'>Comment</td>
<td><textarea cols='48' rows='4' wrap='soft' name='commentText'></textarea></td>
</tr>
<tr>
<td><input type="hidden" name="replyId" id="replyId"></td>
<td><input type='submit' name='commentBtn' value='Reply' onclick='submitForm()'></td>
</tr>
</table>
</form>
</div>

Appending data to <tfoot> section

I have a table that populates with contents from a database. A user should be able to add as many new entries as they want to the table (let's ignore the 'save' button for now).
I attempt to add new rows to the table with
$("#businesscategorytable tfoot").append(addNewRow);
where addNewRow is formatted like the other rows in the table. However, this procedure does not work. What is even more confusing is that a similar module was used in a separate page of the project I'm working on and everything functions properly.
Here's a Stack Snippet that provides a bare-bones mock-up of what I'm working with:
$(function() {
//Remove Row Function for Business Category Tables
$("table[id='businesscategorytable']").on("click", "input[id='btnDeleteRow']", function() {
$(this).closest('tr').hide(); //hiding rows instead of removing so we only commit on 'Save'
});
//End Remove Row Function for Tables
//Add Row Function for Business Category Tables
$("input[id='btnAddBusinessRow']").click(function() {
var addNewRow = "<tr><td style=\"display: none\"><input type=\"hidden\" class=\"hdnBusinessCatId\" id=\"hdnBusinessCatId" + idCount + "\" />" +
"<td><input type=\"text\" id=\"businessCat" + idCount + "\" size=\"12\"></td>" +
"<td><input type=\"text\" id=\"businessColor" + idCount + "\" size=\"8\" value=\"$\"></td>" +
"<td><input type=\"button\" id=\"btnDeleteRow\" value=\"Delete\"\"></td>" +
"</tr>";
$("#businesscategorytable tfoot").append(addNewRow);
idCount++;
});
//End Add Row Function
});
<table border="1" id="businesscategorytable">
<thead>
<tr style="color:white;background-color:darkgray">
<th>Category Name</th>
<th>Color on Map</th>
</tr>
</thead>
<tbody>
<tr>
<td style="display: none">
<input type="hidden" class="hdnBusinessCatId" id="0" />
</td>
<td>
<input type="text" id="txtCategoryName0" size="12" value="0">
</td>
<td>
<input type="text" id="txtCategoryId0" size="8" value="Red">
</td>
<td>
<input type="button" id="btnDeleteRow" value="Delete">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td style="display: none">
<input type="hidden" class="hdnBusinessCatId" id="hdnBusinessCatId0" />
</td>
<td>
<input type="text" id="businessCat0" size="12" />
</td>
<td>
<input type="text" id="businessColor0" value="$" size="8" />
</td>
<td>
<input type="button" id="btnDeleteRow" value="Delete" />
</td>
</tr>
</tfoot>
</table>
<input type="button" id="btnAddBusinessRow" value="Add" />
Any ideas as to why this may not be working?
If you check your console you can see that idCount is undefined you need to declare idCount as a variable somewhere. I did that and it seemed to work how you declare idCount is up to you but it should definitley not conflict with the current id's you set it up with. Here's a JS Bin of that. I just added var idCount=1 before the click handler. It probably worked on the other page because idCount was declared there.

Multi level add more button using jquery

I want to develop a multilevel add more button using jquery.
I did that functionality, but its not success. It has many bugs. Some Logical issues are there...
My actual requirement there is one "Add more" button. When we click this add more button one Div will open. In side that div there is one text box and another one "add more" button
For example, First i add the main option value is "Bajaj". Under this option i want to add some options like "Discover", "Platina",...
Then i click next add more button and add the next option value is "Yamaha" under this Option i need to add sub options like FZ,YBR, Ray...
<div id="tabularoptions">
<input id="btnAdd" type="button" value="Add Options" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
<?php
if ($form['tabularOptions'] != '') {
foreach ($form['tabularOptions'] as $opt) {
?>
<div style="border:1px solid #ccc;margin: 10px;">
<table>
<tr>
<td>Option Value :</td>
<td>
<input name = 'tabluarOptionValue_<?php echo $opt['id']; ?>' type="text" value = "<?php echo $opt['tabularOptionValue']; ?>" />
<input type="hidden" name="tabluarOptionId_<?php echo $opt['id']; ?>" value="<?php echo $opt['id']; ?>">
</td>
<td><input type="button" value="Remove" class="remove" /></td>
<?php
if ($form['tabularSubOptions'] != '') {
foreach ($form['tabularSubOptions'] as $optsub) {
if ($optsub['tabularOptionId'] == $opt['id']) {
?>
<tr>
<td>
<input type="text" name="tabularSuboptionValue_<?php echo $optsub['id']; ?>" value="<?php echo $optsub['tabularSuboptionValue']; ?>">
<input type="hidden" name="tabularSuboptionId_<?php echo $optsub['id']; ?>" value="<?php echo $optsub['id']; ?>">
<input type="button" class="subOptionRemove" value="X">
</td>
</tr>
<?php
}
}
}
?>
</tr>
<tr>
</tr>
<tr>
<table>
<tr class="subOptionDiv">
<td><input class = "btnAdd1" type="button" value = "Add Suboptions" /></td>
</tr>
</table>
</tr>
</table>
</div>
<?php
}
}
?>
</div>
<script>
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
$("body").on("click",".btnAdd1", function () {
$(this).closest("table").append('<tr>\n\
<td>\n\
<input type="text" name="tabularSuboptionValue_'+j+'[]">\n\
<input type="button" class="subOptionRemove" value="X">\n\
</td>\n\
</tr>');
});
$("body").on("click",".subOptionRemove", function () {
$(this).parent().remove();
});
});
var j = 1;
function GetDynamicTextBox(value) {
j=j+1;
$('#optionCount').val(j);
// alert(j);
return '<div id='+j+' style="border:1px solid #ccc;margin: 10px;"><table>\n\
<tr>\n\
<td>Option Value :</td>\n\
<td><input name = "tabluarOptionValue_'+j+'[]" type="text" value = "' + value + '" /></td>\n\
<td><input type="button" value="Remove" class="remove" /></td>\n\
</tr>\n\
<tr>\n\
</tr>\n\
<tr>\n\
<table>\n\
<tr class="subOptionDiv"><td><input class = "btnAdd1" type="button" value = "Add Suboptions" /></td></tr>\n\
<tr>\n\
<td>\n\
<input type="text" name="tabularSuboptionValue_'+j+'[]">\n\
<input type="button" class="subOptionRemove" value="X">\n\
</td>\n\
</tr>\n\
</table>\n\
</tr>\n\
</table></div>';
}
</script>
Please try this code may be usefull for you.
Put this jquery/javascript code where you js code is.
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
Put this code in your php/html file where you want the text box.
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Try this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<table width="100%" cellpadding="0" cellspacing="0" id="type">
<tr >
<td align="left">Subcategory</td>
</tr>
<tr>
<td>Type : <input type="text" name="type" id="type" /></td>
</tr>
<tr>
<td>
<table width="100%" cellspacing="0" cellpadding="0" >
<tr>
<td>
<table width="100%" cellspacing="0" cellpadding="0" id="subtype1">
<tr>
<td>
Subtype : <input type="text" name="type" id="type" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<div>
<input type="button" name="addsub" value="Add Subtype" onclick="addmore('1')" />
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div>
<input type="button" name="add" value="Add Type" onclick="addmoretype()" />
</div>
Javascript
num = 2;
function addmore(id)
{
var tablename = "#subtype"+id;
$(tablename+' tr:last').after('<tr><td> Subtype: <input type="text" name="type" id="type" /> </td> </tr>');
}
function addmoretype()
{
$('#type tr:last').after('<tr> <td>Type : <input type="text" name="type" id="type" /></td></tr> <tr> <td><table width="100%" cellspacing="0" cellpadding="0" > <tr> <td> <table width="100%" cellspacing="0" cellpadding="0" id="subtype'+ num+'"> <tr> <td> Subtype : <input type="text" name="type" id="type" /></td></tr> </table></td> </tr><tr> <td> <div> <input type="button" name="addsub" value="Add Subtype" onclick="addmore('+ num+')" /> </div> </td> </tr></table> </td></tr>');
num++;
}
see working example

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

add input type upon button click

I am trying to add an type upon clicking the button.
Here is my jquery script:
$(function(){
$("#add").click(function(){
$("#inputboxes").append("<tr class='light'><td colspan='3' class='header'>Subject Name</td><td colspan='3'><input type='text' name='subject_name' /></td></tr>");
})
});
Then my HTML markup:
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table cellpadding="0" cellspacing="0" style="text-align:center;">
<thead>
<tr>
<th colspan="7">Add subject on the list of available subjects</th>
</tr>
</thead>
<tbody id="inputboxes">
<tr class="dark">
<td colspan="7">
<input type="button" id="add" value="Click to add a subject" />
</td>
</tr>
</tbody>
<tbody>
<tr class="dark">
<td colspan="7"><input type="submit" name="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</form>
#on page top
if(isset($_GET['submit']) print_r($_GET); // the only entry of array is the [submit'] => "Submit"
I can successfully generate an box, however it seems that whenever I hit submit, the box doesn't seem to be passed. Also how can I generate an increment in the name="" of generated box.
For the record, I found the workaround for this, moved the form tag outside of the table. Thanks everyone.
For the submit button to work, you need to put your inputs in a form. You can add an increment in the name if you want to, but it is not necessary. If you submit inputs with the same name, they will be submitted as an array.
Adding increment:
$(function(){
var i = 1;
$("#add").click(function(){
$("#inputboxes").append("<tr class='light'><td colspan='3' class='header'>Subject Name</td><td colspan='3'><input type='text' name='subject_name" + (i++) + "' /></td></tr>");
})
});
Adding form:
<form action="url" method="POST">
<table>
<tbody id="inputboxes">
<tr class="dark">
<td colspan="7"><input type="button" id="add" value="Click to add a subject" /></td>
</tr>
</tbody>
<tbody>
<tr class="dark">
<td colspan="7"><input type="submit" name="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</form>

Categories

Resources