Jquery unresponsive for certain functions - jquery-ui

Here we go, the variable $thislistitem, in bold below, is in the same place in my function. I seperated it to bold it. Focus on the jquery ui buttons being created and the click events.
function activatequalifdetails($subgrid, qualId){
$subgrid.find('.itemcontrols').hide();
$subgrid.find("#detailedsubjects ol").on("click", "li", function(event){
event.stopPropagation();
var $itemwithfoucsclass = $(".focus");
/* <![CDATA[ */ if(($itemwithfoucsclass[0] != $(this)[0]) && ($itemwithfoucsclass.length !== 0)){ /* ]]> */
$.post('<c:url value="/highschooldetailedqualifications/highschoolqualdetailedajaxupdate/"/>'+$itemwithfoucsclass.find('.itemcontrols button:nth-child(1)').attr("qualdetailid"), {grade: $itemwithfoucsclass.find('.grade').val(), yearattained: $itemwithfoucsclass.find('.yearAttained').val()});
}
var $thislistitem = $(this);
$subgrid.find('#detailedsubjects ol li').not(this).removeClass('focus').find('.itemcontrols').hide();
$(this).addClass("focus").find('.itemcontrols').show();
$(this).find('.itemcontrols button:nth-child(1)').button({
icons: {
primary: "ui-icon-disk"
},
text: false
}).unbind('click').click(function(){
$.post('<c:url value="/highschooldetailedqualifications/highschoolqualdetailedajaxupdate/"/>'+$(this).attr("qualdetailid"), {grade: $thislistitem.find('.grade').val(), yearattained: $thislistitem.find('.yearAttained').val()}, function(data){
$thislistitem.removeClass('focus').find('.itemcontrols').hide();
});
});
$(this).find('.itemcontrols button:nth-child(2)').button({
icons: {
primary: "ui-icon-trash"
},
text: false
}).unbind('click').click(function(){
$.get('<c:url value="/highschooldetailedqualifications/highschoolqualdetailedajaxdelete/"/>'+qualId+'/'+$(this).attr("qualdetailid"), function(data){
$thislistitem.remove();
});
});
$(this).find('.itemcontrols button:nth-child(3)').button({
icons: {
primary: "ui-icon-closethick"
},
text: false
}).unbind('click').click(function(){
$thislistitem.removeClass('focus').find('.itemcontrols').hide()
});
});//apply css class on click on any given item
}
The click events for the save and delete work perfectly. The click event for the cancel button however (3rd button) is giving some starnge behavior. The click logic for the 3rd button is identical to that of the save, only difference is the icon and no post id required.
When I click the cancel button, nothing happens.
If I do
.unbind('click').click(function(){
$thislistitem.remove();
});
for the 3rd button, it works.
If I alert some test text, it works fine. If use removeClass() nothing occurs.
I tried copying and pasting the save function as is, change the icon and so on and left the ajax call intact. this worked fine and the focus class was removed. If I remove the ajax call and run the logic as seen in the function above, well nothing happens. Firebug reports nothing.
I have several versions of jquery loaded on this page, (1.4.3, 1.4.2, 1.5.1, 1.6.2 & 1.7.2), in that order. Could this be my problem ? I need the different versions for different plugins i am using for other things. Any ideas ?
I am totally stumped.

Ok so this is what I had to do, looks like a very very fundimental mistake on my behalf.
$(this).find('.itemcontrols button:nth-child(3)').button({
icons: {
primary: "ui-icon-closethick"
},
text: false
}).unbind('click').click(function(){
$thislistitem.removeClass('focus').find('.itemcontrols').hide();
return false;
});
All i needed to do was add return false; after my logic. Hope it helps someone out there.

Related

jQuery $(document).ready() issue - jQuery 1.7.2

