JQuery Ajax + Dropdown Menu function only runs once - javascript

This function only runs once. How can I get it to run multiple times?
I have tried using live() as was suggested in another SO question, but that made no difference to the program.
$(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});

Did you tried with document ready instead of $function()
$(document).ready(function() {
$('#chooseTeam').live('change', (function() {
$.getJSON($SCRIPT_ROOT + '/_get_info', {
selectedDeck: $('#chooseTeam').val()
}, function(data) {
/* Do something */
});
}
return false;
}));
});
Regards

Related

How to check a radio have onclick with caperjs?

This is my code:
Full code here: http://notepad.cc/casperjsstack1
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
var el = $('#giftMessages.noCard');
el.onclick();
});
});
});
Look at the picture: I want check No Gift Message
I try so much method but all false
Code HTML page here: http://notepad.cc/casperjsstack1_html
Thank you !
Have you tried click()?
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
this.click('#giftMessages.noCard'); // Click the radio button.
});
});
});
Try this.
//jQuery version using evaluation page context
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.evaluate(function() {
$("#giftMessages.noCard").prop("checked", true).trigger("click");
});
});
});
//Casper version using click
this.thenOpen('https://www.1800flowers.com/webapp/wcs/stores/servlet/FDDeliveryOptionsDisplayCmd', function() {
this.waitForSelector('#BP-DeliveryCardMess_1', function() {
this.click("#giftMessages.noCard");
});
});

How do i prevent my .done handler from being called multiple times?

I have this JQuery expression where i push a button, get some HTML from the server and then append it to a DOM node in my document:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").click(function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
});
});
});
</script>
I have multiple ".addButton" buttons on my web site. The problem im experiencing is that after multiple clicks on the buttons my .done handler is being called multiple times.
My guess is that i have a list of event handlers that are being executed, I cant understand where / why this is done or how I prevent it from happening.
The problem is not taht you do the request is done more then once rathern then it calls done after its done.. you can keep the state in data object::
$(document).ready(function () {
var posting = false;
$(".addbutton").data("done", false).click(function () {
var addbuttonNode = $(this);
if (!addbuttonNode.data("done")) {
addbuttonNode.data("done", true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data);
});
}
});
});
I would do the following:
$(".addbutton").click(function () {
var addbuttonNode = $(this);
addbuttonNode.attr('disabled',true);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' })
.done(function (data) {
$(addbuttonNode).next().next().append(data); //find better way of doing this
addbuttonNode.attr('disabled',false);
});
});
You could check it for any request pending:
$(document).ready(function () {
$(".addbutton").click(function () {
// if any request pending, return {undefined}
if ($.active) return;
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
If you wish instead each button to be clickable only once, then use jQuery .one() method:
$(document).ready(function () {
$(".addbutton").one('click', function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", {
id: '#guid'
}).done(function (data) {
// instead of .next().next()
$(addbuttonNode).nextAll('selector').first().append(data); //find better way of doing this
// or .parent().find('selector')
});
});
});
Try to use bind, and unbind functions for the event handling. Then You can unbind the click function after it was executed once.
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").bind('click',function () {
var addbuttonNode = $(this);
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
addbuttonNode.unbind('click');
});
});
</script>
Another way of doing nearly the same, I think this should be better:
<script type="text/javascript">
$(document).ready(function () {
$(".addbutton").each(function(){
$(this).bind('click',function () {
$.post("/InteractiveApplications/GetQuizAnswer", { id: '#guid' }).done(function (data) {
addbuttonNode.next().next().append(data);
});
$(this).unbind('click');
});
});
});
</script>
I haven't tried it yet, but it should work, try it! :)
You can also set up a class or data attribute to check if the button was already clicked. You can then exit from the script like if($(this).hasClass('clicked')) { return; } or something...

JavaScript setInterval inside bind

