This may be a stupid question but I'd like to get some clarification on the matter. I have a function that loops through an array and copies values from input A to input AA (B to BB, and so on). But I want this function to execute when a hidden div is visible only. So I was trying to do this:
$('#showSave').on('click', function () {
copyInputValues();
$('#divModal').css('display', 'block');
});
Then I also tried this to no avail:
$('#showSave').click(copyInputValues);
This is my custom function:
function copyInputValues() {
var minInputs = ['abel1', 'abel2', 'abel3', 'abel4'];
$.each(minInputs, function (i, val) {
$('#l' + val).change(function () {
$('#modalL' + val).val($(this).val());
});
});
}
What is wrong with these scripts? I'm not very versed on javascript or jquery. I'm kinda learning and I've found stackOverflow to be a great source of information.
Thanks again for your help!
You can use
if ($('#divModal').css('display') == 'block') {
copyInputValues();
}
OR
if (!$("#divModal").css('visibility') === 'hidden') {
copyInputValues();
}
OR
if($('#divModal').is(':visible')) {
copyInputValues();
}
Related
Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.
I just came to know about the jQuery .on() method and decided to use it as it was much cleaner than using multiple binds. It is working as long as I am using pre-defined events but when I am trying to add custom events it is not working.
I have this auxiliary function
var EV_ENTER_KEY = "enterKey";
function bind_events(cur_obj, e) {
if (e.keyCode == 13) {
$(cur_obj).trigger(EV_ENTER_KEY);
}
}
which I am using in the following code
CATEGORY_INPUT.on({
keyup: function (e) {
bind_events(this, e);
}
});
//Action for Category Search box Enter press
CATEGORY_INPUT.bind(EV_ENTER_KEY, function () {
alert("Aseem");
});
I am changing it to the following
CATEGORY_INPUT.on({
keyup: function (e) {
bind_events(this, e);
},
EV_ENTER_KEY: function () {
alert("Aseem");
}
});
But it is not working. No errors are being logged in console either for this. I looked and found this and I think I am using it correctly. The API reference did not have any examples of binding multiple events. Can someone tell whether I missed something in the API? If not what is the problem here?
It seems you have to give the custom event as string directly instead of storing it in a js variable and then using it.
If you change EV_ENTER_KEY to "enterKey" in your multiple event binding then it will work.
$(".myInput").on({
keyup: function (e) {
bind_events(this, e);
},
"enterKey": function () {
alert("Enter key pressed");
}
});
JS fiddle demo : http://jsfiddle.net/9ur4c/
It can be made to work like this. This is according to this answer
var EV_ENTER = "enter"
categoryInputEvents = {}
categoryInputEvents[EV_ENTER] = function(e) {
alert("Enter Event");
}
CATEGORY_INPUT.on(categoryInputEvents)
Although this still does not explain the thing reported by #Sanjeev but it is better to have alternatives.
I am stuck. Searched and tried for hours.
EDIT:
I still can't make it work. Okay, I'll just put the source code to make it clear what I want to accomplish.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
var date_fmt="yyyy-mm-dd";
var time_fmt="HH:MM";
var date_field="#id_start_0, #id_end_0"; //id refering to html input type='text'
var time_field="#id_start_1, #id_end_1"; //id refereing to html input type='text'
function clearFmt(fmt_type)
{
if($(this).val() == fmt_type) {
$(this).val("");
}
}
function putFmt(fmt_type)
{
if($(this).val() == "") {
$(this).val(fmt_type);
}
}
$(document).ready(function() {
$(date_field).attr("title",date_fmt);
$(time_field).attr("title",time_fmt);
$(date_field).click(function() {
clearFmt(date_fmt);
});
$(date_field).blur(function(){
putFmt(date_fmt);
});
$(time_field).click(function(){
clearFmt(time_fmt);
});
$(time_field).blur(function(){
putFmt(time_fmt);
});
});
</script>
Help ?
Use the jquery bind method:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").bind('click', { key: 'value' }, myfunc);
});
Also see my jsfiddle.
=== UPDATE ===
since jquery 1.4.3 you also can use:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").click({ key: 'value' }, myfunc);
});
Also see my second jsfiddle.
=== UPDATE 2 ===
Each function has his own this. After calling clearFmt in this function this is no longer the clicked element. I have two similar solutions:
In your functions add a parameter called e.g. element and replace $(this) with element.
function clearFmt(element, fmt_type) {
if (element.val() == fmt_type) {
element.val("");
}
}
Calling the function you have to add the parameter $(this).
$(date_field).click(function() {
clearFmt($(this), date_fmt);
});
Also see my third jsfiddle.
-=-
An alternative:
function clearFmt(o) {
if ($(o.currentTarget).val() == o.data.fmt_type) {
$(o.currentTarget).val("");
}
}
$(date_field).click({fmt_type: date_fmt}, clearFmt);
Also see my fourth jsfiddle.
The following should work as seen in this live demo:
function myfunc(bar) {
alert(bar);
}
$(function() {
$("#foo").click( function() {
myfunc("value");
});
});
anyFunctionName = (function()
{
function yourFunctionName1()
{
//your code here
}
function yourFunctionName2(parameter1, param2)
{
//your code here
}
return
{
yourFunctionName1:yourFunctionName1,
yourFunctionName2:yourFunctionName2
}
})();
$document.ready(function()
{
anyFunctionName.yourFunctionName1();
anyFunctionName.yourFunctionName2();
});
Note: if you don't use 'anyFuctionName' to declare any function then no need return method. just write your function simply like, yourFunctionName1().
in $document.ready section parameter is not issue. you just put your function name here. if you use 'anyFuctionName' function then you have to follow above format.
function myfunc(e) {
alert(e.data.bar); //this is set to "value"
}
$("#foo").click({bar: "value"}, myfunc);
People are making this complicated, simply call directly as you would in Javascript
myfunc("value");
I have a form which is submitted remotely when the various elements change. On a search field in particular I'm using a keyup to detect when the text in the field changes. The problem with this is that when someone types "chicken" then the form is submitted seven times, with only the last one counting.
What would be better is something like this
keyup detected - start waiting (for one second)
another keyup detected - restart waiting time
waiting finishes - get value and submit form
before I go off and code my own version of this (I'm really a backend guy with only a little js, I use jQuery for everything), is there already an existing solution to this? It seems like it would be a common requirement. A jQuery plugin maybe? If not, what's the simplest and best way to code this?
UPDATE - current code added for Dan (below)
Dan - this may be relevant. One of the jQuery plugins I'm using on the page (tablesorter) requires this file - "tablesorter/jquery-latest.js", which, if included, leads to the same error with your code as before:
jQuery("input#search").data("timeout", null) is undefined
http://192.168.0.234/javascripts/main.js?1264084467
Line 11
Maybe there's some sort of conflict between different jQuery definitions? (or something)
$(document).ready(function() {
//initiate the shadowbox player
// Shadowbox.init({
// players: ['html', 'iframe']
// });
});
jQuery(function(){
jQuery('input#search')
.data('timeout', null)
.keyup(function(){
jQuery(this).data('timeout', setTimeout(function(){
var mytext = jQuery('input#search').val();
submitQuizForm();
jQuery('input#search').next().html(mytext);
}, 2000)
)
.keydown(function(){
clearTimeout(jQuery(this).data('timeout'));
});
});
});
function submitQuizForm(){
form = jQuery("#searchQuizzes");
jQuery.ajax({
async:true,
data:jQuery.param(form.serializeArray()),
dataType:'script',
type:'get',
url:'/millionaire/millionaire_quizzes',
success: function(msg){
// $("#chooseQuizMainTable").trigger("update");
}
});
return true;
}
Sorry i haven't tested this and it's a bit off the top of my head, but something along these lines should hopefully do the trick. Change the 2000 to however many milliseconds you need between server posts
<input type="text" id="mytextbox" style="border: 1px solid" />
<span></span>
<script language="javascript" type="text/javascript">
jQuery(function(){
jQuery('#mytextbox')
.data('timeout', null)
.keyup(function(){
clearTimeout(jQuery(this).data('timeout'));
jQuery(this).data('timeout', setTimeout(submitQuizForm, 2000));
});
});
</script>
Here's your fancy jquery extension:
(function($){
$.widget("ui.onDelayedKeyup", {
_init : function() {
var self = this;
$(this.element).keyup(function() {
if(typeof(window['inputTimeout']) != "undefined"){
window.clearTimeout(inputTimeout);
}
var handler = self.options.handler;
window['inputTimeout'] = window.setTimeout(function() {
handler.call(self.element) }, self.options.delay);
});
},
options: {
handler: $.noop(),
delay: 500
}
});
})(jQuery);
Use it like so:
$("input.filterField").onDelayedKeyup({
handler: function() {
if ($.trim($(this).val()).length > 0) {
//reload my data store using the filter string.
}
}
});
Does a half-second delay by default.
As an update, i ended up with this which seems to work well:
function afterDelayedKeyup(selector, action, delay){
jQuery(selector).keyup(function(){
if(typeof(window['inputTimeout']) != "undefined"){
clearTimeout(inputTimeout);
}
inputTimeout = setTimeout(action, delay);
});
}
I then call this from the page in question's document.ready block with
afterDelayedKeyup('input#search',"submitQuizForm()",500)
What would be nice would be to make a new jquery event which uses this logic, eg .delayedKeyup to go alongside .keyup, so i could just say something like this for an individual page's document.ready block.
jQuery('input#search').delayedKeyup(function(){
submitQuizForm();
});
But, i don't know how to customise jquery in this way. That's a nice homework task though.
Nice job, Max, that was very helpful to me! I've made a slight improvement to your function by making it more general:
function afterDelayedEvent(eventtype, selector, action, delay) {
$(selector).bind(eventtype, function() {
if (typeof(window['inputTimeout']) != "undefined") {
clearTimeout(inputTimeout);
}
inputTimeout = setTimeout(action, delay);
});
}
This way you can use it for any type of event, although keyup is probably the most useful here.
I know this is old, but it was one of the first results when I was searching for how to do something like this so I though I would share my solution. I used a combination of the provided answers to get what I needed out of it.
I wanted a custom event that worked just like the existing jQuery events, and it needed to work with keypress + delete, backspace and enter.
Here's my jQuery plugin:
$.fn.typePause = function (dataObject, eventFunc)
{
if(typeof dataObject === 'function')
{
eventFunc = dataObject;
dataObject = {};
}
if(typeof dataObject.milliseconds === 'undefined')
dataObject.milliseconds = 500;
$(this).data('timeout', null)
.keypress(dataObject, function(e)
{
clearTimeout($(this).data('timeout'));
$(this).data('timeout', setTimeout($.proxy(eventFunc, this, e), dataObject.milliseconds));
})
.keyup(dataObject, function(e)
{
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 8 || code == 46 || code == 13)
$(this).triggerHandler('keypress',dataObject);
});
}
I used $.proxy() to preserve the context in the event, though there could be a better way to do this, performance-wise.
To use this plugin, just do:
$('#myElement').typePause(function(e){ /* do stuff */ });
or
$('#myElement').typePause({milliseconds: 500, [other data to pass to event]},function(e){ /* do stuff */ });
I have a big problem writing a small piece of code using JS/jQuery (don't know which of these is causing the problem). Anyhow, here we go:
$('#themePicker').unbind().click(function() {
var t = $(this);
modalwindow2(t, function() {
console.log(1);
}, function(w) {
console.log(w);
});
return false;
});
and the function itself:
function modalwindow2(w, callbackOnSHow, callbackOnHide) {
if (typeof(callbackOnSHow) == 'function') {
callbackOnSHow.call();
}
// do some stuff //
$('form').submit(function() {
ajaxSubmit(function(data) {
if (typeof(callbackOnHide) == 'function') {
console.log('---------------');
console.log(data);
console.log('---------------');
callbackOnHide.call(data);
}
});
return false
});
}
The function is called modalwindow2 and I want to call a function when the modal is shown and another function when the modal will be hidden.
The first is not a problem.
The second… Well… Let's just say it's a problem. Why?
I want a parameter sent to the second function. The paramenter is an ajax response, similar to other jQuery stuff (ajax action, sortable, etc).
I hope I made myself clear enough.
Thanks!
Edit:
I'm using jQuery 1.1.2 (or 1.1.3) and upgrading or using jQuery UI is NOT a solution. I have some dependencies (interface is one of them) and i don't have enough time (nor motivation) to upgrade to 1.3 & UI 1.7.
I noticed that you have a typo on .submit:
$('form').submti(function(){
Was that just an entry error to SO?
EDIT:
Ok, so after looking at your code and doing a short test, I've come up with this (pardon the pun):
function modalwindow2(w, callbackOnShow, callbackOnHide) {
if(typeof callbackOnShow == 'function') {
callbackOnShow.call();
}
$('form').submit(function() {
if(typeof callbackOnHide == 'function') {
callbackOnHide.call(this, "second");
}
});
}
$(document).ready(function (){
$('#themePicker').click(function(){
var t=$(this);
modalwindow2(t, function() { alert("first"); }, function(x) { alert(x); });
return false;
});
});
It looks like you may have just been missing the "this" in your call() statement. Try using callbackOnHide.call(this, data);
Let me know if that works any better!
I understand what you are trying to do, but you will need to store the newly created window so that you can access it on the close callback function.
You might want to look at jQuery UI Dialog. It provides some really basic functionality for dialog windows (modal and otherwise) and handles some of the callback implementation.