jquery regarding toggle () - jquery-selectors

I need to toggle an element ONLY if it is not disabled.
jQuery("#sbutton").toggle(
function () {
if (!jQuery(\'input[name^="choose"]\').attr ( "disabled" )) {
jQuery(\'input[name^="choose"]\').attr ( "checked" , true);
}
},
function () {
jQuery(\'input[name^="choose"]\').removeAttr("Checked");
}
)
Is the IF condition possible?

What you probably want to do (thanks Frédéric):
jQuery("#sbutton").click(function() {
if (jQuery('input[name^="choose"]').is(':disabled'))
return false;
if (jQuery('input[name^="choose"]').is(':checked'))
jQuery('input[name^="choose"]').removeAttr("checked");
else
jQuery('input[name^="choose"]').attr("checked", true);
});
or simply
jQuery("#sbutton").click(function() {
var checkbox = jQuery('input[name^="choose"]');
if (checkbox.is(':disabled'))
return false;
checkbox.attr('checked', !checkbox.is(':checked'));
});
The problem with your code is that you expect the evaluation on disabled to be evaluated on every button click and use the first function if true. It's only called on every other click though, and the other function doesn't care if it's disabled or not. It checks the check box no matter what. You have to either bind on the click event, like I've done, or bind to and unbind from the toggle event depending on whether or not the button is disabled.
In the future it would be easier to help you if you present your code as a fiddle (http://www.jsfiddle.net) and describe more thoroughly what you're trying to do and what it is that's not working.

Related

ag-grid column menu reset columns event?

Does ag-grid have a grid event that corresponds to to the "Reset Columns" item that is at the bottom of each column menu?
I need to do some special processing on "Reset Columns", and different handling of column "move", "resize", (etc.). I setup an event handler for the "columnEverythingChanged" event and a different event handler for "columnMoved" (etc.). I found that:
1) When no changes have been made to any column and I press "Reset Columns", "columnEverythingChanged" gets called. Fine.
2) When one or more columns have been changed and I press "Reset Columns", both "columnEverythingChanged" AND "columnMoved" (or other) get called.
My problem: in case (2), my "columnMoved" logic should not run.
A secondary problem: "columnEverythingChanged" also gets called at application startup. Not a big deal, but I had to hack around it.
This was so long ago, I don't remember the details. But in my code, I see that I use the columnMoved, columnResized, columnVisible, filterChanged, and sortChanged events. I run the same function on all of these events. That function debounces the event before doing my special processing.
you can use GlobalListener to work with multiple events without issue
gridOption.api.addGlobalListener(GlobalListenerSaveColumnState);
function GlobalListenerSaveColumnState(type, event) {
if (type == "columnVisible" || type == "columnResized"|| type == "columnMoved"|| type == "columnPinned" || type == "dragStopped") {
UpdateGridDefaultsIntoDb(event);
}
}
I solved this by 'overriding' the default getMainMenuItems function, which basically creates that "hamburger" icon, and reveals the options inside the Main Menu. When overriden, you can supply the list of items you want to include, and you can give it your own function you want to run when "Reset Columns" is clicked.
this.gridOptions = {
viewportDatasource: {
init: this.init,
setViewportRange: this.setViewportRange,
},
rowModelType: 'viewport',
sideBar: localStorage.getItem('test_pivot') == 'true' ? 'columns' : '',
suppressRowClickSelection: false,
suppressMultiSort: true,
rowMultiSelectWithClick: true,
rowSelection: 'multiple',
getMainMenuItems: (params) => this.getMainMenuItems(params), // <- This piece right here
getContextMenuItems: this.getContextMenuItems,
};
Later you define that getMainMenuItems()
getMainMenuItems(params) {
params.defaultItems[params.defaultItems.length - 1] = {
name: this.translate.instant('i18n.reset_columns'),
action: () => {
this.onResetColumnStateClick(null); // <- The custom functionality you want to execute when Reset Columns is clicked
},
};
return params.defaultItems;
}
I believe their documentation has another example containing the getMainMenuItems function
https://ag-grid.com/javascript-data-grid/column-menu/
https://plnkr.co/edit/?open=main.js&preview

How to fire place_changed event for Google places auto-complete on Enter key

The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.
function locationAuto() {
$('.search-location').focus(function () {
autocomplete = new google.maps.places.Autocomplete(this);
searchbox = this;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var thisplace = autocomplete.getPlace();
if (thisplace.geometry.location != null) {
$.cookie.raw = true;
$.cookie('location', searchbox.value, { expires: 1 });
$.cookie('geo', thisplace.geometry.location, { expires: 1 });
}
});
});
The .search-location is a class on multiple textboxes.
There is a submit button that takes the values from the cookies and redirects (server side)
Adapted from Jonathan Caulfield's answer:
$('.search-location').keypress(function(e) {
if (e.which == 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
return false;
}
});
I've encountered this problem as well, and came up with a good solution. In my website I wanted to save the autocomplete.getPlace().formatted_address in a hidden input prior to submission. This worked as expected when clicking the form's submit button, but not when pressing the Enter key on the selection in the autocomplete's dropdown menu. My solution was as follows:
$(document).ready(function() {
// Empty the value on page load
$("#formattedAddress").val("");
// variable to indicate whether or not enter has been pressed on the input
var enterPressedInForm = false;
var input = document.getElementById("inputName");
var options = {
componentRestrictions: {country: 'uk'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$("#formName").submit(function(e) {
// Only submit the form if information has been stored in our hidden input
return $("#formattedAddress").val().length > 0;
});
$("#inputName").bind("keypress", function(e) {
if(e.keyCode == 13) {
// Note that simply triggering the 'place_changed' event in here would not suffice, as this would just create an object with the name as typed in the input field, and no other information, as that has still not been retrieved at this point.
// We change this variable to indicate that enter has been pressed in our input field
enterPressedInForm = true;
}
});
// This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined, and the next time it has the data. This is why the following logic has been added.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// If getPlace() is not undefined (so if it exists), store the formatted_address (or whatever data is relevant to you) in the hidden input.
if(autocomplete.getPlace() !== undefined) {
$("#formattedAddress").val(autocomplete.getPlace().formatted_address);
}
// If enter has been pressed, submit the form.
if(enterPressedInForm) {
$("#formName").submit();
}
});
});
This solution seems to work well.
Both of the above responses are good answers for the general question of firing a question when the user presses "enter." However - I ran into a more specific problem when using Google Places Autocomplete, which might have been part of the OP's problem. For the place_changed event to do anything useful, the user needs to have selected one of the autocomplete options. If you just trigger 'place_changed', the if () block is skipped and the cookie isn't set.
There's a very good answer to the second part of the question here:
https://stackoverflow.com/a/11703018/1314762
NOTE: amirnissim's answer, not the chosen answer, is the one to use for reasons you'll run into if you have more than one autocomplete input on the same page.
Maybe not the most user friendly solution but you could use JQuery to disable the enter key press.
Something like this...
$('.search-location').keypress(function(e) {
if (e.which == 13) {
return false;
}
});

kendo ui cancel treeview drop

i have a TreeView that once the user drops the item to the desired position, it displays a dialog box and asks for confirmation, if the user selects cancel, how would i also cancel the placement of the item so it goes back to its original position? my current code is below but isnt working:
var newDiv = $(document.createElement('div'));
newDiv.html('Are you sure you want to move the item: ' + title);
newDiv.dialog( {
autoOpen: true,
width: 600,
buttons: {
"Save": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
e.setValid = false;
}
}
});
I have also tried doing the same kind of code on the dragend event and using e.preventDefault(); with no more luck
The drop event handler provides the setValid function, which can prevent the drop from occurring. For example:
function onDrop(e) {
e.setValid(confirm('Do you wish to move this item here?'));
}
$("#treeView").kendoTreeView({
// ...
dragAndDrop: true,
drop: onDrop
});
I've written a fiddle which demonstrates how this works.
Did you try to use the drop event and call prevent default there if the condition is not satisfied?

