I'm using the following JavaScript Control:
http://www.ama3.com/anytime/
How do I get the selected date in the control? So I can pass it to a postback page?
I tried finding it, but I'm just not very good at JavaScript :(
Which function do I have to call?
// Initialization
$(document).ready(function () {
//alert("welcome");
$("#DateTimeDemo").AnyTime_picker(
{ format: "%Y-%m-%d %H:%i: %E",
formatUtcOffset: "%: (%#)",
hideInput: true,
placement: "inline"
});
// Asp.net code
<input type="text" id="DateTimeDemo" style="background-color:Green;" />
I assume the code will be something like this:
var x = getBlaBla();
Where x is something that I can use to pass to C# for postback info. I think I'll have to use JQuery to select the object I'll be taking the date out of.
Edit:
Okay I think I have to use something like this:
$("#DateTimeDemo").AnyTime_current(g, k);
what do the g and the k stand for? What do I have to pass?
As Joe Johnson earlier commented, you will likely want to attach an event handler. With this method, whenever your input changes within the DateTimeDemo field, you can do something with that value.
$(function() {
$("#DateTimeDemo").change(function() {
var dt = $("#DateTimeDemo").val();
alert(dt);
// do something with dt.
});
});
I think I'll have to use JQuery to select the object
You never "have" to use jQuery, or any library. You can add an in–line listener like:
<select ... onchange="someFunc(this.value);" ...>
Where the logic for adding the listener is on the server, so no different to adding it at the client (but faster and more robust than any client–side method).
Or add it as a DOM property sometime after the element is created in the document (use the load event or a script at the bottom of the page):
document.getElementById('selectID').onchange = function(){someFunc(this.value);};
Or use addEventListener:
document.getElementById('selectID').addEventListener('change', function(){...}, false);
but include support for other browsers too (e.g. an addEvent function).
Related
I got a jQuery function that catches changes on a input field and add it to a variable.
The input field is also held up on a vanilla js based API lib, that I cant convert to jQuery.
The lib is an address API, so people can select a address, and that wont trigger my jQuery function. I therefore thought of a workaround, where my jQuery is watching my vanilla js, to see when it's fired, and fire my jQuery function right after.
My jQuery function:
$('#billing_address_1').on('input',function(e){
let addressValue = $('#billing_address_1').val();
});
My vanilla js function:
"use strict"
dawaAutocomplete.dawaAutocomplete( document.getElementById("billing_address_1"), {
select: function(selected) {
document.getElementById("valgtadresse").innerHTML = selected.tekst;
}
});
All solutions I've been able to search for, has been requiring that I use .trigger() on my vanilla js in this case. They've not been made for the mix of these two js alternatives. Can I do it in a more proper way?
If you don't want to touch your fields with trigger you can try event emitter pattern which is quite popular in node. Here you keep an object as notifier on which you call event and also hook listeners for that event. It is basically a Pub-Sub pattern a simple implementation of which in vanilla javascript is available over here by mudge or you might also try any alternatives if you find
// KEEP THIS SOMEWHERE IN OUTER SCOPE
let bird = new EventEmitter()
//THEN - hook on any event you name it
bird.on('tweet', (val)=>{
console.log(val)
addressValue = val
})
//THEN - emit that named event wherever you might need
dawaAutocomplete.dawaAutocomplete( document.getElementById("billing_address_1"), {
select: function(selected) {
document.getElementById("valgtadresse").innerHTML = selected.tekst;
bird.emit('tweet', selected.tekst);
}
});
I am trying to write an auto complete jQuery plugin.
The desired usage:
$('.advancedSelect').advancedSelect({/*plugin options*/}).change(function(){})/*.otherJQueryMethods*/;
The implementation:
$.fn.advancedSelect = function({
return this.each(function(){
var $advSel = $('<input/>');
var $el = $(this).after($advSel).hide();
/* my codes on desired functionalities */
/* how is it possible to trigger the chained change method */
});
});
In a comment on my soon-to-be-deleted answer (as it answered a question other than your real question, as it turns out), you've said:
I was wondering whether we could have a syntax like this:
$('.advancedSelect').advancedSelect({/*plugin options*/}).onChange(function(){}).css({})
-and by .css I meant any other jQuery's methods.
I would suggest either this:
$('.advancedSelect').advancedSelect({/*other plugin options*/, onChange: function(){}}).css({})
or this:
$('.advancedSelect').advancedSelect({/*plugin options*/}).advancedSelect("onChange", function(){}).css({})
... with a fairly strong preference for the first one. :-)
Re that first option, an adjunct you see a lot is an optional "options" method you can use later to change options::
// Initial setup
$('.advancedSelect').advancedSelect({/*other plugin options*/, onChange: function(){}}).css({})
// Later, I need to change something
$('.advancedSelect').advancedSelect("options", { onChange: function(){}});
Side note: If this change-like method is to register a change handler, why not just use jQuery's change (or on with some plugin-specific event name) and have your plugin raise an event? That's how I would handle any kind of event-related thing in a plugin. Look at bootstrap's use of shown.bs.modal and such, for instance.
I'm working with a 3rd party product where I am extending the UI with my own custom functionality. Within part of that I need to call an event after the UI has been updated with an AJAX call. Luckily the app fires a call to a Custom Event using the Prototype JS library after the call is complete, like this:
$(document.body).fire("ns:customevent");
If I add my own custom event with the same name then this works as expected
$(document).observe("ns:customevent", function(event) {
//do custom stuff here
});
[I could not get $(document.body).observe() to work here but I don't think that really matters.]
My concern here is that there may be other parts of the app that have registered functions against that event, and I am (blindly) overwriting them with my own, which will lead to issues further down the line.
Does Prototype append custom functions even though they have the same name or does it in fact overwrite them? If it does overwrite them then how can I append my function to anything that is already existing? Is there anyway of viewing what
I would imagine something like this, but I hardly know Protoype and my JS is very rusty these days.
var ExistingCustomEvent = $(document.body).Events["ns:customevent"];
$(document).observe("ns:customevent", function(event) {
ExistingCustomEvent();
//do custom stuff here
});
I can't add my event handler or add in code to call my own function, I want to try avoiding the 3rd party library (if that would even be possible).
Thanks.
As an FYI for anyone else that stumbles upon this question, following the comment from Pointy it turns out that Prototype does append the functions to the custom event.
I verified this by trying the following and both alerts fired.
$(document).observe("ns:customevent", function(event) {
alert("ALERT 1");
});
$(document).observe("ns:customevent", function(event) {
alert("ALERT 2");
});
Great :)
I'm trying to write a plugin that will select multiple elements and then apply some private methods to them (see code below). Then I also want to give the user the ability to trigger the activation of the plugin's methods manually with a .activate() function.
Here is my code :
MARKUP : https://github.com/simonwalsh/jquery.imagepox/blob/master/demo/index.html
JS : https://github.com/simonwalsh/jquery.imagepox/blob/master/dist/jquery.imagepox.js
Basically, when I select multiple items and then try to use the manual activation like so :
$(".pox-wrapper").imagepox({ // NOTE: selects two elements
manualActivation: true
});
var manual = $(".pox-wrapper").data('imagepox');
setTimeout(function(){
manual.activate();
}, 5000);
It will only apply the activate() method to the first element in the query...
This is my first jQuery plugin and I've been able to handle everything so far but I'm not sure about this one or even if it is the right way to effectively call a public method. I also tried using a custom event with an event listener in the plugin but it still only applies the methods on the first element in the page.
Thanks in advance :)
its not your plugin's fault. data does not work like that, it doesnt know how to return data from a collection of elements. Because think about it, each element in the collection contains its own data object!
So when you call data on a collection, it returns the data from the first one. The quick solution would be to change the innards of the setTimeout into a loop over all the elements in the set and call activate on them.
setTimeout(function(){
$(".pox-wrapper").each(function(){
$(this).data('imagepox').activate();
})
}, 5000);
It seems to me that you want to add functions to collections of jquery objects. This is the usecase of a jquery plugin. You can create a lightweight one like this:
$.fn.imagepox.activate = function(){ //do this after you create your plugin!
return this.each(function(){
var $this = $(this);
var data = $this.data('imagepox');
if(data){
data.activate();
}
});
};
now you can call it like this:
$(".pox-wrapper").imagepox.activate()
I'm trying to execute JavaScript functions that are called when a event (for example onClick event) is performed on a web page with JavaScript code. I'm getting the function from the event like this :
var attributval = document.getElementsByTagName("a").getAttribute('onClick');
and I'm trying to execute this object (which a JavaScript function in fact) as a function (suppose we have <a onClick = alert('whatever');> on this example, I tried:
var attributval = document.getElementsByTagName("a").getAttribute('onClick');
attributval() = function(){attributval};
attributval();
but it didn't work.
A DOM attribute is not the same as a JavaScript property (even though they can have the same name onclick). You should use
var attributval = document.getElementsByTagName("a")[0].onclick;
to retrieve a function (or null) from the JS object (as opposed to getAttribute(), which will most likely return a toString() for the property).
Now, attributval() = is illegal syntax, as attributval() is not an l-value (you cannot assign to it).
attributval(); will work but without the second line (which is illegal JavaScript) it will invoke the original A element onclick handler (if one is defined) or throw an exception (if the onclick handler is null).
Skip trying to create a function around the function. Just call it:
var attributval = document.getElementsByTagName("a")[0].onclick;
attributval();
try
var attributval = document.getElementsByTagName("a")[0].getAttribute('onClick');
By using get attribute you are returning a string so your only way is to use eval(onclickString) or var fn = new Function(onClickString); fn();
attributval is simply a string, correct? If you trust this code, execute it with eval(attributval) -- however any reference to this won't work.
What you probably want is to manually trigger an event. jQuery makes that easy.
If you want to do more than a click, then Chris McDonald's answer at Is it possible to trigger a link's (or any element's) click event through JavaScript? seems to fit the bill, although you might need to heed the third comment.
I thought I'd add a short answer on how to work with events using jQuery, since it seems relevant.
// Select the link using it's ID field (assuming it has one)
var myLink = $('a#myLink')
// Add a click event to the link
myLink.on('click', function(e) {
console.log("I've been clicked!");
});
// Trigger the click event manually. This would result in the above
// function being run. Interestingly, this will not cause the browser
// to follow the link like a real click would
myLink.trigger('click');
// Remove the click event (this removes ALL click events)
myLink.off('click');
// Add a click event to the link that only runs once, then removes itself
myLink.one('click', function() {
alert("I'll only bother you once!");
});
// Add a click event that you can identify from other click events.
// This means that you can trigger it or remove it without bothering other
// click events
myLink.on('click.myClick', function() {
alert("This click event has been identified as 'myClick'");
});
// Now you can trigger it without triggering other click events
myLink.trigger('click.myClick');
// And remove it, also with no harm coming to other click events
myLink.off('click.myClick');
Hope this helps