I have a table consisting of elements like this
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<button id="button"></button>
</tr>
How can i get all values of current row including selected option when press button by using jquery?
I want to get: 1 'a'('a' option selected for example) 3
If by "values" you mean the 1 and the 3 in the other two cells, you'd use closest to find the row, then use find or children to access the tds in it. Here's one way you might do it:
$("#button").on("click", function() {
// Get the row
var row = $(this).closest("tr");
// Get the cells and their contents:
row.children("td").each(function() {
var $this = $(this);
// Ignore the one with the button
if (!$this.find("button").length) {
// Does this one have the select?
var select = $this.find("select");
if (select.length) {
// Yes, use that
console.log(select.val());
} else {
// No, grab text
console.log($(this).text());
}
}
});
});
<table>
<tbody>
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<td>
<button id="button">I'm a button</button>
</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But refer to the API, there are lots of other ways you might access those tds.
Note that I wrapped the button in a td. Your original markup is invalid, you can't have a button as a direct child of a tr.
Also note that if you have more than one tr, you can't use id="button" on all of them (probably better to use a class), but I'm guessing from the ID that that's just a placeholder you put in for the question. :-)
Related
I have a table that is being populated by a foreach loop to get data from a database:
foreach ($retrieve_data as $retrieved_data) {
$content .= "
<tr id=\"id_$retrieved_data->id\">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type=\"button\" id=\"editImpressionsBtn\" value=\"Edit\">Edit </button>
</tr>";
}
I want to write a jQuery function that gets data from the table like the id, availableinv, and maxinv when the edit button is clicked.
jQuery(document).on('click', 'editImpressionsBtn', function() {}
How can I assign a variable in this function to the data in each of these columns for only the row that the edit button was clicked?
Something like this? One thing I noticed, you need to make sure to add the selector (. or # for class or ID) to the handler.
$('.table_selector tbody').on('click', '.editImpressionsBtn', function(){
row = $(this).closest('tr');
})
Then you can add values or ids and get them like this
var my_id_value = row.attr('id')
Target the TR and then the different TD's
$('#editImpressionsBtn').on('click', function() {
var tr = $(this).closest('tr');
var tds = tr.find('td');
var id = tds.eq(0).text();
var avb = tds.eq(4).text();
});
If you're generating more than one table on the serverside, make sure you don't use the same ID for all of them, use a class instead.
There are three parts to this answer. Two are core to your question, one is a coding option / improvement:
First:
As your table is being built in a loop, I presume you've got multiple rows. Be aware that you can not have multiple buttons with the same ID. This is not only semantically incorrect, it will cause issues with jQuery. So, change the id of the button to be a class instead:
<button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
Second:
Now, in your jQuery, you can access that row fairly easily:
jQuery(document).on('click', 'button.editImpressionsBtn', function() {
var row = $(this).closest('tr');
var id = row.find('td:eq(0)').text();
var posname = row.find('td:eq(1)').text();
// ... etc
});
Third:
Escaping quotes inside of quotes like you are doing is a pain to code, and more difficult to maintain and read. I'd recommend in this case using a HEREDOC.
Example:
$content .= <<<HTML
<tr id="id_$retrieved_data->id">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
</tr>
HTML;
I'm trying to create a dynamic table, in other words, a table where the number of columns per row
isn't necessarily the same as the other rows
can be changed live by the user
in every added column, there is contained a dropdown box which is filled using a database request.
I would like to be able to fill this dropdown once when the page loads, and not every time a column is added(it's for a calendar, so worst case: multiple times per row = 31*x).
I'm using jquery 1.9 and php 5.3 for my programming.
I've tried with JSON and $.post(), but this escapes too much of the needed slashes and quotes, and due to my version 5.3 of php, I can't use the "DO_NOT_ESCAPE_ANYTHING" constants provided in php 5.4+ (and yes, I know that that name isn't right, it's by heart)
So, heart of the question:
How do I use a combination of jquery and php to put a HTML -tag in a javascript variable to output on a jquery-handled button-click.
jsfiddle: http://jsfiddle.net/pjc3y/3/
code:
HTML:
<form name="myform" id="myForm" action="#test">
<div>
<table id="persCalTable">
<tr id="DAY_0">
<td>
<input type="text" name="name" size="25" value="Enter your name here!" />
</td>
<td>
<button id="eventAdder">add event</button>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="submitter" />
</div>
</form>
javascript:
function addCellToRow(row, cell) {
row.append(cell);
}
function expandCalendarTable(myObj) {
var DATA = myObj.closest('tr').attr('id').slice(4); //data is the number after DAY_
var selector = '#persCalTable #DAY_' + DATA; //selector is the table and the clicked row id
var cellHiddenField = '<input type="hidden" name="status" value="New" />';
var cellOtherData = "INSERT SELECT TAG HERE";
var cell = cellHiddenField + cellOtherData;
addCellToRow($(selector), cell); // add the cell to the row defined by the selector
eve.preventDefault(); // stop the page refresh(if not in a form, this is not needed, when in a form, this is needed)
//alert('Picked: ' + DATA);
}
$(document).ready(function () {
$("#submitter").click(
function (e) {
e.preventDefault();
alert($('#myForm').serialize());
});
$("[id^=eventAdder]").click(
function (e) {
e.preventDefault();
expandCalendarTable($(this));
});
});
While you can have differing columns per row in an HTML table, if you have the following:
<table>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
What you will end up with is a table with 3 columns, and in the second row the third cell will be empty and borderless. What you can do is use a seperate table for each row, set the widths as equal and calculate and set cell widths manually with jQuery.
As for the calendar. I would suggest you use JQueryUi, which has a great calender control or a similar library than going for a select. Either way, you can prepare the object ahead of time and store it in a variable. You will then have to use clone on it otherwise it will move to the last place you inserted it at.
$(function(){
// Prepare the select (obviously yours would be more complicated)
var select = $("<select>");
<?php for( $i = 0; $i < count($optionValue); $i++ ) { ?>
select.append($("<option value='<?php echo $optionValue[$i]?>'><?php echo $optionText[$i]?></option>"));
<?php } ?>
// Insert into relevant parts
$("#insert1").append(select.clone());
$("#insert1 select").attr("name", "select1");
$("#insert2").append(select.clone());
$("#insert2 select").attr("name", "select2");
})
I have a table where it's rows are generated by a foreach loop.
Each table row has two columns, one with a form and the other with the forms submitted data, which I have called notes. (and updates using a jQuery library without refreshing the browser).
<script>
$(".notes_column").each(function(){
var $myform = $(this).find('.notes_form');
var $mynotes = $(this).find('.notes');
$myform.validate({
submitHandler: function(form) {
$.post('process.php', $myform.serialize(), function(data) {
$mynotes.html(data);
});
}
});
}); // each function
</script>
<table id="myTable" class="tablesorter" border="1" cellpadding="5">
<thead>
<tr>
<th>Notes</th>
<th>Submit Note</th>
</tr>
</thead>
<tbody>
<?php
foreach($myarray as $myvar){
echo '
<tr>
<td>ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</td>
<td class="notes_column">
<form class="notes_form" action="" method="post">
<input class="q" type="text" name="notes" size="30" placeholder="Place your notes here..." />
<input class="searchsubmit" type="submit" name="submit" value="Submit" />
</form>
<div class="notes"></div>
</td>
</tr>
';
}
?>
</tbody>
</table>
Right now I use a jQuery each function which iterates through each table column, and for each column with the class name ".notes_column" populates a div with the class "notes" with the submitted data.
The question is listed inside the code with capitalized letters, how can I populate the other column with the forms submitted data?
Any ideas?
Ty
I would create a <div> in the first <td> such as
<td>
<div class="put_notes_here">ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</div>
</td>
Then populate it the same as you did before
$mynotes.closest("tr").find(".put_notes_here").html(data);
Change the selector for your each to $('#myTable tr'), then you can iterate through each in your table.
Then you could either do an each on the tr object to access each td, or make use of jQuery's :first-child and nth-child(2) etc in a subsequent selector
I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
<tr>
<td>
<input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>
<?php
}
?>
This resolves to something like this:
<tr>
<td>
<input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>
Notice the data hash attribute is different for each button. I want to process this button with my jquery code:
$(".play").click(function(){
var camerahash = $('input').data('hash');
console.log($('input').data('hash'));
});
No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.
$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input
You need to specify which input element to read.
Try something like:
$(".play").click(function(){
$this = $(this);
var camerahash = $this.data('hash');
console.log($this.data('hash'));
});
You are always calling the first object of .play. This would be a correct way:
$('.play').on('click', function(){
var camerahash = $(this).data('hash');
});
You could always grab them by using the .attr(data-hash) html5 attribute.
Try:
$('.play').on('click', function() {
var _hash = $(this).attr('data-hash');
console.log(_hash);
});
Your selector will return the first one that it comes to. Use this instead
<script>
$("input.play").click(function() {
alert($(this).data('hash'));
});
</script>
I'm somewhat new to jQuery, so I could use some help here.
This is my issue:
I have a PHP script outputting a dynamic table. Each row has an "edit" button, plus some other fields. Only 3 of those need to be turned into an input box. The edit button should only put that specific row into "edit mode." I got as far as assigning each row a unique class by adding a number to the end of it.
I have been able to use jQuery to change all of the rows into edit mode, but I need it to be specific to a row.
An example row would have classes like name0, price0, and desc0. The next row would go on to classes name1, price1, and desc1 (for the fields that need changed). How can I reference these values and pass them to jQuery so it processes an event on just those elements?
There are two ways of doing this:
Dynamically creating the elements when the button is pressed; or
Hiding and showing elements that already exist.
Too much DOM manipulation can be really slow (particularly on certain browsers) so I favour (2). So for example:
<table class="editable">
<tbody>
<tr>
<td>one</td>
<td>
<div class="view">two</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<div class="view">three</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<input type="button" class="edit" value="Edit">
<input type="button" class="send" value="Send" disabled>
<input type="button" class="cancel" value="Cancel" disabled>
</td>
</tr>
</tbody>
</table>
with:
table.editable div.edit { display: none; }
and
$(function() {
$(":button.edit").click(function() {
var row = $(this).closest("tr");
row.find("input.view").attr("disabled", true");
row.find("div.view").each(function() {
// seed input's value
$(this).next("div.edit").children("input").val($(this).text());
}).fadeOut(function() { // fade out view
row.find("div.edit").fadeIn(function() { // fade in edit
row.find("input.edit").removeAttr("disabled"); // enable edit controls
});
});
});
$(":button.cancel").click(function() {
var row = $(this).closest("tr");
row.find("input.edit").attr("disabled", true");
row.find("div.edit").fadeOut(function() {
row.find("div.view").fadeIn(function() {
row.find("input.view").removeAttr("disabled");
});
});
});
$(":button.save").click(function() {
// ...
});
});