Why is Jquery only responding to first element? - php

I have comment on my site, that have a reply button. When the reply button is hit a new text box pops up and allows the user to reply to the comment.
For some if there is more than one comment on a page, the reply link only works for the comment at the bottom of the other comments. Essentially the first comment in a list of more than one.
I'm pretty certain is has to do with my click function class.
Here is my html and php structure:
<a name='reply_form_<?php echo $airwave_comment_row['id']; ?>' style="clear:both"></a>
<div id='reply_to_<?php echo $airwave_comment_row['id']; ?>' class="respond_structure_future" <?php if(isset($_GET['reply_to']) && $_GET['reply_to'] == $airwave_comment_row['id']) { echo 'style="display:block;"';}else{ echo 'style="display:none;"';} ?>>
<div class="response_polaroid_future">
<a href="http://www.cysticlife.org/Profile.php?id=<?php// echo $auth->id; ?>">
<img src="/styles/images/prof_thumbnail_2.jpg" />
</a>
</div>
<?php
echo validation_errors();
echo form_open('community/insert_airwaves_comments_replies/'.$this->uri->segment(3));
?>
<div class="respond_body_future">
<div class="response_arrow_future"></div>
<div class="response_tail_future"></div>
<div class="respond_data_future">
<?php
$data = array('name' => 'airwaves_comments_replies', 'id' => 'reply_to'. $airwave_comment_row['id'].'_textarea', 'class' => 'respond');
echo form_textarea($data, set_value('airwaves_comments_replies'));
$data = array('type' => 'hidden', 'name' => 'comment', 'value' => $airwave_comment_row['id']);
echo form_input($data);
?>
<div class="respond_nevermind">
nevermind
</div>
<?php
echo form_submit('sub_comment_reply', 'Reply');
?>
</div>
</div>
</form>
</div>
jquery:
<script type="text/javascript">
$(document).ready( function() {
$('.scroll').localScroll({ offset:{top:-0,left:0} });
$("a.reply_link").click( function() {
$("#"+$(this).attr('name')).fadeIn('slow');
});
$(".respond_nevermind a").click( function(event) {
event.preventDefault();
var reply_box = document.getElementById($(this).attr('href'));
$(reply_box).css('display','none');
var reply_textarea = document.getElementById($(this).attr('href')+"_textarea");
$(reply_textarea).val('');
});
});
</script>
Thanks in advance.

The click event handler is bound to the initial existing elements but dynamically created elements are not bound.
Try using live() or on() to bind dynamically created elements.

Related

Yii: run a function when a submitButton is pressed