I am trying to make an infinite periodic get loop:
<script type=text/javascript>
$(function() {
$('a#log').bind('click', setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000));
});
</script>
If I do this
<script type=text/javascript>
$(function() {
$('a#log').bind('click', function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
});
});
</script>
All works well, but without infinite loop.
As #sacho say, setInterval() returns a Number. You are binding that number as your click handler instead a function. That's why is not working, but...
You can do something like this is just want to call the ajax function every time is finished, you can't be sure that your response will be every 2000ms.
$('a#log').click(function (e) {
e.preventDefault();
infiniteLoop();
})
function infiniteLoop() {
$.get(
$LOG + '/json_test',
{},
function(data) {
$("#logs").html(data.replace('\n', '<br/>'));
infiniteLoop();
}
);
}
Note: Use jQuery (specially to manage the DOM) every time you can if you already loaded the library
You need wrap your setInterval function in a intermediate function to prevent it from executed before your click. In other word, a function inside a function.
$(function () {
$('a#log').bind('click', function () {
setInterval(function () {
$.get('example.json',{}, function (data) {
$('#logs').html(JSON.stringify(data).replace('\n', '</br>'));
});
}, 2000);
});
});
JSfiddle Working Demo: http://jsfiddle.net/x13sruaf/
$('a#log').on('click', infiniteLoop);
function infiniteLoop() {
setInterval(function() {
}, 2000);
}
You can try this :
<script type=text/javascript>
$(function() {
var refreshIntervalId;
$('a#log').bind('click', function (){
clearInterval(refreshIntervalId);
refreshIntervalId = setInterval(function() {
$.get(
$LOG + '/json_test',
{},
function(data) {
document.getElementById("logs").innerHTML = data.replace('\n', '<br/>');
}
);
}, 2000);
});
});
</script>

Bind JQuery event to html created after pageload via jquery

I am developing a jquery module for add delete edit view etc.
My problem is when page load complete, a list of items populate. After selecting an item this item's subitems loaded via jquery and html built, appended. But on this table event not fired up. Jquery Live is no longer available. Instead "On" is not working.
I tried :
$(document).on('click', selector , function () { foo(); });
But when a button is clicked it triggers other buttons as well.
My code is below.
I have a working code except links on table which loaded by jquery.
var myModule = {
el: {
listbutton: $('#list-button'),
listcontainer: $('#list'),
detailbutton: $(".item-detail"),
deletebutton: $(".item-delete"),
editbutton: $(".item-edit")
},
init: function() {
...
myModule.el.listbutton.on("click",myModule.getMainData);
},
getMainData: function() {
...
success: function(data) {
myModule.BuildTable(data.Value.DataList);
}
...
},
BuildTable: function (hws) {
var c = "";
c += "<table>";
$.each(hws, function() {
c +=
'<tr>' +
'<td>' + this.Title + '</td>' +
'<td></td>' +
'<td></td>' +
'<td></td>' +
'<tr>';
});
c += "</table>";
myModule.el.listcontainer.empty().append(c);
myModule.TableLinks();
},
itemDetails: function () {
alert("Detail clicked");
},
itemDelete: function () {
alert("Delete clicked");
},
itemEdit: function () {
alert("Edit clicked");
},
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
$(document).on('click', myModule.el.deletebutton, function () { myModule.itemDelete(); });
$(document).on('click', myModule.el.editbutton, function () { myModule.itemEdit(); });
},
};
myModule.init();
Can you try following:
TableLinks: function () {
$(document).on('click',
".item-detail",
function (ev) {
myModule.itemDetails();
ev.stopPropagation();
}
);
$(document).on('click',
".item-delete",
function (ev) {
myModule.itemDelete();
ev.stopPropagation();
});
$(document).on('click',
".item-edit",
function (ev) {
myModule.itemEdit();
ev.stopPropagation();
});
},
you need the delegation
$("selector on which item is added").on("click", "new item selector", function(){
});
ON and Delegate
You have to do something like this to use the "on" method.
$("table").on("click", myModule.el.detailbutton, myModule.itemDetails());
UPDATE: Just noticed, you have to used a selector not a jQuery object in the second parameter.
So $("table").on("click", ".item-detail", myModule.itemDetails());
your approach using on is exactly what you need, but should have been bit more careful on constructing the element object
el: {
listbutton: '#list-button',
listcontainer: '#list',
detailbutton: ".item-detail",
deletebutton: ".item-delete",
editbutton: ".item-edit"
},
and use it like this
init: function () {
$(myModule.el.listbutton).on("click", myModule.getMainData);
},
what you did is
TableLinks: function () {
$(document).on('click', myModule.el.detailbutton, function () { myModule.itemDetails(); });
...
},
which is similar to and which is wrong
TableLinks: function () {
$(document).on('click', $(".item-detail"), function () { myModule.itemDetails(); });
....
},
working fiddle

