Javascript function only works after page refresh - javascript

I have a forum that has a "subscribe" and "unsubscribe" button. When you hit it once, it changes but then doesn't switch back again until the page is refreshed.
http://jsfiddle.net/7QPyL/
Here's my code:
$(document).ready(function () {
// Subscribe to topic subscribedtotopic
$(".notsubscribedtotopic").click(function () {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Unsubscribe From Topic');
$(this).removeClass('notsubscribedtotopic').addClass('subscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/SubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
});
// UnSubscribe to topic subscribedtotopic
$(".subscribedtotopic").click(function () {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Subscribe To Topic');
$(this).removeClass('subscribedtotopic').addClass('notsubscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/UnSubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
});
});

It does not work because the class is not there when you add the event handler, so it can not find the element.
$(".notsubscribedtotopic") and $(".subscribedtotopic") do not magically select new elements as they are added to the page.
You should write one function and just toggle the state.
$(".subscribe").click(function () {
var link = $(this);
var isSubscribbed = link.hasClass("subscribedtotopic");
link.toggleClass("subscribedtotopic notsubscribedtotopic");
...
});

I would set up your code to be something like this:
$(document).ready(function () {
// Subscribe to topic subscribedtotopic
function subscribetotopic() {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Unsubscribe From Topic');
$(this).removeClass('notsubscribedtotopic').addClass('subscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/SubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
}
// UnSubscribe to topic subscribedtotopic
function unsubscribetotopic() {
var topicid = $(this).attr('rel');
$(this).slideUp('fast');
$(this).html('Subscribe To Topic');
$(this).removeClass('subscribedtotopic').addClass('notsubscribedtotopic');
$(this).slideDown();
$.get("/base/Solution/UnSubScribeToTopic/" + topicid + ".aspx",
function (data) {
var result = $('value', data).text();
});
return false;
}
});
And then make a simple onclick call in your HTML element, like so:
<button onclick="subscribetotopic()">Subscribe</button>
If you'd prefer to keep your code the way it is, then clarify which element you want to have active.
Example (simply set a div w/ id mymainelement and button w/ id subscribebutton):
$(#mymainelement .subscribebutton).click(function() { ... });
If you'd prefer to toggle the button instead of having two separate elements, check out #epsacarello's answer.

Related

JS to get checked box value add to URL and then on click goes to URL

I have a script that looks like this:
var baseUrl = 'http://ab3.0e7.myftpupload.com/idmatch_process.php?idmatch_process.php?quizid=". urlencode($quiz_id) ."&escalation=". urlencode($escalation) ."&correctrule=". urlencode($correctrule) ."&page=" . $next_page ."&ans=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
Basically I am getting the value of the checked box and then appending it to the and of baseUrl. Then i am automatically changing the window location. What i would like to do is have the window location changes not on checkbox click but on a button click that I will add. Anyone have an easy way of doing this?
Store your ulr in a global var.
show the button only if url is not empty and redirect on click.
var baseUrl = 'http://ab3.0e7.myftpupload.com/idmatch_process.php?idmatch_process.php?quizid=". urlencode($quiz_id) ."&escalation=". urlencode($escalation) ."&correctrule=". urlencode($correctrule) ."&page=" . $next_page ."&ans=';
var newurl="";
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
// jump to url
newurl = baseUrl + queryString; //setting new url
$("#yourbutton").show();
}
});
$("#yourbutton").click(function(){
if(newurl!="")
window.location.href=newurl;
}
});
If you move the declaration of queryString to the outer scope you can use it later on click.
$(document).ready(function () {
var queryString = '';
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ' OR ' + $(this).val();
}
});
}
});
$('button.submit').on('click', function() {
// jump to url
window.location = baseUrl + queryString;
});
});
You can create a button that onclick does what you are doing now on document ready, that should work.

Remove dynamically created button's history - jQuery

