Making a Delete and Reply button in Jquery - javascript

this is my second post on the website. Of all other sites i tried, this one gave the most accurate and useful information!
I'm in a bit of a trouble with buttons, i have a task to make an inbox and to add a "reply" and "delete" button into every instance of the message.
I was indeed wandering if there is a better way to do that than forcing the HTML code into the script, because every message is dynamically generated. Any help and/or suggestions would be very appreciated!(The objects are called from a JSON file).
$(document).ready(function(){
$.getJSON('public/js/data.json', function(json){
$.each(json.data, function(i, data){
var output = '';
if(data.from.id != '234' && data.from.name != 'Alan Ford'){
$("#inbox").append(
output +=
'<div class="post">'+
'<div class="h1">'+data.from.name+' - '+data.subject+'</div>'+ //this gives the name of the person who sent the message and the subject
'<div class="content">'+data.message_formatted+'</div>'+ //The content of the message
//buttons should be squeezed left of the date
//this gives the date of the message sent
'<div class="time">'+data.date_sent_formatted.formatted+'</div>'+
'</div>'
);
}});
});
});
var date_sent=convertToDateTime();
function delete_message(id){
console.log('Delete message with id: '+id);
}
function reply_message(id, sender){
console.log('Message id: '+id);
console.log('Reply to: '+sender);
}

$(document).ready(function() { //when de html document is loaded
$(".deleteButton").each(function() { //for each button with class *deleteButton*
var button = this; //we take the html element
$(button).click(function() { //and we bind an eventlistener onclick
alert($(button).attr("id")); //when the user clicks we tell him the id
// code to execute when the user clicks on a delete button
});
});
$(".replyButton").each(function() {
var button = this;
$(button).click(function() {
alert($(button).attr("id"));
// code to execute when the user clicks on a reply button
});
});
});
With this you add a class and id to every delete/reply button in the html.
Lets say you have a simple list like this.
<div>
<button class="deleteButton" id="1">Message 1</div>
<button class="replyButton" id="1">Message 1</div>
<button class="deleteButton" id="2">Message 2</div>
<button class="replyButton" id="2">Message 2</div>
<button class="deleteButton" id="3">Message 3</div>
<button class="replyButton" id="3">Message 3</div>
</div>
Now if you click on one of the buttons, you will get an alert that tells you the id of the button.

Related

copy ajax text generated

I tried to copy text after an ajax text generated
I am able to copy a text an inputtext but for the field inputtext generated by the ajax response, it does not work
this code below display the input generated by the ajax
<div class="chat-box-message text-start">
<div id="chat-output" class="text-bg-light">
<button id="copyButton" class="btn btn-primary" data-clipboard-target="#chat-output">
<i class="bi bi-clipboard" title="Copy HTML Code"></i>
</button>
</div>
<div>
this script represent the element injected in chat-output
$(document).ready(function() {
// Initialize the clipboard
var clipboard = new ClipboardJS("#copyButton");
// Handler for when the copy button is clicked
clipboard.on("success", function(e) {
// Show a tooltip indicating that the text was copied
$(e.trigger).attr("data-original-title", "Copied!").tooltip("show");
e.clearSelection();
});
$("#send").click(function() {
let message = $("#message").val();
$.post("' . $url . '", {message: message}, function(data) {
$("#chat-output").html(data);
});
});
});
When the message is generated, I do not see the copy button.
Do you have an idea to implement the coy button afterthe text is generated ?
Thank you

How to change the contents of the modal through javascript function?