I'm very new to Yii, and trying to understand an existing web app, so please bear with me.
I've been having issues with a certain function, that seems to fail retaining data whenever actionView is calledhere, but I thought perhaps I was going about this problem all wrong.
Instead, I thought perhaps the button could directly run the function from the controller, instead of... whatever it was doing prior.
I looked at a sample here that had this:
<?php echo CHtml::submitButton('CSV Report', array('submit'=>'getReport')); ?>
Where getReport is the function in my controller (actionGetReport).
Unfortunately, it's not working. Here's the code of my _commentform.php:
<?php $post = $forum; ?>
<?php $comment = $model; ?>
<div id="comment_form<?=$post->id?>" class="other-member-comment-box">
<?php
$user=Persons::model()->findByAttributes(array('party_id'=>Yii::app()->user->id));
$country=Lookup_codes::model()->findByAttributes(array('id'=>$user->country));
$location = empty($country) ? '' : 'from '.$country->name;
?>
<div class="user-profilepic">
<a href="<?php echo Yii::app()->createUrl('persons/view/id/'.$user->showViewLinkId())?>"><img src="<?php
if(!empty($user->image) AND file_exists( Yii::getPathOfAlias('webroot').'/images/profile_picture/'.$user->party_id . $user->image)){
echo Yii::app()->request->baseUrl.'/images/profile_picture/'.$user->party_id . $user->image;
} else echo Yii::app()->request->baseUrl.'/images/profile_picture/NA.jpg';
?>"></a>
</div>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('forum/view/id/'.$forum->id),
'enableAjaxValidation'=>false,
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->hiddenField($model,'node_type_id',array('value'=>'7')); ?>
<?php echo $form->error($model,'node_type'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'content_id',array('value'=>$forum->id)); ?>
<?php echo $form->error($model,'content_id'); ?>
</div>
<div class="row">
<?php echo $form->hiddenField($model,'category',array('value'=>$forum->category)); ?>
<?php echo $form->error($model,'category'); ?>
</div>
<div class="row">
<?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>90),array('id'=>'sample')); ?>
<?php echo $form->error($model,'content'); ?>
</div>
<input type="hidden" value="<?php echo $view; ?>" id="view" name="view"/>
<div class="row buttons">
<?php
if ($view == 'view'){
if ($model->isNewRecord) {
echo CHtml::submitButton('Reply', array('id'=>'comment'.$comment->id));
} else {
echo CHtml::button('Save', array('submit'=>'updatecomment'));
}
}?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
</div>
And here's the UpdateComment function from my controller:
public function actionUpdateComment()
{
Yii::log(CVarDumper::dumpAsString("ForumController: Update COMMENT!"));
Yii::log(CVarDumper::dumpAsString($_POST['Comment']));
exit();
}
I'm not exactly sure what I'll get by the $_POST['Comment'], but if the code worked, I'd very least expect it to log out the "ForumController: Update COMMENT!". It doesn't.
I tried changing the submitButton to button, but that just kills the button function entirely.
Next, I tried this answer here.
So I changed the submitButton code to this:
echo CHtml::submitButton($model->isNewRecord ? 'Reply' : 'Save',array('id'=>'comment'.$comment->id));
And added this to the end:
<script>
$(document).ready(function() {
$('#text_form_submit').click(function(ev) {
ev.preventDefault();
$.ajax({ type: 'POST', dataType: 'JSON',
url: '<?php echo Yii::app()->createUrl("forum/UpdateComment"); ?>',
success:function(data){
if(data !== null) {
$('#Text_group').val(data);
$('#text-form').submit();
}
},
error: function() {
alert("Error occured!!!.");
},
});
return false;
});
});
</script>
Not exactly sure what the code does, other than call a function as well, but as well, it doesn't work (I also changed POST from GET and back).
Any suggestions? I feel like CActiveForm is to blame here, but even modifying that causes the site to fail in loading pages.
You have a long question and could be you should split your question in more question with simple question each ..
A firts answer the submit button don't contain the target function see this doc
http://www.yiiframework.com/doc/api/1.1/CHtml#submitButton-detail
the target function (php controller/action) is defined in form .. this is from html .. is the form definition that define the target for the submitted data ..
if you want execute the actionGetReport you should define the target in form action
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('yourController/actionGetReport'),
'enableAjaxValidation'=>false,
)); ?>

Ajax how to disable div or item

I am new to ajax, is there a way you can help me, how to disable all items once click is successful:
Here is my code for ajax:
if (!parent.hasClass('.disabled')) {
// vote up action
if (action == 'click') {
alert("test");
};
//how do i add disabled function on a particular div
// add disabled class with .item
parent.addClass('.disabled');
};
here is my index:
<?php while($row = mysql_fetch_array($query)): ?>
<div class="item" data-postid="<?php echo $row['recipe_id'] ?>" data-score="<?php echo $row['vote'] ?>">
<div class="vote-span"><!-- voting-->
<div class="vote" data-action="up" title="Vote up">
<i class="icon-chevron-up"></i>
</div><!--vote up-->
<div class="vote-score"><?php echo $row['vote'] ?></div>
</div>
<div class="post"><!-- post data -->
<p><?php echo $row['recipe_title'] ?></p>
</div>
</div><!--item-->
i jst want to disable the loop icon-chevron-up class.not just one but all.
Actually no ajax call needed here. I will only be done by using jquery. See the code
$(document).ready(function(){
$('.item').click(function(){
if (!parent.hasClass('.disabled')) {
parent.addClass('.disabled');
}
});
});
Here you have not mentioned, on what click you need the action, so i consider that on the div contains class='item', the action will be performed. I hope it will help.