this is my first entry on StackOverFlow.
I'm working on a project and it needs jQuery to perform a master/detail table layout.
I have to work in asp.net C#, master and detail table generate dynamically.
So what is my problem:
I generate the master table with ajax:
function refreshMasterTable() {
xhr = $.ajax({
type: "GET",
url: "tablefunctions.aspx?mode=showmastertable",
success: function (html) {
$("#tbl_master").html(html);
prevAjaxReturned = true;
$('input[type=button]').click(function () {
var bid, trid;
bid = (this.id);
trid = $(this).closest('tr').attr('id');
if ($("#detail_" + trid).length == 0) {
detailShow = true;
pointer = $(this).closest('tr');
pointer.after("<tr><td colspan=5><div id=detail_" + trid + "></div></td></tr>");
$.get("tablefunctions.aspx?mode=showdetailtable&id=" + trid, function (response) {
$('#detail_' + trid).html(response);
});
$(document).on('click', '#submitMasterData', function () {
value = $('#name').val();
$.get("tablefunctions.aspx?mode=mastertableupdate&id=" + trid + "&name=" + value);
refreshMasterTable();
});
} else {
detailShow = false;
$(this).closest('tr').next("tr").remove();
}
});
}
});
};
In tablefunctions.aspx there is an entry, what generates the submit button:
html.Append("<tr><td colspan=\"2\" align=\"right\"><input type=\"submit\" id=\"submitMasterData\" /></td></tr>");
So the problem begins here. Each time when I ask a new detail row in the master table, a new submitMasterData instance of button creates and the $(document).on('click', '#submitMasterData', function () event triggers on every previous values. If I reload the page, the first detail request is OK, but the "collection" begins again.
$("#submitMasterData").remove(); didn't solve the problem. Sorry for my bad English, if something is not clear, please ask me...
The problem is the $(document).on() function is binding a new event each time a button is clicked without removing any of the previous events. You can use the off() function to remove the old ones in queue.
function refreshMasterTable() {
xhr = $.ajax({
type: "GET",
url: "tablefunctions.aspx?mode=showmastertable",
success: function (html) {
$("#tbl_master").html(html);
prevAjaxReturned = true;
$('input[type=button]').click(function () {
var bid, trid;
bid = (this.id);
trid = $(this).closest('tr').attr('id');
if ($("#detail_" + trid).length == 0) {
detailShow = true;
pointer = $(this).closest('tr');
pointer.after("<tr><td colspan=5><div id=detail_" + trid + "></div></td></tr>");
$.get("tablefunctions.aspx?mode=showdetailtable&id=" + trid, function (response) {
$('#detail_' + trid).html(response);
});
//need to unbind all the previously attached events
$(document).off('click', '#submitMasterData');
$(document).on('click', '#submitMasterData', function () {
value = $('#name').val();
$.get("tablefunctions.aspx?mode=mastertableupdate&id=" + trid + "&name=" + value);
refreshMasterTable();
});
} else {
detailShow = false;
$(this).closest('tr').next("tr").remove();
}
});
}
});
};
You can view a proof of concept in this JS fiddle: https://jsfiddle.net/bfc6wzt8/
Hope that helps :-)

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 */
}
});

JQuery .hover / .on('mouseleave') not functioning properly

