JQuery data is not "bind" with click submit - javascript

i have a tip game where are many games on a list. If you click on a game´s quote, a modal opens with the data and you can set your amount and then with submit you can submit it via ajax. I don´t know whats going wrong, but since 2 days i have a binding problem.
When i click on some quotes and then I take an amount.. then it submits not only one, it submits all i have clicked before...
that´s crazy.. here is my js code
$('.ui.buttons').on('click', 'a.quote.button', function (e) {
e.preventDefault();
// FOR DESKTOP
// $('#bet').fadeIn(300);
var id = $(this).data('id');
var tip = $(this).data('tip');
var game = $(this).data('game');
var team = $(this).data('team');
var quote = $(this).data('quote');
var earnings = 0;
var amount = $('#stake').val();
console.log(game);
$('#game').text(game);
$('#team').text(team);
$('#tip').text(tip);
$('#quote').text(quote);
bet.modal('show');
//bet.on('change', '#submit', function(){
// console.log(2);
$("#submit").bind('click', function (ev) {
ev.preventDefault();
$(this).unbind(ev);
var game = {};
game.id = id;
game.tip = tip;
game.quote = quote;
game.amount = $('#stake').val();
//SEND TIP
$.ajax({
type: 'POST',
url: url + '/bet',
data: {game_id: game.id, tip: game.tip, quote: game.quote, stake: game.amount}, .....
});

I solved it. I have closed it before the #submit binds.
$('body').on('click', 'a.quote.button', function (e) {
// e.stopPropagation();
$('a.button.active').removeClass('active');
$(this).addClass('active');
// FOR DESKTOP
// $('#bet').fadeIn(300);
id = $(this).data('id');
tip = $(this).data('tip');
game = $(this).data('game');
team = $(this).data('team');
quote = $(this).data('quote');
earnings = 0;
amount = $('#stake').val();
console.log(game);
$('#game').text(game);
$('#team').text(team);
$('#tip').text(tip);
$('#quote').text(quote);
bet.modal('show');
earnings = quote * amount;
return false;
});
$("#submit").on('click', function () {
....
});

Related

Javascript foreach loop calls ajax several times

So I am trying to create to do list with several boards. Each board have add item button. If I click add item button it opens modal where to insert task info. But if I click add item button several times and then insert info to modal and press save ajax fires as many times i clicked add item button. How can I prevent from that?
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function(addNewItem) {
addNewItem.addEventListener("click", function(e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
addNewBtn.addEventListener ("click", function(e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
$.ajax({
type: "POST",
url: "add.php",
data: { content: contentValue , title: titleValue , listid: boardId },
success: function(data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
}
});
});
});
});
You could use a variable, lets say busy, to validate that an AJAX request isn't already on going.
You could set this variable in the beforeSend callback of AJAx and then updated it back to false in the finally callbac :
var addNewItems = document.querySelectorAll("#addNewItem");
var addNewSubmits = document.querySelectorAll("#listItemSave");
addNewItems.forEach(function (addNewItem) {
addNewItem.addEventListener("click", function (e) {
var newItemModal = this.nextElementSibling;
newItemModal.classList.toggle("hidden");
var addNewBtn = newItemModal.querySelector("#listItemSave");
//current board
var board = this.closest("div.list");
//current list
var list = board.querySelector(".todo--items");
var busy = false;
addNewBtn.addEventListener("click", function (e) {
//current board id
var boardId = board.dataset.boardid;
//current title
var title = newItemModal.querySelector("#listTitle");
var titleValue = title.value;
//current content
var content = newItemModal.querySelector("#listTextarea");
var contentValue = content.value;
if (!busy) {
$.ajax({
type: "POST",
url: "add.php",
beforeSend: () => {
busy = true;
}
data: {
content: contentValue,
title: titleValue,
listid: boardId
},
success: function (data, textStatus, jqXHR) {
$("#todoItems-" + id + "").append(data);
},
complete: () => {
busy = false;
}
});
}
});
});
});
This is a pretty simple solution but it works.
You can use addNewBtn.onclick = function () {} instead to overlap the previous listener in this case.
But it's not recommended to register listeners inside another listener. Try to move it out of there.

Adding event handler to non-existent class?

I've seen questions that relate to non-existent elements, but not non-existent classes. Here's what I want to do. When a button of class "see_answer" is clicked, I want to remove the class and replace it with "see_question". However, my click function for a button, once its class is "see_question", is not running. I have tried $(document).on("click", ".see_question", function(event ) and I have tried $(".see_question").on("click", function(event) {etc.... Thanks for the help! My code is below:
$(document).ready(function() {
// initialize variables
var lang = "javascript";
var qno = 1;
var prevText; // holds question/answer
var language = lang + ".html";
// set up tabs, and keep track of which one is clicked
$("#myTabs").tabs({
activate: function (event, ui) {
var active = $("#myTabs").tabs("option", "active");
lang = $("#myTabs ul > li a").eq(active).attr("href");
lang = lang.replace("#", "");
}
});
/* REMINDERS
actual qa part: blah_language
*/
// set up question
$.ajax({
url: language,
dataType: "html",
success: function(data) {
$("#blah_"+lang)
.text($(data).find("#1").text());
},
error: function(r) {
alert("whoops, error in initialization");
}
});
$(".next_question").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("next_question_", "");
var language = id + ".html";
var doc = "#blah_" + id;
$.ajax({
url: language,
dataType: "html",
success: function(data) {
var num = "#" + qno;
$(doc)
.text($(data).find(num).text());
qno = qno + 1;
},
error: function(r) {
alert("whoops");
}
});
prevText = "";
});
// SHOW ANSWER
$(".see_answer").on("click", function(event) {
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
var answers = id + "_answers.html";
// Save the question
prevText = $(prev).text();
var obj = $(this);
$.ajax({
url: answers,
dataType: "html",
success: function(data) {
var num = "#" + 3;
$(prev)
.text($(data).find(num).text());
},
error: function(r) {
alert("whoops");
}
});
obj.val("See Question");
obj.removeClass("see_answer");
obj.addClass("see_question");
event.stopPropagation();
});
$(document).on("click",".see_question", function(event) {
event.preventDefault();
obj = $(this);
event.preventDefault();
var id = $(this).attr("id").replace("see_answer_", "");
var prev = "#blah_" + id;
$(prev).text(prevText);
obj.val("See Answer");
obj.removeClass("see_question");
obj.addClass("see_answer");
});
})
Click handling for .see_question elements is delegated to document. For .see_answer elements, a click handler is attached directly. Therefore, swapping the class names will have an undesirable effect.
when see_answer is in force, a click will trigger the "see_answer" handler.
when see_question is in force, a click will trigger the "see_question" handler AND the "see_answer" handler, which is still attached.
There's a number of ways to do this properly. From where you currently are, the simplest solution is to delegate click handling of .see_question and .see_answer elements to document.
$(document).on("click", ".see_answer", function(event) {
...
});
$(document).on("click", ".see_question", function(event) {
...
});
Combine the 2 handlers and figure out which version it is by hasClass() before you change the classes around
$(document).on("click", ".see_question, .see-answer", function(event ){
var $btn =$(this), isAnswer = $btn.hasClass('see_answer');
// we know which one it is so can switch classes now
$btn.toggleClass('see_answer see_question');
if(isAnswer){
/* run code for answer version */
}else{
/* run code for question version */
}
});

How to play a sound effect in ajax post way on jQuery and javascript?

I'm trying to play a sound effect when write a data of post method to mysql server which works with php and receive a xml.
so I wrote a code like following.
When I write a data (#post_send button click), sound works well,
but receive a data, sound doesn't work.
I doubt that sound doesn't work when play sound snippet is in a ajax or similar function..
How to play a sound in ajax post methos?
// Start Main code Area //
$(document).ready(function () {
// Global variable define area
curr_date = null;
last_date = "0000-00-00 00:00:00";
readAjax_timer = null;
audioElement = null;
// End of Global variable define area
audioElement = document.createElement('audio');
audioElement.setAttribute('src', './sound/bubble.mp3');
$("#post_send").click(function () {
audioElement.play();
curr_date = getTodayAndTime();
last_date = curr_date;
var str_postMsg = $("textarea").val();
if (str_postMsg == "") {
return;
}
appendShowBubble();
writeMsgToDB();
});
readAjax_timer = setInterval(function() {
readMsgByAjax();
}, 2000);
readMsgByAjax();
});
// End Main code Area //
Here is a function of receiving a data.
function readMsgByAjax() {
// receive a data from mysql by specified school name with ajax.
var sch_name = "wonderful_element_school";
var send_data = "sch_name=" + sch_name +
"&last_date=" + last_date;
// call ajax post method
$.post(
"PHP_readMsg_sql.php",
send_data,
function (data) {
$(data).find('tr').each(function () {
var db_record = $(this); //<= <tr>
// if "$(this)" is a table head, continue to next tr.
if (db_record.attr("id") == "head") {
return;
}
//////////////////////////////////////////////////
audioElement.play(); //<== This code doesn't work.
//////////////////////////////////////////////////
// process contents of tr.
var str_message;
var str_date;
var div_leftframe = $("#left_frame").clone();
div_leftframe.css("display", "block");
var p_message = div_leftframe.children('p');
str_message = db_record.find('td[id=post_message]').text();
str_message = str_message.replace(/\u000a/g, "</br>");
p_message.html(str_message);
var small_message = div_leftframe.children('small');
str_date = db_record.find('td[id=post_time]').text();
last_date = str_date;
str_date = str_date.replace(" ", " at ");
small_message.text(str_date);
$("#chat_list").append(div_leftframe);
});
}
);
$("#chat_list").append(div_leftframe);
var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 1000);
}
You would have to pass the audioElement in the function since it's out of scope of your function as #scrowler mentioned. So you can either add the function in your document.ready() scope, or you can change your function to:
function readMsgByAjax(audioElement){}
And when you call it in your document.ready() code, just do this:
readMsgByAjax(audioElement);

How to achieve recursive call - jquery

I have a custom created dialog module.
I am passing a mvc view called Cart to this module.
The cart view has a link called 'Create New Contat' clicking on which the view(Cart) will be replaced with another view(Contact) using an ajax call. The contact view has a button called cancel. When the user clicks on Cancel the old view(Cart) will replace the existing view(contact).
The problem I am facing is after replacing the view none of the links or buttons work on the view.
Can some body pls directed me towards a better way of doing this.
Pasted below is the code.
$(document).on('click', '.ddlCart li', function(e) {
var ddlselectedVal = $(this).attr('id');
var selectedListinsCount = selected_Listings.length;
var SelectedMlsnums = selected_Listings.join();
var agentId = $("#AgentId").val();
var Action;
var EnvironmentURL = $("#EnvironmentURL").val();
var postData = { AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: “PreAddToCart” };
var close = function (event, ui) {
$('#dvModalDialog').dialog("close");
}
var open = function (event, ui) {
var url = EnvironmentURL + "MLSReports/Stats/SearchContacts";
$("#btncart_cancel").on("click", function () {
$('#dvModalDialog').dialog("close");
});
$("#btncart_submit").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
AgentId: agentId, Mlsnums: SelectedMlsnums, ActionTypeValue: "AddToCart"
},
function (data) {
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
});
});
$("#lnkCreateNewcart").on("click", function () {
var url = EnvironmentURL + "MLSReports/Stats/Cart";
//Send the data using post and put the results in a div
$.post(url, {
ActionTypeValue: "preAddorEditContact"
},
function (data) {
//debugger;
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
$("#btnCancelContact").on("click", function () {
////********** replace the view (Contact) with the view (Cart).
// In the cancel event I am loading the previous page.I am having problem here. after post none of the controls work.
$.post(url, {
ActionTypeValue: "PreAddToCart"
},
function (data) {
//debugger;
// Replace current data with data from the ajax call to the div.
$("#dvModalDialog").empty().append(data);
})
});
});
});
};
if (ddlselectedVal == "AddtoCart") {
var rd = Mod.ReportsDialog({ title: 'Add To Cart', close: close, open: open });
rd.url = EnvironmentURL + "/MLSReports/Stats/Cart";
rd.targetElement = '#dvModalDialog'// '#dvSendEmail'
rd.formName = '#frmCart'
rd.postData = postData
rd.open();
}
});

jQuery confirm popping up multiple times

I'm having problems with this confirm box popping up multiple times. I only confirm after a certain button is pressed. If I only click on that button this should only ask once for that button but it's asking me once for every button of that class.
Any ideas why this is looping if I'm only firing this condition when a user clicks on a specific button?
$(".TweetNow").each(function () {
$(this).click(function TweetThis() {
var identify = $(this).attr('id');
var prestart = identify.indexOf('_');
var start = prestart + 1;
var end = identify.length;
var position = identify.substr(start, end);
var message = $("#Tweet_" + position).val();
var site = $("#SiteLabel").text();
if (message != '') {
var trend = $("#Topic_" + position).text();
var website = $("#SiteLabel").text();
if (confirm("Are you sure you want to tweet the following message:\n" + message + " ?")) {
PageMethods.TweetThis(message, site, trend, website);
location.reload();
}
}
});
});
Change your code as
$(".TweetNow").click(function() {
var identify = $(this).attr('id');
//Rest of code
});
Instead of
$(".TweetNow").each(function () {
$(this).click(function TweetThis() {
});
});

Categories

Resources