I have a page on which I am loading a select tag with options that I am getting from an ajax call to a service. It is working just fine and loading the select tag correctly. I only want this loading to happen once when the user first arrives at the page so I put the call to the function that does this inside the $(document).ready(function call. The problem that I am seeing is that when the user selects one of the options and then clicks a button under certain circumstances I pop a dialog (jQuery UI) telling them they need to take a certain action. The first time this happen and only the first time the selected option is getting reset somehow to the first option in the list. I ran in debug many times and discovered that if this is the first time on the page the selector is loaded on arrival at the page as is expected but if the dialog gets popped it is loaded again - only the first time - after that if the dialog gets popped the reload does not occur and all is well. The abbreviated code:
$(document).ready(function () {
$.fn.LoadStuff();
});
jQuery.fn.LoadStuff = function () {
//load up the select tag with options
};
LoadStuff does not get called anywhere else. selOffers is the select tag and dvConflict is the dialog. They are not sharing a common parent div.
<select id="selOffers"></select>
<div id="dvConflict"><div id="dvConflictMsg" /></div>
jQuery for the dialog:
var optSave = {
width: 400,
modal: true,
resizable: false,
draggable: false,
closeOnEscape: true,
zIndex: 1320,
buttons: [
{
text: 'Ok',
click: function () {
$(this).dialog('close');
}
}
]
}
$(".ui-dialog-titlebar").hide(); //Hides the title
$('#dvConflict').css('background', 'none'); //Takes out our custom background
$('#dvConflict').dialog(optSave);
EDIT: Two things
Use $.LoadStuff = function () { } instead of $.fn.LoadStuff = function () {...}. The first is to be called at any context via $.LoadStuff();. The latter is to be used on an element-selection, like $("div.to-load").LoadStuff();.
$(document).ready is fired every time the DOM finishes loading. In some AJAX calls, you could be reloading parts of your DOM, or an internal frame (I don't know, though I don't have your code).
The following code sample will help you bypass the problem:
var first = true;
$(document).ready(function () {
if (first) $.LoadStufF();
...
first = false;
}
When opening a dialog, make sure there are no <script> tags inside the dialog-wrapped element. Say you have the code line:
$('#dialoged').dialog({ ... });
So a bad practice is to have:
<div id="dialoged">
<script>
var first = true;
$(document).ready(function () {
if (first) $.LoadStufF();
...
first = false;
}
</script>
</div>

jQuery UI Accordion - does refresh method overwrites initialisation settings?

Currently I am working on a project for which I use the jQuery UI Accordion.
Therefore I initialise the accordion on an element by doing
<div id="accordion"></div>
$('#accordion').accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
After init the accordion I append some data coming from an AJAX request. (depends on user interaction)
In a simplified jsfiddle - which does exact the same thing as the ajax call - you can see how this looks like.
So far it seems to be working quite well but there is one problem I face.
In my initialisation I say that I want all panels to be closed but after calling refresh on the accordion everything of those settings seems to be gone and one panel opens.
Note that I implemented jQuery UI v1.10.2 in my fiddle. Update notes say
The refresh method will now recognize panels that have been added or removed. This brings accordion in line with tabs and other widgets that parse the markup to find changes.
Well it does but why has it to "overwrite" the settings I defined for this accordion?
I also thought about the possibility that it might be wrong to create the accordion on an empty <div> so I tested it with a given entry and added some elements afterwards.
But the jsfiddle shows exactly the same results.
In a recent SO thread I found someone who basically does the same thing as I do but in his jsfiddle he faces the same "issue".
He adds a new panel and the first panel opens after the refresh.
My current solution for this issue is to destroy the accordion and recreate it each time there's new content for it.
But this seems quite rough to me and I thought the refresh method solves the need to destroy the accordion each time new content gets applied.
See the last jsfiddle
$(document).ready(function () {
//variable to show "new" content gets appended correctly
var foo = 1;
$('#clickMe').on('click', function () {
var data = '';
for (var i = 0; i < 3; i++) {
data += '<h3>title' + foo + '</h3><div>content</div>';
foo++;
}
if ($('#accordion').hasClass('ui-accordion')) {
$('#accordion').accordion('destroy');
}
$('#accordion').empty().append(data).accordion({
collapsible: true,
active: false,
heightStyle: "content"
});
});
});
Unfortunately it is not an option for me to change the content of the given 3 entries because the amount of panels varies.
So my questions are the one in the title and if this behaviour is wanted like that or if anybody faces the same problem?
For the explanation of this behaviour, have a look in the refresh() method of the jquery-ui accordion widget, the problem you are facing is at line 10 :
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ((options.active === false && options.collapsible === true) || !this.headers.length) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} if (options.active === false) {
this._activate(0); // <-- YOUR PROBLEM IS HERE
// was active, but active panel is gone
} else if (this.active.length && !$.contains(this.element[0], this.active[0])) {
// all remaining panel are disabled
if (this.headers.length === this.headers.find(".ui-state-disabled").length) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate(Math.max(0, options.active - 1));
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index(this.active);
}
this._destroyIcons();
this._refresh();
}

jquery mobile trigger click doesn't work the first time

I have a jquery mobile form with several radio inputs whit the options "DS", "NO" and "YES". I want when I click a button it simulates a click on the "YES" option of all radio buttons.
I use this code:
$("#btn-all-yes").click(function(){
$(".replay-yes").each(function(index, element){
$(element).trigger("click");
//$(element).click();
});
});
But I need to do click two times in the button to achieve the desired result. If I put the line '$(element).trigger("click")' two times it works, but I think it should work with a single call to the click event.
You can see all the code at http://jsfiddle.net/qwLPH/7/
You need to change its' status using .prop and then refresh it .checkboxradio('refresh').
Working demo
Update - Uncheck other buttons
$("#btn-all-yes").click(function () {
$('[data-role="controlgroup"]').find("[type=radio]").each(function () {
if ($(this).hasClass('replay-yes')) {
$(this).prop('checked', true).checkboxradio("refresh");
} else {
$(this).prop('checked', false).checkboxradio("refresh");
}
});
});
Old answer
$("#btn-all-yes").click(function(){
$(".replay-yes").each(function(index, element){
$(element).prop('checked', true).checkboxradio("refresh");
});
});
Reference
Similar issue
Try to initialize the click on page load:
$(".replay-yes").each(function (index, element) {
$(element).trigger("click");
//$(element).click();
}).click();
//-^^^^^^^----------this way
Tryout in fiddle here

Click and keydown at same time for draggable jQuery event?

I'm trying to have a jQuery UI event fire only if it meets the criteria of being clicked while the shift key is in the keydown state ( to mimic being held), and if not disable the event.
This example uses jQuery UI's .draggable to drag a container div only if the user clicks and holds shift.
http://jsfiddle.net/zEfyC/
Non working code, not sure if this is the best way to do this or what's wrong.
$(document).click(function(e) {
$('.container').keydown(function() {
if (e.shiftKey) {
$('.container').draggable();
} else {
$('.container').draggable({
disabled: true
});
}
});
});​
I see lots of errors with that code. Firstly, you only add the key listener after there's been a click on the document. Second you are adding keydown to the container div, rather than the whole document. Then, you also need to listen to keyup, since releasing the shift key should disable draggability, then you also need to pass disabled: false to the case where shift is down. And your handler is missing the e parameter. Try this:
$(function(e) {
var handler = function(e) {
if (e.shiftKey) {
$('.container').draggable({
disabled: false
});
} else {
$('.container').draggable({
disabled: true
});
}
};
$(document).keydown(handler);
$(document).keyup(handler);
});

jQuery UI autocomplete select event not working with mouse click

I have a list of links, and I have this search box #reportname. When the user types in the search box, autocomplete will show the text of the links in a list.
<div class="inline">
<div class="span-10">
<label for="reportname">Report Name</label>
<input type="text" name="reportname" id="reportname" />
</div>
<div class="span-10 last">
<button type="button" id="reportfind">Select</button>
</div>
</div>
The user can then use the keyboard arrow to select one of the text, and when he press ENTER, browser will go to the address of the link. So far so good.
<script type="text/javascript">
$(document).ready(function () {
$("#reportname").autocomplete({
source: $.map($("a.large"), function (a) { return a.text }),
select: function () { $("#reportfind").click() }
})
$("#reportfind").click(function () {
var reportname = $("#reportname")[0].value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
})
});
</script>
The issue is when the user types, autocomplete shows a list, and then the user use the mouse to click one of the result. With keyboard navigation, the content of the search box is changed, but if the user clicks one of the options, the search box is not modified and the select event is immediately triggered.
How can I make the script work with keyboard selection and mouse selection? How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?
To your 2nd question: "How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?"
The event object in the jQuery UI events would include a .originalEvent, the original event it wrapped. It could have been wrapped multiple times though, such as in the case of Autocomplete widget. So, you need to trace up the tree to get the original event object, then you can check for the event type:
$("#reportname").autocomplete({
select: function(event, ui) {
var origEvent = event;
while (origEvent.originalEvent !== undefined)
origEvent = origEvent.originalEvent;
if (origEvent.type == 'keydown')
$("#reportfind").click();
},
...
});
Thanks to #William Niu and firebug, I found that the select event parameter 'ui' contains the complete selected value: ui.item.value. So instead of depending on jquery UI to change the text of the textbox, which didn't happen if the user clicks with mouse, I just pick up the selected value from 'ui':
$("#reportname").autocomplete({
select: function (event, ui) {
var reportname = ui.item.value
var thelinks = $('a.large:contains("' + reportname + '")').filter(
function (i) { return (this.text === reportname) })
window.location = thelinks[0].href
};
})
I tested it in all version of IE (inlcuding 9) and always ended up with an empty input-control after I selected the item using the mouse. This caused some headaches. I even went down to the source code of jQuery UI to see what happens there but didn’t find any hints either.
We can do this by setting a timeout, which internally queues an event in the javascript-engine of IE. Because it is guaranteed, that this timeout-event will be queued after the focus event (this has already been triggered before by IE itself).
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
$this = $(this);
setTimeout(function () {
$('#txtBoxRole').val(value);
}, 1);
},
Had the same issue / problem.
Jquery: 1.11.1
UI: 1.11.0
Question: Do you use bassistance jquery validte plugin simultanously?
If positive: update this to a newest version or just disable it for tests.
I updated from 1.5.5 to 1.13.0
Helped for me. Good luck!
I recently encountered the exact same problem (autocomplete items not clickable, keyboard events working).
Turned out that in my case the answer was not at all JS related. The autocomplete UI was not clickable simply because it was lacking an appropriate value for the z-index CSS property.
.ui-autocomplete {
z-index: 99999; /* adjust this value */
}
That did the trick.
This may be a bit farshot, but I had a similar situation where selecting an autocomplete value left the input field empty. The answer was to ignore the "change" events (as those were handled by default) and replace them with binds to "autocompletechange" events.
The "change" event gets triggered before the value from autocomplete is in the field => the field had "empty" value when handling the normal "change" event.
// ignore the "change" event for the field
var item = $("#"+id); // JQuery for getting the element
item.bind("autocompletechange", function(event, ui) { [call your handler function here] }
I was facing a similar problem. I wanted to submit the form when the user clicked on an option. But the form got submitted even before the value of the input could be set. Hence on the server side the controller got a null value.
I solved it using a modified version of William Niu's answer.
Check this post - https://stackoverflow.com/a/19781850/1565521
I had the same issue, mouse click was not selecting the item which was clicked.My code was supposed to make an ajax call to fetch the data as per the selection item from autocomplete source.
Previous code: mouse click not working.
select: function(event, ui) {
event.preventDefault();
for(i= 0; i< customer.length; i++)
if(document.getElementById('inputBox').value == customer[i].name)
{
$.ajax({
call
})
Changed code :mouse click working
select: function(event, ui) {
// event.preventDefault();
for(i= 0; i< customer.length; i++)
// if(document.getElementById('inputBox').value == customer[i].fields.name)
if(ui.item.value == customer[i].name)
{
$.ajax({
call
})
After inspecting the code in the developer tools console, I noticed there were two list items added. I removed the pairing <li></li> from my response code and oh yeah, the links worked
I also added this function as the click event:
$("#main-search").result(function ()
{
$("#main-search").val("redirecting...."), window.location.href = $("#main-search").attr("href").match(/page=([0-9]+)/)[1];
})
This works and you can test it here: Search for the term dress -->

Resources