I am trying to use the hover function which is pretty rudimentary, but I can't seem to get the mouseout/mouseleave to function properly.
Code:
$(document).ready(function(){
$('.SList').css('display','none');
$(".MList a").on('mouseenter',
function(){
var HTMLArr = $(this).children().html().split(':');
$(this).children('p').replaceWith('<p>'+HTMLArr[0]+':&nbsp◤</p>');
$(this).siblings('.SList').slideDown('slow');
})
.on('mouseleave',function(){
var HTMLArr = $(this).children().html().split(':');
$(this).children('p').replaceWith('<p>'+HTMLArr[0]+':&nbsp◢</p>');
$(this).siblings('.SList').slideUp('slow');
});
});
The mouseenter works properly, but it is not even entering the code for the mouseleave. Any ideas would be greatly appreciated.
Fiddle
See this: DEMO
$(".MList a").on('mouseenter',
function(){
var HTML = $(this).children('p').html();
$(this).children('p').html(HTML.replace('◢','◤'));
$(this).siblings('.SList').slideDown('slow');
})
.on('mouseleave',function(){
var HTML = $(this).children('p').html();
$(this).children('p').html(HTML.replace('◤','◢'));
$(this).siblings('.SList').slideUp('slow');
});
You have an issue with the anchor of the event.
Change to use this:
$(".MList a").on('mouseenter', function () {
var myP = $(this).children('p');
var HTMLArr = myP.text().split(':');
myP.html( HTMLArr[0] + ':&nbsp◤');
$(this).next('.SList').slideDown('slow');
}).on('mouseleave', function () {
var myP = $(this).children('p');
var HTMLArr = myP.text().split(':');
myP.html( HTMLArr[0] + ':&nbsp◢');
$(this).next('.SList').slideUp('slow');
});
You have the same issue with click, and redo same thing. SO, rework and reuse: (you could even make it better but this shows the start of that)
$(".MList a").on('mouseenter', function () {
down($(this).find('p').eq(0));
}).on('mouseleave', function () {
up($(this).find('p').eq(0));
});
$(".MList a").click(function () {
if ($(this).siblings('.SList').is(':visible')) {
up($(this).find('p').eq(0));
} else {
down($(this).find('p').eq(0));
}
});
function up(me) {
var HTMLArr = me.text().split(':');
me.html(HTMLArr[0] + ':&nbsp◢');
me.parent().next('.SList').slideUp('slow');
}
function down(me) {
var HTMLArr = me.text().split(':');
me.html(HTMLArr[0] + ':&nbsp◤');
me.parent().next('.SList').slideDown('slow');
}

reinitiate jquery plugin after ajax, causes events to fire multiple times

I have a query plugin I'm working on and I certain functions after ajax content has loaded. The problem is that let's say I re-initiate it 15 times, a click event will then fire 15 times when it's only clicked once.
Is there a way so it doesn't keep piling up? I'm calling addToCart onload and also from itemDetail after the ajax return
thanks!
function addToCart()
{
$(options.add_to_cart).click(function ()
{
event.preventDefault();
var id = $(this).attr('id');
store_item_id_val = id.replace('store-item-id-', '');
var quantity = $('.quantity-' + store_item_id_val);
if (quantity.val() < 1)
{
showError('Please enter a quantity of 1 or more.');
$(quantity).val(1);
return this;
}
$.post($(this).attr('href'),
{ store_item_id: store_item_id_val, quantity: quantity.val() },
function (data)
{
var result = jQuery.parseJSON(data);
renderCart(result);
});
});
return this;
}
function itemDetails()
{
$('.item-details').click(function ()
{
event.preventDefault();
var url = $(this).attr('href');
$.getJSON(url, function (result)
{
$('.modal-title').empty().html(result.title);
$('.modal-content').empty().html(result.html);
$('#modal').slideDown(100);
$('.ui-button').button();
addToCart();
$('.modal-close').click(function ()
{
event.preventDefault();
$('#modal').hide();
});
});
});
Based on the code you provided, I would probably say that you have some other code calling itemDetails(). Each time itemDetails() is called, it ADDS another event handler for click to your .item-details. You may want to instead do:
$(document).ready(function()
{
$('.item-details').click(function ()
{
event.preventDefault();
var url = $(this).attr('href');
$.getJSON(url, function (result)
{
$('.modal-title').empty().html(result.title);
$('.modal-content').empty().html(result.html);
$('#modal').slideDown(100);
$('.ui-button').button();
addToCart();
$('.modal-close').click(function ()
{
event.preventDefault();
$('#modal').hide();
});
});
});
});
This would put the event handler on your .item-details classed items, and only fire the events once. If you have dynamic .item-details added and removed you probably should use:
$('.item-details').live('click', function() ...

Categories

Resources