I want to get the text of just which table data is clicked on. i.e. get $post_no value if clicked on post_no, get the word 'description' if clicked on description. I have tried a number of ways but cannt get what i want. whats the approach?
my php code:
echo "<table border=1>";
echo "<tr><th>Post No</th><th>Writer ID</th><th>Writer Name</th><th>Title</th><th>Description</th><th>Summary</th><th>Approval</th></tr>";
while ($row= mysqli_fetch_array($r2)){
$post_no=$row['post_no'];
$writer_id=$row['writer_id'];
$writer_name=$row['writer_name'];
$title=$row['title'];
$description=$row['description'];
$summary=$row['summary'];
echo "<tr height='50' class='x"."". " '>";
echo "<td class='r'>".$post_no."</td>";
echo "<td class='r'>".$writer_id."</td>";
echo "<td class='r'>".$writer_name."</td>";
echo "<td class='r'>".$title."</td>";
echo "<td class='r'>".'description'."</td>";
echo "<td class='r'>".'summary'."</td>";
echo "<td class='r'>Approve</td>";
echo "</tr>";
}
echo "</table>";
javascript code;
<script>
$(document).ready(function(){
$(".x").each(function(i){
$(this).click(function(){
console.log($(this).children().eq(i).text());
});
});
});
</script>
I would do this
$('.x').click(function (e) {
var $target = $(e.target);
console.log($target.text());
});
So you just want the value of $post_no if you click on the according div? Then why don't you just bind the event on that class?
$(".r").click(function() {
console.log($(this).text())
});
Since people continue to downvote this - for whatever reason - here you go, fiddle. If i do something wrong, tell me and don't just downvote.
https://jsfiddle.net/LcbwL85m/
So you want to know on what value you've clicked on, but the binding remains on the row?
Perfectly possible:
$(document).ready(function(){
$(".x").click(function(event){
console.log(event.target); //Log where you clicked
console.log($(event.target).text());
});
});
Why should this work?
In the event handler that we add to the clicking event when we click the elements with class x (every row), we pass a reference to the event itself.
In this reference we have access to a lot of information about the event, like in this case the target. The target is the Element where there is really clicked.
Because Javascript works with event bubbling, you do not need to set the handler on every element, but you can set it on a top level (even on 'body' would work), and with this (event.target) you can see where the user really clicked.
Because we now know the element that the user clicked, we can pass that reference to a jQuery object ($(event.target)) and utilise the text() function.
echo "<table border=1>";
echo "<tr><th>Post No</th><th>Writer ID</th><th>Writer Name</th><th>Title</th><th>Description</th><th>Summary</th><th>Approval</th></tr>";
while ($row= mysqli_fetch_array($r2)){
$post_no=$row['post_no'];
$writer_id=$row['writer_id'];
$writer_name=$row['writer_name'];
$title=$row['title'];
$description=$row['description'];
$summary=$row['summary'];
echo "<tr height='50' class='x"."". " '>";
echo "<td class='r'>".$post_no."</td>";
echo "<td class='r'>".$writer_id."</td>";
echo "<td class='r'>".$writer_name."</td>";
echo "<td class='r'>".$title."</td>";
echo "<td class='r'>".$description."</td>";
echo "<td class='r'>".$summary."</td>";
echo "<td class='r'>Approve</td>";
echo "</tr>";
}
echo "</table>";
// jquery part
<script>
$(document).ready(function(){
$(document).on('click','.r',function(event){
event.preventDefault();
var td_txt = $(this).text();
console.log(td_txt);
//or you can use alert.
});
});
</script>
the php values of 'description' and 'summary' were not concatenated properly.
in the jquery part you can use alert as well to get the value of respective td
$(function() {
$("#table_test").find("td").each(function() {
$(this).click(function() {
alert($(this).text());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table_test" border="1">
<tr>
<td>One</td>
<td>Two</td>
</tr>
<tr>
<td>Three</td>
<td>Four</td>
</tr>
</table>
With this code, you can alert the value of each td.
This code use .each(), which is not advisable, better use event.target on click on table.
Not sure why everyone is going for complicated solutions. Just use a selector that targets the elements you desire:
$("tr.x td.r").click(function(){
console.log($(this).text());
});
or even just:
$(".r").click(function(){
console.log($(this).text());
});
Dynamic elements:
If you are after something more efficient, you can use a delegated event handler. This has the advantage that it will still work if items are added dynamically to the table:
$("table").on('click', 'td.r', function(){
console.log($(this).text());
});
This works by listening for events (in this case click) to bubble up to the non-changing ancestor element, then it applies the jQuery filter (in this case td.r) to just the elements in the bubble-chain. It then applies the function to just the element that caused the event. The upshot of all this is that the elements only need to exist at event time and not when the event was registered.
The target of the delegated event should be a non-changing ancestor element. In this example I just chose table. If nothing is close/convenient the default to use is document (do not use body as it has a bug that can stop mouse events responding)
Related
I am trying to use jquery to delete a row from a table when a button is clicked. The row is dynamically generated when the user clicks a + submit button.
Right now, when the button is clicked the form gets submitted. I'm trying to stop that with a return false. (Not sure how to implement prevent default in onclick)
I have tried 2 pieces of code. When using the onlick = 'return false;' on the button tag, it works fine. When I try to add a function call with it, it continues to submit the form and I'm at a wits end with this.
Variation 1 that doesnt work:
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td><button onclick='return delete_row();' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i></button></td>");
function delete_row(){
alert('hello');
return false;
};
Variation 2(also doesnt work):
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td><button onclick='return delete_row(); return false;' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i></button></td>");
function delete_row(){
alert('hello');
};
I also tried the return false in both places simultaneously but that doesn't work either. What am I doing wrong ?
Last Thing I tried was, this doesnt stop the submit either:
"<td><button class='remove' style='border: 0; background: none;'>"
$(document).ready(function(){
$('.remove').click(function(event){
event.preventDefault();
alert('test');
// var num = $(this).attr('value');
// console.log(num);
// $("#"+num).remove();
});
});
Why not use jQuery for this:
(function($, document){
$(document).ready(function($){
var countCourses = 'course-1'; //ids shouldn't start with a number (for testing)
$('#tbl').append(
"<tr id='"+countCourses+"'>"+
"<td>"+
"<button name='submit_delete' style='border: 0; background: none;'>"+
"<i class='fa fa-minus-circle fa-lg' style='color:red' ></i>"+
"</button>"+
"</td>"+
"<td>Foobar</td>"+ //for testing
"</tr>" //for testing
);
$('#tbl').on('click', 'button[name="submit_delete"]', function(e){
//return; //-- simply return before the remove action on some condition
$(this).closest('tr').remove(); //find the closest parent tr to the button and remove it
});
});
})(jQuery, document);
td{border:1px solid black;}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table id="tbl" >
</table>
I think the thing you were missing is $(this).closest('tr') - in the event handler this is the target of the event. So we can simply find the next parent row above this in the DOM and remove it.
event.preventDefault(); will prevent the default action of whatever it is your preventing. Since your already in the event handler it wont prevent your code in there from running there.
If you want to stop an actual form from submitting, both e.preventDefault() and return false will work from inside the event handler.
But, in your example:
$('.remove').click(function(event)
You have a class remove that I don't see on the button, but even if it was there you would need to use Event Delegation, because it's a dynamically rendered element. There is a good chance when you add a new row, your event is already bound and won't detect these new elements. Therefor you have to bind to a parent element that is present in the actual source code. Then you delegate it to the button as I did above. This way it can pick up those events and pass them to the dynamic elements.
That said it's been a long time since I looked up the docs on how jQuery handle events, it must have been like v 1.6 or something back in 2011 or so, that may have changed in the "mean" time... lol ... but I know this way works, so I just do it like that for the last 8 years or so. Well whenever they got rid of live anyway.
Cheers!
I have a main-page.php with a simple form (id=search) that performs a live search in a MySQL database and returns results in a list like this:
echo "<ul style=\"list-style-type: none;\">";
while($row = mysql_fetch_assoc($sql)) {
echo "<li>".$row['Long_Desc']."";
}
echo "</ul>";
What I need is a JQuery function to allow me to click on any of the returned list items from the above list, but instead of being directed to next-step.php, I would like to stay on main-page.php, and have the div "results" on this page updated with the contents of the next-step.php script.
Of note, next-step.php performs another SQL search and returns results as a form element with radio buttons that are built with an echo command - something like this:
echo "<form id=choices>"
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<input type=RADIO name=\"food_quantity\" value=\"$line[Gm_Wgt]\">";
echo "<b>$line[Amount] $line[Msre_Desc]</b> ($line[Gm_Wgt] grams)";
}
echo "<INPUT type=RADIO name=quantity>";
echo "<INPUT type=text NAME=my_quantity SIZE=4 value=\"\"> <b>grams</b>";
echo "<input type=submit name=Submit value=\"Submit\">";
echo "</form>";
Finally, what I'd like to be able to do with the form "choices" is to check a radio button option, send the selection to an external php page (let's call it last.php), where yet another SQL search is performed, the results of which should then be returned as a blcok of formatted HTML into the original "results" div of main-page.php.
Thank you for your help!
Here are the simple and easy 4 steps that i would recommend you and you shall customize it to your need
Step 1 : Write a Jquery function onclick()
<script>
$( "#yourID" ).click(function() {
$( this ).slideUp();
});
</script>
Step 2 : Do an ajax call and send value to the Server
$.post( "yourServer.php", { data: "yourData" })
.done(function( data ) {
});
Step 3 : Get the value in server side
$data = $_POST['data'];
#Do some process and get the result
Step 3 : Send the Results
echo json_encode($yourData)
Step 4 : Get the results in JQuery success event & Show in the div that you need to update
if(success.data==1)
{
$('#yourResult').html(data.name);
}
else
{
$('#yourResult').html(data.error);
}
Hope this helps you !
How can I change the ondblclick event to onclick event when page detects that its on IOS/Android etc. What makes it difficult is I cannot just call the ID of the element since it carry data from database to Javascript function.
Check it out.
Server-side:
<?php
echo '<table>';
while($row=mysql_fetch_array($query)){
echo '<tr><td ondblclick="sampFunc("'.$row[0].'","'.$row[1].'")">';
echo $row[0];
echo '</td></tr>';
}
echo '</table>';
?>
Client-side:
<script>
$(document).ready(function(){
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)){
/* ?????????????????? */
}
});
function sampFunc(data1,data2){
//-- Something
}
</script>
I think you should re-write some of you code to make it easier to achieve what you want.
Trying to sniff the user agent isn't a great idea. Devices can change, new OS's can be launched and it requires more maintenance on your end. Feature detection is a much better approach as it covers devices now and in the future as well as minimising false positives.
The updated PHP now uses the HTML5 data-* attribute and removes the inline event:
<?php
echo '<table class="myclass">';
while($row=mysql_fetch_array($query)){
echo '<tr><td data-a="'.$row[0].'" data-b="'.$row[1].'">';
echo $row[0];
echo '</td></tr>';
}
echo '</table>';
?>
The new JS checks whether it's a touchscreen device and defines a variable touchDevice as true or false depending on which it is. This var is then used to define the event. If it's true (device is touch capable) then click is the event, otherwise it's dblclick.
The event handler now uses .on() instead of being defined inline and it makes use of the .data() function.
<script>
var touchDevice = !!('ontouchstart' in window) || !!('onmsgesturechange' in window);
$(document).ready(function(){
var dblevent = touchDevice ? 'click' : 'dblclick';
$('.myclass td').on(dblevent, function(){
var data1 = $(this).data('a'), data2 = $(this).data('b');
//-- Something
});
});
</script>
or simply use the updated PHP and the doubletap event:
$('.myclass td').on('dblclick doubletap', function(){
var data1 = $(this).data('a'), data2 = $(this).data('b');
//-- Something
});
Here is my block of Php code in which I am rendering the table row:-
Actually what I am trying to achieve is that on the click of the button in the first row I should be able to show the next row, which is previously hidden by using .hide() in the document ready script.
<?php
echo "<tr>";
echo "<td>"."<button id= \"btnnumber_". $i ." \" class=\"btn info toggler\" data-value=\" $val\">Show Info <i class=\"icon-arrow-down\"></i></button>"."</td>"; // On click of this button I am taking its id in Jquery getting the number at end creating the id of the next row in the Jquery script.
echo "</tr>";
echo "</tr>";
echo "<tr id=\"row_$i \" class=\"info_row\">";// This row is dynamically generated one each row has its unique id like 0 row is having id row_0,1 row is having id row_1 etc.
echo "<td id=\"student_count\">"."students count:"."</td>";
echo "<td id=\"start_date\">"."start date: "."</td>";
echo "<td id =\"end_date\">"."end date: "."</td>";
echo "<td></td>";
echo "</tr>";
?>
This row is initially set to hide in document ready by using the following JQuery:-
$(function(){
$('.info_row').hide();// On document load I am hiding all the element with class info_row.
$('.toggler').toggle(function(){// Then I am toggling between hide and show.
var currentId = $(this).attr('id');
var number = currentId.substr(currentId.length - (currentId.length - currentId.indexOf("_") - 1));
var rowId = 'row_' + number;
$("#" + rowId).show();
}, function(){
var currentId = $(this).attr('id');
var lastChar = currentId.substr(currentId.length - (currentId.length - currentId.indexOf("_") - 1));
var rowId = 'row_' + lastChar;
$("#" + rowId).hide();
});
});
I am not able to achieve the toggle i.e the row is not hiding and showing as I was trying to achieve.
Any help will be highly appreciated.
This line look like a problem
echo "<tr id=\"row_$i \"
In that there is a spurious space in the id.
echo "<tr id=\"row_$i\"
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<script type='text/javascript'>
$(window).load(function(){
$('#varx2').click(function() {
$("#txt").toggle(this.checked);
});
});
</script>
<?php
print "<table>";
if($items)
foreach($items as $i){
print "<tr>";
print"<td><input type='checkbox' id='varx2' name='checkbox[]' value='$i->logi_id'/></td>"; //CHECKBOX
print "<td id='txt' style='display:none'>$i->logi_jo</td>";
print "<td>$i->logi_cntrlnum</td>";
print "</tr>";
}
print "</table>";
?>
gud day, this is a show/hide java script.. when i click or check the checkbox, the row will extent beside, the problem is only the first row/result is extending.. can u pls help me.. ty
IDs must be unique, ID selector only selects the first element that has a specific ID, you should use classes instead:
print "<td class='txt' style='display:none'>$i->logi_jo</td>";
Id's for each element need to be unique. JQuery will just select the first one, unlike a class selector for example will select all elements with a class. Try set the id to the item id or name or something else unique.
Remove id and put it as a class.
jQuery function will be
$('.varx2').each(function(){
$(this).click(function(){
// do whatever you want
});
})