Ignore multiple button taps after first one on iPhone webapp using jQuery Mobile?

Assume button A in an HTML5 webapp built with jQuery Mobile.
If someone taps button A, we call foo(). Foo() should get called once even if the user double taps button A.
We tried using event.preventDefault(), but that didn't stop the second tap from invoking foo(). event.stopImmediatePropagation() might work, but it also stops other methods further up the stack and may not lead to clean code maintenance.
Other suggestions? Maintaining a tracking variable seems like an awfully ugly solution and is undesirable.
You can set a flag and check if it's OK to run the foo() function or unbind the event for the time you don't want the user to be able to use it and then re-bind the event handler after a delay (just a couple options).
Here's what I would do. I would use a timeout to exclude the subsequent events:
$(document).delegate('#my-page-id', 'pageinit', function () {
//setup a flag to determine if it's OK to run the event handler
var okFlag = true;
//bind event handler to the element in question for the `click` event
$('#my-button-id').bind('click', function () {
//check to see if the flag is set to `true`, do nothing if it's not
if (okFlag) {
//set the flag to `false` so the event handler will be disabled until the timeout resolves
okFlag = false;
//set a timeout to set the flag back to `true` which enables the event handler once again
//you can change the delay for the timeout to whatever you may need, note that units are in milliseconds
setTimeout(function () {
okFlag = true;
}, 300);
//and now, finally, run your original event handler
foo();
}
});
});
I've created a sample here http://jsfiddle.net/kiliman/kH924/
If you're using <a data-role="button"> type buttons, there is no 'disabled' status, but you can add the appropriate class to give it the disabled look.
In your event handler, check to see if the button has the ui-disabled class, and if so, you can return right away. If it doesn't, add the ui-disabled class, then call foo()
If you want to re-enable the button, simply remove the class.
$(function() {
$('#page').bind('pageinit', function(e, data) {
// initialize page
$('#dofoo').click(function() {
var $btn = $(this),
isDisabled = $btn.hasClass('ui-disabled');
if (isDisabled) {
e.preventDefault();
return;
}
$btn.addClass('ui-disabled');
foo();
});
});
function foo() {
alert('I did foo');
}
});