Is it possible to bind multiple functions to multiple delegation targets in one place?

As it is possible to define multiple event handlers in one single function in jQuery like this:
$(document).on({
'event1': function() {
//do stuff on event1
},
'event2': function() {
//do stuff on event2
},
'event3': function() {
//do stuff on event3
},
//...
});
Then again we can do this:
$(document).on('click', '.clickedElement', function() {
//do stuff when $('.clickedElement') is clicked
});
I was wondering if it is also possible to do something like this (the following code does not work, it's just for illustration):
$(document).on('click', {
'.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
},
'.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
},
//... and so on
});
This code gives me an error complaining about the "," after '.clickedElementX'. I also tried it like this:
$(document).on('click', {
'.clickedElement1': function() {
//do stuff when $('.clickedElement1') is clicked
},
//... and so on
});
Then I don't have the error but also the function is not executed. Is there a way to collect all the click handlers in one place like this or would I have to always do it like this:
$(document).on('click', '.clickedElement1', function() {
//do stuff when $('.clickedElement1') is clicked
});
$(document).on('click', '.clickedElement2', function() {
//do stuff when $('.clickedElement2') is clicked
});
//... and so on
You can chain :
$(document).on({
click: function() {
//click on #test1
},
blur: function() {
//blur for #test1
}
}, '#test1').on({
click: function() {
//click for #test2
}
}, '#test2');
FIDDLE
Short answer: no, you have to bind them all separately.
Long answer: You can create an "infrastructure" for your site and have all events in one place. e.g.
var App = function(){
// business logic
return {
Settings: { ... },
Events: {
'event1': function(){
},
'event2': function(){
},
'event3': function(){
}
}
}
}();
Then wiring it up involves:
$(document).on(App.Events);
Then internally you can add then new bindings to your App object but still remains wired up in only one place (as far as jQuery is concerned). You could then make some kind of subscriber model within App (e.g. App.Subscribe('click', function(){ ... })) and each new subscription still is only wired through the single .on() binding.
but, IMHO, this is a lot of overhead with very little pay-off.
$(document).on('click' , function(e){
if($(e.target).hasClass("some-class")){
//do stuff when .some-class is clicked
}
if($(e.target).hasClass("some-other-class")){
//do stuff when .some-other-class is clicked
}
});
you can choose any some-class you want
It can be easily done, really:
$(document).ready(function()
{
$(this).on('click', '.one, .two',function()
{
if ($(this).hasClass('one'))
{//code for handler on .one selector
console.log('one');
}
else
{//code for handler on .two selector
console.log('two');
}
console.log(this);//code for both
});
});
If multiple events is what you're after:
$(document).ready(function()
{
$(this).on('click focus', '.one, .two',function()
{
if (event.which === 'click')
{
if ($(this).hasClass('one'))
{
console.log('one');
}
else
{
console.log('two');
}
}
else
{
console.log('focus event fired');
}
console.log(this);
});
});
Play around with this: here's a fiddle
documentation on event
jQuery's on, which is used here as though it were delegate
you can use a helper function:
function oneplace(all){
for (var query in all){
$(query).on('click', all[query]);
}
}
and then call:
oneplace(
{'#ele1':function(){
alert('first function');
},
'#ele2':function(){
alert('second function');
}});
jsfiddle here: http://jsfiddle.net/5zwkf/

Categories

Resources