Jquery event won't fire when element is displayed via mysql

I have some content that is fed in from mysql that, when clicked should fire an alert()...
however, this is not working...
here is my code for the code that is fed in from php/get_answers.php
<?php session_start(); ?>
<?php require_once("../includes/include_all.php"); ?>
<?php $answers = $question->get_answers_for_question($_GET['id']); ?>
<?php while($row = $answers->fetch_array()){ ?>
<!-- ALL ANSWERS HERE -->
<div class = 'answer-row'>
<div class = 'answer-side'>
<div class = 'arrow-contain-answer' type = 'answer' id = 'arrow-up' answer-id = '<?php echo $row["id"]; ?>'></div>
<div class = 'answer-votes-contain'>
<?php echo $row['popularity']; ?>
</div>
<div class = 'arrow-contain-answer' id = 'arrow-down'answer-id = '<?php echo $row["id"]; ?>'></div>
</div>
<div class = 'answer-content'>
<?php
echo $row['content'];
?>
</div>
<div class = 'actions'>
<a href = '#' class= 'add-comment' id = '<?php echo $row["id"]; ?>'> add comment </a>
</div>
</div>
<?php } ?>
and here is the jquery on the page that it is displayed on:
$(".arrow-contain-answer").click(function(){
alert();
});
What I want to happen is when someone clicks the element with the class of 'arrow-contain-answer' an event will occur..
I think I have had problems before when elements are being 'fed' into the page via mysql/php.
$(document).on("click", ".arrow-contain-answer", function(){
alert();
});
Try this way for dynamic added elements!
even better(performancewise) if you delegate it with the closest static element(parent) which is present in the document when dynamic fed element is added.
$('.answer-row').on("click", ".arrow-contain-answer", function(){
alert('clicked');
});
to read more about on delegated event

jQuery Dialog Modal (only open one when there is multiple ones on a page)