Hi I am making Quiz module. In which student can take quiz. once submitted, if the quiz is not passed, than students can 'retake quiz'. Once students click on 'retake quiz', only questions for which user gave wrong answer will be showed up. I am using php and HTML modal for showing the questions for the first time when student take quiz. Than using jquery and javascript, I am passing the responses of user to backend and checking if it is passed or failed. If failed, than I have wrong questions id, whihc I want to display when they take 'requiz'. Following a code:
Index.php
//When user clicks this button, modal will be pop-up and questions will be displayed one by one.
Start Quiz
<!-- Quiz Modal -->
<div class="modal fade quiz-modal" id="Quiz">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<? foreach ($questions as $i=>$question) { ?>
<div class='question'>
<div class="modal-header">
<div class="row">
<h4>QUIZ</h4>
</div>
</div>
<div class="modal-body">
<div class="row">
<div id="quest-content" class="quest">
<h4 class="question-title"><?=$question->number?>) <?=$question->title?></h4>
<ul class="list-unstyled">
<? foreach ($question->getAnswers() as $answer) { ?>
<li>
<div class="checkbox">
<input class="cb" type="checkbox" name="answer[]" value="<?=$answer->title?>">
<?=$answer->title?>
</div>
</li>
<? } ?>
</ul>
<br>
<br>
<p class='error'>Please select an answer</p>
</div>
</div>
</div>
<div class="modal-footer">
<p class='quest_num'><?=$question->number?> of <?=count($questions)?></p>
<? if( count($questions) === 1 ) { ?>
<a class="btn button btn-lg quiz-btn">Submit Quiz</a>
<? } else if ( count($questions) === $i +1 ) { ?>
<a class="btn button btn-lg quiz-btn">Submit Quiz</a>
<? } else { ?>
Next Question
<? } ?>
</div>
</div>
<? } ?>
</div>
</div>
</div>
Following is <script> where I am doing couple of things: if there are more questions, button will show 'Next' and if it's a last question- button will show 'Submit'. Once submit the quiz, it will send user's responses to backend through $.post and get back the array of questions IDs that were wrong. Using this wrong question's ids, when user clicks on 'Retake Quiz', it should show quiz again with these ids only.
<script type="text/javascript">
$(document).on('ready', function(){
var answers = [];
$('.quiz-btn').click(function(e){
e.preventDefault()
var checkbox = $(this).parents('.question').children('.modal-body').children('.row').children('.quest').children('ul').children('li').children('.checkbox').children('.icheckbox_square');
var btn = $(this).parents('.question').children('.modal-footer').children('.quiz-btn')
var next = false
var submit = false
console.log(checkbox)
$(checkbox).each(function(){
if ( $(this).hasClass('checked') && $(btn).html() == 'Next Question' ) {
answers.push($(this).children('.cb:checked').val());
console.log(answers);
next = true
}
else if ($(this).hasClass('checked') && $(btn).html() == 'Submit Quiz') {
answers.push($(this).children('.cb:checked').val());
submit = true
}
});
if ( next ) {
e.preventDefault();
$(this).parents('.question').slideUp(500);
$(this).parents('.question').next('.question').delay(500).slideDown(500);
} else if ( submit ) {
e.preventDefault();
$.post('/student/submit_quiz',{answers: answers, module: <?=$model->course_module->id?>}, function(data){
var correct = data['correct'];
var incorrect = data['incorrect'];
if(incorrect){
if(incorrect.length > 0){
var div = $('.quest')[$('.quest').length - 1];
var footer = $('.modal-footer')[$('.modal-footer').length - 1];
var progress = (correct.length*100)/(<?=count($questions)?>);
div.innerHTML = "<h4 class='question-title'>" + (correct.length)+"/<?=count($questions)?> questions correct <h4>";
div.innerHTML += "<div class='error'><p><strong>We are sorry but you have " + incorrect.length +" answers incorrect</strong><br>Please go back and review and reanswer those questions.</p></div>";
footer.innerHTML = "<a onclick='retakeQuiz(["+incorrect+"])' class='btn btn-success btn-lg quiz-btn'>Retake Quiz</a>";
} else {
var div = $('.quest')[$('.quest').length - 1];
var footer = $('.modal-footer')[$('.modal-footer').length - 1];
var progress = (correct.length*100)/(<?=count($questions)?>);
div.innerHTML = "<h4 class='question-title'> Congratulations!! You Passed this Module.<h4>";
footer.innerHTML = "<a href='/student/course/<?=$model->course->id?>' class='btn btn-default btn-lg'>Continue</a>";
}
}
});
} else {
console.log(next)
$('.quest .error').fadeIn();
}
});
});
function retakeQuiz(incorrect) {
$.each(incorrect, function(key, val) {
alert('index ' + key + ' points to file ' + val);
//Here incorrect is the array of Wrong Question's IDs. How can I use that id to show only this questions in my above modal.
});
}
</script>
I would like to know you all that I have only one Modal- that shows the quiz questions one after another and when quiz is completed and user submit the quiz, it will show the message of pass or fail along with the respective button say 'Continue' or 'Retake Quiz'. If 'Retake Quiz' is clicked, wrong questions will be displayed on the modal. So I have only one modal, but just changing the contents dynamically through javascript.
I tried my best to explain my question and code. Hope to get some help. Help is highly appreciated.
Doing manipulating from two sides like this always ends up in a bit of a tizy. Instead of changing the questions by using jQuery, can you change your PHP endpoint to return modal content given a set of ids? Here is the big idea:
Your PHP code has an endpoint that takes in a list of ids. These ids get passed off to the PHP code which does it thing and returns a list of questions of the ids (and corresponding answers). When a user first visits your page, your PHP code auto-loads all of the questions into the modal so the user gets the entire quiz (similarly to how you are loading on initial page load now).
Once they finish the quiz, you said you stored the ids of the questions they got wrong. What I would recommend is sending the ids to your php code to return a newly generated modal only including the ids of questions they got wrong. Then, you can simply replace the modal content with the result. Something like this perhaps (this is all psuedo-code, but I hope it gets the idea across)
// user has finished taking the quiz
$.get({
"url": "/yourendpoint" + ids.toString()
"method": "GET"
}.then(function(data){
$(".modal-content").html(data);
});
My suggestion is to add attribute id to the every question divison with the value of question id like below
<? foreach ($questions as $i=>$question) { ?>
<div class='question' id="<? $question->id ?>">
// Your remaining code here
</div>
<? } ?>
After submitting the form, in your callback of ajax call, remove the question divs with the ids those are not present in the response like below
function retakeQuiz(incorrect) {
// I am assuming incorrect as [id, id, id] for example
$('.question').each(function (index, question) {
if (!incorrect.includes($(question).attr('id'))) {
$(question).remove();
}
});
}

Gettings 2nd Popup After Closing First

I have a form which dynamically generates a table of attached (uploaded) files to the form. The last cell of each row is a delete button. That delete button when clicked executes this code:
Delete Button Clicked
$("td").on("click", ".btn-danger", function(event){
var rowID = "#"+$(this).attr("rowID");
var id = $(this).attr("id");
$("#confirmDelete").animate({top:'15%'}, 1000);
$("#confirmDelete").removeClass("hidden");
$("#confirmDelete").on("click", "#deleteFile", function(e){
var inn = document.thisItem.getInnovator();
var getInfo = inn.newItem("CSH_PLI_CommercialPartFiles", "get");
getInfo.setProperty("related_id", id);
getInfo = getInfo.apply();
var relatedID = getInfo.getProperty("id", "");
var thisRelated = inn.newItem("CSH_PLI_CommercialPartFiles", "delete");
thisRelated.setID(relatedID);
thisRelated = inn.applyAML(thisRelated.ToString());
var thisFile = inn.newItem("File", "delete");
thisFile.setID(id);
thisFile.apply();
$("#confirmDelete").animate({top:'-100%'}, 1000);
$("#confirmDelete").addClass("hidden");
$(rowID).hide();
});
$("#confirmDelete").on("click", ".btn-default", function (e){
$("#confirmDelete").animate({top: '-100%'}, 1000);
});
});
Which in turn brings into focus this bit of HTML, my confirmation window.
HTML
<div id="confirmDelete">
<div class="bg-danger">
<h4>Delete File Confirmation</h4>
</div>
<div>
<p><b>Delete this file? This action cannot be undone</b></p>
</div>
<div class="pull-right">
<button type="button" class="btn btn-default btn-sm">Cancel</button>
<button type="button" class="btn btn-danger btn-sm" id="deleteFile">Delete</button>
</div>
</div>
Now everything works fine enough. Cancel closes the popup. And delete, will actually delete the file from the server and remove it from the table in the form. However, as soon as delete is done, the popup will scroll up and then scroll back down as if it were called again.
I cannot figure out any combination of hides and removes which will actually stop this from happening.

jQuery AJAX Button Click - Remove Table Row after AJAX Call is Successful

I'm displaying an HTML table and would like to include a button in the last column that, when clicked, performs an AJAX call which will result in the removal of the table row from the table. I'm new to jQuery and AJAX and working things out as I go - I've managed to setup some AJAX calls that run when a field is edited, but now I'm struggling to attach one to a button in a table row.
Here's how the table looks:
<tr class="" id="tableRow1"><td>Store 1</td><td>lorem ipsum</td><td>John Smith</td><td>20/11/2014 12:53:52 AM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
<tr class="" id="tableRow2"><td>Store 2</td><td>lorem ipsum</td><td>Sally Jones</td><td>20/11/2014 12:53:52 AM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
<tr class="" id="tableRow3"><td>Store 3</td><td>lorem ipsum </td><td>Bill Howden</td><td>12/11/2014 01:43:03 PM</td><td><button type="button" id="closeNote" class="btn btn-primary">Acknowledge</button></td></tr>
I know that the ID for the button is not unique - at the moment the script only fires when the button in the first row is clicked. I'm not sure how to assign a unique ID for each button which the script can see.
Here's my script:
<script type="text/javascript">
$(document).ready(function() {
$("#closeNote").click(function(){
$.post('editNote.php', { type: 'hideNote', id: '1E1DDA14-D2C6-4FC8-BA5F-DBCCC7ABAF7F' }, function(data) {
data = JSON.parse(data);
if (data.error) {
$("#ajaxAlert").addClass("alert alert-danger").html(data.text);
$("#ajaxAlert").show();
return; // stop executing this function any further
} else {
$("#ajaxAlert").hide();
$(this).closest('tr').remove();
}
}).fail(function (xhr) {
// no data available in this context
$("#ajaxAlert").addClass("alert alert-danger");
//display AJAX error details
$("#ajaxAlert").html(xhr.responseText);
$("#ajaxAlert").show();
});
});
});
</script>
I just need some help in bring this altogether so that when the button is clicked on any row it calls the script which in turn, if the PHP script it then calls is successful, it then removes the row where the button was clicked.
Rather than applying the button to an ID give each link a class:
<button class="btn btn-primary close-note"
Then amend your JS as follows:
$("button.close-note").click(function(){
Inside your callback functions the keyword this no longer refers to the element, but instead refers to the XHR object.
To solve this assign $(this) to a variable outside of the $.post
var $self = $(this);
$.post( ... ... function(response){
// code and stuff
$self.closest('tr').hide();
});
You also need to ensure that the browser doesn't then follow the link; amend the click line again:
.click(function(e){
e.preventDefault();

JQuery Ajax call stop refresing the page

I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.

Categories

Resources