I'm having trouble keeping event handlers attached to future loaded selectors. For example, when pull.php is loaded, the confirmdelete is no longer hidden, and also the click event handlers no longer exist. I am new to jquery and ajax. Below is my code.
$id= (int)strip_tags($_GET['id']);
$(document).ready(function() { //make a comment delete js file eventually, just so we can reference the source
$('.confirmdeletecomment').hide();
$('.deletecomment').on("click", function(e){
var cid = $(this).attr("id");
$('a#c'+cid).show(500, function(){ //right now as call back
$(this).on("click", function(e){
var id = $(this).attr("id");
var did = id.substring(1);
$.post(
'deletecommentdata.php?cid='+did,
function(data)
{
$("#commentarea").load("pull.php?id=<? echo $id; ?>");
$("#comment").val("");
$('.confirmdeletecomment').hide();
}
)
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
</script>
the below script is the php part:
<div id="commentarea">
<?
$query = mysql_query("SELECT users.user_id, users.username, users.miniavatar, comments.comment_id, comments.comment, comments.time_stamp FROM users INNER JOIN comments ON users.user_id=comments.products_users_user_id WHERE comments.products_products_id = '$id' ORDER BY comments.time_stamp DESC");
while($row2 = mysql_fetch_array($query)) {
?>
<div id='singlecomment'>
<hr class="comment" />
<table>
<col width="*" />
<col width="400" />
<col width="*" />
<tr>
<td valign = "top" rowspan="2">
<img src="<? echo $row2['miniavatar']; ?>" height="52" width="52" /> <br />
<?
if ($user_id == $row2['user_id']) {
$cid = $row2['comment_id'];
echo "<a id='$cid' class='deletecomment' title='Delete Post'>X</a>  ";
echo "<a id='c$cid' class='confirmdeletecomment'>confirm</a>";
}
?>
</td>
<td valign="top">
<a class="blue" href="collection.php?profile=<? echo $row2['user_id']; ?>"> <? echo $row2['username']; ?> </a>
</td>
<td>
<span class="date"><? echo date("F j, Y g:i a ", strtotime($row2['time_stamp'])); ?> </span>
</td>
<tr>
<td colspan="2">
<? echo stripslashes($row2['comment']); ?> <br/><br/>
</td>
</tr>
</table>
</div>
What you need to do is use 'on' like it's meant. Right there all you're doing is binding a .click event to that element in the selector.
What you want is:
$('body').on("click", ".deletecomment", function(e){
or something in place of 'body' that is a wrapper that can watch that level of the DOM for new elements to apply the event too.
I am guessing the event got messed up since you are the passing the event handler from
$('.deletecomment').on("click", function(e){
to
$(this).on("click", function(e){
Change the event names, if you really want to handle them separately. More like updating your second handler as these will do goo
$(this).on("click", function(event){
Since I dont have your markup structure, I am guessing, when you are loading pull.php to #commentarea, another element with class confirmdelete should have been loaded as well, thus making the code execution incomplete logically.
Put, $(".confirmdelete").hide(); right above e.preventDefault() to see if I am right.
You should look into the event delegation system http://api.jquery.com/on/
Try JQuery live. more info It should be something like the following
<script type="text/javascript">
$(document).ready(function() { //make a comment delete js file eventually, just so we can reference the source
$('.confirmdeletecomment').hide();
$('.deletecomment').live("click", function(){
var cid = $(this).attr("id");
$('a#c'+cid).show(500, function(){ //right now as call back
$(this).on("click", "a", function(e){
var id = $(this).attr("id");
var did = id.substring(1);
$.post(
'deletecommentdata.php?cid='+did,
function(data)
{
$("#commentarea").load("pull.php?id=<? echo $id; ?>");
$("#comment").val("");
$('.confirmdeletecomment').hide();
}
)
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
e.preventDefault();//so it doesn't interpret is as an anchor link
});
});
</script>
Related
In a table I display several links whose value (user id) is extracted from a database. By clicking on the link appears a modal pop up in which I would like to pass the selected value.
Here is the table:
<table>
<tr>
<td>Username</td>
<td>Id</td>
</tr>
<?php
include ‘db_connection.php’;
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row[userID]?></td>
<td>
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
</td>
</tr>
<?php } ?>
</table>
If I click on the link Show appears the modal pop up:
<div id="basic-modal-content">
<?php
if(isset($_GET[‘userID’])){
$userID = $_GET[‘userID’];
echo ‘UsuerID: ‘ .$userID;
}
?>
</div>
This is the script I used
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content').modal();
return false;
});
});
Since I have little familiarity with the jQuery framework I would like to ask you how can I pass the selected value within the modal and then use it.
jquery allows you to use the .data() attribute
<div id='basic-modal'>
<a href="?id=<?php echo $row[userID]?>" data-mydata="<?php echo $row[userID]?>" class='basic'>Show</a>
</div>
and then u can retrieve data from 'data-mydata' attribute:
jQuery(function ($) {
$('#basic-modal .basic').click(function (e) {
$('#basic-modal-content')
.text($(this).data('mydata'))
.modal();
return false;
});
});
i have a while loop in my coding
while (($i < $num3b)&&($i < ($start+$perpage))) {
$tododetail_id=mysql_result($result3b,$i,"tododetail_id");
$comment=formatUrlsInText(mysql_result($result3b,$i,"comment"));
$staff_name=mysql_result($result3b,$i,"staff_name");
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id='create-user'>Reply Message</span>";
$i++;}
How can onclick "Reply Message" jquery will popup $staff_name and $comment accordingly.
This is my jquery code
$( '[id^="create-user"]')
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
Thanks
You could use the data-attributes
HTML
<span style='float:right' class="reply" data-staffname="staffname" data-comment="staff comment">Reply Message</span>
jQuery
$(document).ready(function() {
$('span.reply').click(function() {
var staffname = $(this).data('staffname');
var comment = $(this).data('comment');
alert(staffname + ': ' + comment);
});
});
When you echo tags, I can't see you are closing them anywhere. Your HTML must be correct in order for jQuery to work properly. Also ID must be unique so use class.
HTML
<tr>
<td>
<span style="color: #5858FA;">SOMETHING 2</span>
<span class="create-user">Reply Message</span>
</td>
</tr>
JS
$('.create-user').click(function(){
var $text = $(this).prev().text();
alert($text);
});
DEMO
Your HTML is a mess, and your jQuery doesn’t correspond with it. You have this line:
$( "#dialog-form" ).dialog( "open" );
But you haven’t shown us any HTML that includes an element with the ID dialog-form.
You should restructure your HTML so you don’t use the font tag, every ID is unique, and tags are properly nested and closed. Run your output HTML through the validator if you’re not sure.
Then, you can do something like this:
$('span').click(function(){
alert($(this).closest('.comment'));
});
Obviously you’ll have to put the comment data in an element with the class comment.
Also, if you want to select an element by its ID with jQuery:
// Incorrect
$('[id^="create-user"]')
// Correct
var $createUser = $('#create-user');
// Also correct (normal JavaScript)
var createUser = document.getElementById('create-user');
id must be unique give it as something like the id from the database. Then put the jquery script inside the loop. or else in the html use a onclick function which passes the id to the JavaScript function.
<?php
echo "<tr><td><span><font color='#5858FA'>" . $staff_name . nl2br($comment) . "</font>
<span style='float:right' id="<?php echo $row['id'];">Reply Message</span>";
$i++;
?>
<script type="text/javascript">
$( "#<?php echo $row['id']; ?>")
.click(function() {
var nameStf = $(this).data('id');
alert (nameStf);
$( "#dialog-form" ).dialog( "open" );
});
</script>
<?php }?>
Try not to use html inside an echo statement since echo is a php statement which loads from the server which is slower than normal html which loads in the browser.
I'm building a website where the admin can make settings for the website. I would like the admin settings page to have a similar "feel" as the rest of the website, which has some nice looking jQuery features.
On the admin site there's a hidden div, which is shown when one of six links has been clicked. I'd like the content of the hidden div to change content before showing itself. I'm not sure how to do this. I could have a div box for every link on the page. But this becomes pretty cumbersome since I'd need to repeat my css and jquery for every link. I imagine that this, somehow, can be done with some javascript/jquery code that determines which link that was click and then decides which php function to call inside the hidden div. Then the php could "echo" out the content of the div, which then could be shown.
How could one do this?
My HTML/jQuery code is as follows:
--- The html links ---
<table id="settings">
<tr>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
<td>
<img src="images/folder.gif" alt="" height="100"/>
</td>
----- The Hidden div -----
<div id="dashboard_box">
<div class="dashboard_inside">
<form action="#" method="post">
<p style="font-size:20px; font-weight: bold;">Change color</p>
</br>
<fieldset>
<? load_content1();?>
</fieldset>
</form>
</div>
</div>
---- jquery code (working)----
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
You probably want to use ajax to load the content from the server. Take a look at jquery's .load() method: http://api.jquery.com/load/
You could include a data attribute per link:
<a class="action" data-content="content.php?method=load_content1"></a>
<a class="action" data-content="content.php?method=load_content2"></a>
js would look something like this:
$(".action").on('click', function() {
$("#dashboard_box fieldset").load($(this).data('content'), function() {
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
}
return false;
});
Then, in your content.php file you could check the method parameter in the url to determine what content to return.
My php is a little rusty, but something like this:
<?
call_user_func($_GET['method']); // i'm not sure how safe this is. you may want to be more explicit
?>
You can just add data attribute in each of your link's
<a href="#" data-url="content1.php" ..
Then on click of any of the a you can get the php to be called.
$('a').on('click',function(){
var phpFunctionToCall = $(this).data('url');
});
You probably need to make ajax call to load content into your fieldset As this <? load_content1();?> run's on server and javascript have no control over it.
Thanks for all the help. this is what I ended up doing.
--- HTML ---
<a class="action" data-content="content.php?method=load_content2"></a>
---Jquery---
var mouse_is_inside = false;
$(document).ready(function() {
$(".action").click(function() {
var phpFunctionToCall = $(this).data('content');
$('#indhold').load(phpFunctionToCall);
var loginBox = $("#dashboard_box");
if (loginBox.is(":visible"))
loginBox.fadeOut("fast");
else
loginBox.fadeIn("fast");
return false;
});
$("#dashboard_box").hover(function(){
mouse_is_inside=true;
}, function(){
mouse_is_inside=false;
});
$("body").click(function(){
if(! mouse_is_inside) $("#dashboard_box").fadeOut("fast");
});
});
--- PHP (shortened)---
function load_settings_panel($settingOnRequest) {
return $settingOnRequest;
}
$result = call_user_func('load_settings_panel', $_GET['method']);
echo($result);
When you open the application can you please click on the "Add Question" twice so it adds 2 table rows.
Now you will see in the application that above the horizontal line there is a textarea and a plus button, and below the horizontal line shows 2 table rows, both rows displaying its own textarea and plus button.
Now my question is that I want these 2 outcomes to happen but I do need help from somebody who is good at using Jquery/Javascript in order to solve this situation:
Situation 1. If the user clicks on the plus button ABOVE the horizontal line, then it displays a modal window which contains a search bar, Please type in search bar "AAA". You will now see a list of results. Now what I want is that if the user selects a row by clicking on the "Add" button, then I want the "QuestionContnet" within that row to be displayed in the textarea above the horizontal line. At the moment the Add button just closes the modal window but doesn't add anything into the textarea.
Situation 2: This deals with the user clicking on a plus button within one of the table rows BELOW the horizontal line. I want the same thing to happen except the "QuestionContent" added is displayed in the textarea within the same row the user has clicked the plus button, no where else.
How can both situations be solved so that it adds the QuestionContent into the correct textareas depending on which plus button is clicked? I am using an Iframe to display the content within the modal window.
UPDATE:
If you look at the application, it is now displaying "[Object] [object]" in textaea when I click "Add" button. Not the "Question".
Below is the code for the application:
<head>
<script type="text/javascript">
var plusbutton_clicked;
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $plusrow = $("<td class='plusrow'></td>");
var $question = $("<td class='question'></td>");
$('.questionTextArea').each( function() {
var $this = $(this);
var $questionText = $("<textarea class='textAreaQuestion'></textarea>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$question.append($questionText);
});
$('.plusimage').each( function() {
var $this = $(this);
var $plusimagerow = $("<a onclick='return plusbutton();'><img src='Images/plussign.jpg' width='30' height='30' alt='Look Up Previous Question' class='imageplus'/></a>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$plusrow.append($plusimagerow);
});
$tr.append($plusrow);
$tr.append($question);
$tbody.append($tr);
form.questionText.value = "";
$('.questionTextArea').val('');
}
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function closewindow() {
$.modal.close();
return false;
}
$('.plusimage').live('click', function() {
plusbutton($(this));
});
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function addwindow(questionText) {
if(window.console) console.log();
var txt = $(this).val(questionText);
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainTextarea').val(txt);
} else {
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(txt);
}
$.modal.close();
return false;
}
</script>
</head>
<body>
<form id="QandA" action="<?php echo htmlentities($action); ?>" method="post">
<div id="detailsBlock">
<table id="question">
<tr>
<td rowspan="3">Question:</td>
<td rowspan="3">
<textarea class="questionTextArea" id="mainTextarea" rows="5" cols="40" name="questionText"></textarea>
</td>
</tr>
</table>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage" id="mainPlusbutton" name="plusbuttonrow"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
<table id="questionBtn" align="center">
<tr>
<th>
<input id="addQuestionBtn" name="addQuestion" type="button" value="Add Question" onClick="insertQuestion(this.form)" />
</th>
</tr>
</table>
</div>
<hr/>
<div id="details">
<table id="qandatbl" align="center">
<thead>
<tr>
<th class="plusrow"></th>
<th class="question">Question</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
</body>
The details stored in the modal window comes from a seperate script known as "previousquestions.php", Below is the code where it shows the result of the "QuestionContent" field only displayed and it's "Add" button after the user has compiled a search:
<?php
$output = "";
while ($questionrow = mysql_fetch_assoc($questionresult)) {
$output .= "
<table>
<tr>
<td class='addtd'><button type='button' class='add' onclick='parent.addwindow();'>Add</button></td>
</tr>";
}
$output .= " </table>";
echo $output;
?>
Thank you
Application here
The first issue is this ->
<button id="add">
You cannot reuse an ID over and over, or, the page will iterate to the last element with that ID and NEVER run anything on any previous elements.
Quick fix:
<button class="add">
Simple enough.
We need to get the question text, from the first column, there are so many methods to do this with jQuery selectors it's mind blowing.
Situation 1
Let's take a peek at one option ->
$(document).on('click', '.add', function(){
//now that we've declared the click function, let's jump up to our parent element, and grab the text in the first cell.
var theQuestion = $("td:first-child", $(this).parent()).text();
//Now that we've figured out how to traverse the DOM to get the data we want, we need to move that data elsewhere.
$('.questionTextArea').val(firstCell);
});
Simple enough, right? That should solve the first problem you had.
Note: Textareas use value to set the data, whereas other elements will use .text()
Situation 2
Alright, now we need to figure out how to add a unique identifier to the "+" row when we click, and check for that "unique identifier" when appending the data, let's do it.
You have a <td> with a class of plusrow, sounds good, let's make a click function out of it, and give it a cool new class to reference.
$(document).on('click', '.plusrow', function(){
//adding a unique class for the purpose of the click.
$(this).addClass('activePlusRow');
});
So now the "+" we clicked has a new class -- activePlusRow, let's go back to our initial click handler for the add button, and give it some new conditional statements.
$(document).on('click', '.add', function(){
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets your data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
});
Alright, as you can see of the above, we test to see if the activePlusRow class exists, if it does, then we iterate to the next textarea with a class of textAreaQuestion and change the value of it, to theQuestion from the .add button we clicked.
Let me know if you've any questions.
I think best way to target chosen question to specified textarea is to parameterise your plusbutton function:
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
Of course you have to declare global var plusbutton_clicked; before insertQuestion function so other functions could change/use this information. You have to call this function with unique parameter for each plusbutton (you generate it dynamically, so this is up to you how you want to do it)
Then you can simply use it in your $(document).on('click', '.add', function(){}); - when user clicks 'add' button you have your plusbutton id so you can navigate with jQuery to corresponding textarea and place text there.
I'm thinking next() isn't the right function, since it only searches for the immediately following sibling... Try this:
$(document).on('click', '.add', function(){
console.log("clicked");
//lets get our Question Text...
var theQuestion = $("td:first-child", $(this).parent()).text();
//the row is present, let's then make sure that the proper cell gets oru data.
if($('.activePlusRow').length > 0){
$('.activePlusRow').next('.question').find('textarea.textAreaQuestion').val(theQuestion);
$('.activePlusRow').removeClass('activePlusRow');
}
$.modal.close();
return true;
});
I have a list of products from a particular supplier being displayed in a <table> populated with data from my mysql database.
Within this table, each product has a link that, when clicked, should show the product details in a ui-dialog, <div id = "detalhe_produto"></div>. The dialog does open, however, it only works only for the first item in the list. The other links of the following lines do not open the dialog.
Can anyone help me?
Here's the script I am using to open the ui-dialog:
<script type="text/javascript">
$(function(){
$('detalhe_produto').click(function(){
var selectedVal=$("#detalhe_produto").val();
var url="produto_detalhe.php?codigo="+selectedVal;
var dialog = $("#detalhe_produto");
if ($("#detalhe_produto").length == 0) {
dialog = $('<div id="detalhe_produto" style="display:hidden"></div>').appendTo('body');
}
dialog.load(
url,
{},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
close: function (event, ui) {
dialog.remove();
},
modal: true,
width: 460
});
}
);
});
});
</script>
and then the code table:
<table border="0" cellpadding="0" cellspacing="3">
<?php do { ?>
<tr>
<td align="left" valign="top" class="lista_produto"><?php echo $row_lista_produtos['codigo']; ?></td>
<td width="15"></td>
</tr>
<?php } while ($row_lista_produtos = mysql_fetch_assoc($lista_produtos)); ?>
</table>
I have tried to change the href="#" to href="javascript: void (0)"
and the result was the same.
Suggestions?
If you have many distinct dialogs that can be clicked open, you need to use a class selector, . instead of an ID selector, #. You may have also forgotten the #.
So instead of this:
var dialog = $("#detalhe_produto");
do this:
var dialog = $(".detalhe_produto");
**Please see this jsfiddle: http://jsfiddle.net/trpeters1/uFDdb/2/
It has a complete working demonstration of the jqueryUI dialog for multiple dialogs specific to your use case. Meaning, the dialog shows a value specific to which link was clicked.
you missed a # in $('detalhe_produto').click(function(){