Ok I am looping through my news postings and each one you can comment on. So I built a dialog modal for each news posting (which I think is silly), but it's the only way I can keep the news_id looping through and passing it into the form action attribute.
Anyway, hopefully that's not such a huge deal, but whenever I click on a comment link (.comment), it opens up ALL of the repeating dialog modals since it's the same class. How do I make it only open up that dialog modal with the same news id as the comment link they are clicking on so I can insert their comment based on the news id?
This is the HTML for my news looping (using CodeIgniter)
<div id="news">
<?php foreach($news_array as $news) { ?>
<div class="news_box">
<h3 align="right">Peanut - December 18, 2012</h3>
<p align="right"><?php if($admin) { echo anchor('admin/news/edit/'.$news->id, 'Edit').' | '.anchor('admin/news/delete/'.$news->id, 'Delete', array('onClick' => "return confirm('Are you sure you want to delete this post?')")); } ?></p>
<h2><?php echo $news->title; ?></h2>
<p><?php echo nl2br($news->body); ?></p>
<p align="right"><?php echo anchor('news/comment/'.$news->id, 'Comment', array('class' => 'comment', 'onclick' => 'return false')); ?></p>
<div class="comment-form" title="Comment">
<?php echo form_open('news/comment/'.$news->id, array('class' => 'form')); ?>
<fieldset>
<legend>Please Leave A Comment</legend>
<div class="row clearfix">
<div class="full control-groups">
<div class="clearfix">
<div class="form-status"></div>
<?php echo form_label('Comment', 'comment'); ?>
</div>
<?php echo form_textarea(array('name' => 'comment', 'id' => $news->id, 'maxlength' => 200, 'placeholder' => 'Please enter 5 - 200 characters.', 'value' => set_value('comment'))); ?>
</div>
</div>
</fieldset>
<? echo form_close(); ?>
</div>
<hr color="orange" />
</div>
<?php } ?>
</div>
Then here is my Javascript (only showing the important stuff so it's not all jumbled together):
$('.comment-form').dialog({
autoOpen: false,
height: 380,
width: 900,
modal: true,
buttons: {
"Comment": function() {
form = $('.form');
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method'))
});
},
Cancel: function() {
$(this).dialog('close');
}
}
});
$('.comment').click(function() {
$(this).closest('.comment').find('.comment-form').dialog('open');
});
Thank you for any help!
There's a few ways you can do it. I'd probably just do it like this. Give each comment form an id e.g. id="comment-form-0", id="comment-form-1" etc as you're looping through and creating them in PHP.
Also for each comment element you store an HTML5 data attribute on it e.g. data-comment-id="0", data-comment-id="1".
Then in the JavaScript you'd do something like:
$('.comment').click(function() {
var commentId = $(this).attr('data-comment-id');
$('#comment-form-' + commentId).dialog('open');
});
I'd search for the parent container, then grab the appropriate comment form:
$('.comment').click(function() {
$(this).closest('div.news_box').find('.comment-form').dialog('open');
});
Given that [.closest()][1]:
Begins with the current element
Travels up the DOM tree until it finds a match for the supplied selector
The returned jQuery object contains zero or one element for each element in the original set
You likely have some containing element above div.news_box that has a class of .comment. The above code (untested), should stop the .closest() match at div.news_box and then find the sole child element with class .comment-form, thus only opening a single dialog.

Output Text Doesn't Show in Correct Format

Here is the JavaScript I use to animate slider (fade effect) of the content I read from database:
<script language="javascript">
jQuery(document).ready(function ()
{
var terms = ["span_1","span_2"];
var i = 0;
function rotateTerm() {
jQuery("#text-content").fadeOut(200, function() {
jQuery(this).text(jQuery('#text-slider .'+terms[i]).html()+i).fadeIn(200);
});
jQuery("#title-content").fadeOut(200, function() {
jQuery(this).text(jQuery('#title-slider .'+terms[i]).html()+i).fadeIn(200);
i == terms.length - 1 ? i=0 : i++;
});
}
rotateTerm();
setInterval(rotateTerm, 1000);
});
</script>
And here is the PHP code I use:
<?php
if (!empty($testLst)) :
$num=1;
foreach($testLst as $key=>$item):
$item->slug = $item->id;
$item->catslug = $item->catid ;
?><div id="hidden-content" style="display:none;">
<div id="title-slider">
<span class="<?php echo 'span_'.$num; ?>">
<h4><a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($item->id, $item->catid)); ?>">
<?php echo $item->title; ?></a>
</h4>
</span>
</div>
<div id="text-slider">
<span class="<?php echo 'span_'.$num; ?>">
<p>
<?php
$concat=array_slice(explode(' ',$item->introtext),0,20);
$concat=implode(' ',$concat);
echo $concat."...";
?>
</p>
</span>
</div></div>
Learn more >></p>
<?php
$num++;
endforeach;
endif;
?>
<div id="title-content">
</div>
<div id="text-content">
</div>
And here is a JSFiddle page reproducing what I would like to do.
My problem is that I am getting data that still has HTML tags, however I would like the output to have my CSS styles.
You could clone the node, and set that to be the new content of the target elements, to keep everything in jQuery objects, but personally, I'd use the .outerHTML property.
I've updated your fiddle to show you what I mean: I've changed the .text(...set content here) to .html(), because we're injecting HTML content. Then, I added [0] at the end of your selector, to return the raw element reference, which gives access to all standard JS properties and methods an element has, and just went ahead and fetched the outerHTML... easy-peasy

Categories