Click not firing first time after rebind with live() method

I understand that this is a probably a noob-ish question, but I've had no luck with the other threads I've found on the same topic.
I've devised a workaround to hack a views exposed filter to hide and show products with a stock count of "0". The exposed filter for the stock count (input#edit-stock) is hidden with CSS and inside a custom block is a link to manipulate the form and trigger the query (with ajax). This is working great, but with one exception - after resetting the form with the views-provided "reset" button, toggle() will not rebind properly to the link, and click won't fire the first time. Works fine on the 2nd click. I'm sure that the solution is very simple, but I'm at a loss..
How to rebind toggle() effectively?
Sorry, I'm unable to provide a live example. Many thanks for any input.
CUSTOM BLOCK:
<a id="toggle" href="#">exclude</a>
JQUERY:
$(document).ready(function () {
var include = function () {
$('input#edit-stock').attr('value', 0).submit();
$('a#toggle').html('include');
};
var exclude = function () {
$('input#edit-stock').attr('value', '').submit();
$('a#toggle').html('exclude');
};
$('a#toggle').toggle(include, exclude);
$('input#edit-reset').live('click', function (event) {
$('a#toggle').unbind('toggle').toggle(include, exclude).html('exclude');
});
});
if i get the problem right you need to reset the toggle. Why instead of unbind toggle and rebinding it you just don't simulate a click if the link is == to include?
$(document).ready(function () {
var include = function () {
$('input#edit-stock').attr('value', 0).submit();
$('a#toggle').html('include');
};
var exclude = function () {
$('input#edit-stock').attr('value', '').submit();
$('a#toggle').html('exclude');
};
$('a#toggle').toggle(include, exclude);
$('input#edit-reset').live('click', function (event) {
//if the link is include, click it so that it resets to exclude, else do nothing
if ($('a#toggle').html() == 'include'){
$('a#toggle').click();
}
});
});
fiddle here: http://jsfiddle.net/PSLBb/
(Hope this is what you were looking for)