I need to access to the custom attribute or data of my link but I can't. My code is simple yet in repeater. I don't know if this is causing a problem. Here is the code:
<a class="showAllComm" data-userid='<%# DataBinder.Eval(Container.DataItem, "USER_ID")%>' href="#sa">Show all comments</a>
Here is my click event:
$('.showAllComm').click(function(index, element) {
var commId = $(element).data("userid");
})
commId is undefined but I can see it in the source code that it has value of 1.
how can I access to the userId?
Thank you
Reference the element with this instead of the second parameter:
var commId = $(this).data("userid");
The arguments passed to an event handler are not the index and element as you'd have in .each().
By default, you just get a single event argument passed.
DEMO: http://jsfiddle.net/Jjbwd/
$('.showAllComm').click(function( event ) {
alert( event.type ) // click
var commId = $(this).data("userid");
});
The data method is not a shortcut for the attr method. It takes an element and an attribute, per the docs
Just use attr("data-userid")
Related
I have a function as follows:
$("#submitBtn").on('click', function () {
....
});
I am using the following in invoke the click it in a portion of code by doing:
$('#submitBtn').click();
Is there a way to set a input parameter to the click.
For example, I need to pass a string value to the click so that the function can take appropriate steps. Note that the value of p is not from any element from the page. It is something I will be pro-grammatically setting based on some conditions.
var p = 'sourceinfo';
$('#submitBtn').click(p);
Alright, the best way to do this is by adding custom data-attribute params to the element before chaining it with the click event:
$("#submitBtn").data("params", {
one: "Parameter 1",
two: "Parameter 2"
}).click();
And you can use params like this:
$("#submitBtn").on('click', function () {
// Parameter 1
alert( $(this).data("params").one );
// Parameter 2
alert( $(this).data("params").two );
// Do other stuff
});
Check working demo
You can use the event handler .trigger() instead of .click()
Syntax :
.trigger( eventType [, extraParameters ] )
Example:
.trigger('click',[param1,param2])
After that you can get those params from your call back function after event param
Click is a event generated and cannot pass the message/data. Instead you can pass the args to the listener(calling method).so that it can be captured to that method.
for e.g
<button onclick="handleClick('msg',event)"></button>
You can use .trigger() instead.
$('#submitBtn').trigger('click', [arg1, ...]);
You can retrieve the parameters passed when attaching the click handler
$('#submitBtn').on('click', function(e, arg1, ...) {
});
You can you jQuery(this).attr('action') ... Inside the function
And on the element add attribute as follow data-action('myaction')
I am trying to pass the argument to the JQuery event handler when a button is being clicked. In plain JavaScript i was using onclick="function(argument)"
Now i am transferring all of my inline click events to external call like one with Jquery i.e
$(".selector").click(function(){
//some code
});
However, in this case i am confused how i can pass the arguments from the HTML tag and how should i receive the arguments in the Jquery event handler.
Please help.
An optional object of data passed to an event method when the current executing handler is bound.
In your case it will be something like this -
$(".selector").on("click", function(event){
//you can access the parameter value as follows
console.log(event.target.value);
});
Refer the official documentation here Pass arguments from a button click to Jquery event handler
The .click() function receives an EventData object that gets passed as the first argument to the handler, you can use that object inside the handler.
For example:
$('.selector').click(function(data) {
$(data).addClass('newClass');
});
If you are trying to pass data from the HTML the cleanest way might be to store that data into the data attribute of your tag.
The HTML
<div id="mydiv" data-arg="Hello world!">Click me</div>
The JS
$('#mydiv').click(function(data) {
var arg = $(data).attr('data-arg');
console.log(arg);
});
For what you are trying to achieve
The HTML
<button id="dark" data-stroke-width="0.5"
class="txtcolor uk-button" type="button">1px</button>
The JS
$('button#dark').click(function(data) {
selectStroke($(data).attr('data-stroke-width'));
});
Check the documentation for click
A sample:
// say your selector and click handler looks something like this...
$("some selector").click({param1: "Hello", param2: "World"}, cool_function);
// in your function, just grab the event object and go crazy...
function cool_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
var param_obj = {data : {param1: "Hello", param2: "World"}};
cool_function(param_obj);
$("dark").click({param1: 0.5}, selectStroke);
or
var i = 0.5;
$("dark").click({param1: i}, selectStroke);
or if you do not want change functionality of the handler
var i = 0.5;
$("dark").click({param1: i}, function() {
selectStroke(event.data.param1);
);
I am creating a function which will take in a URL and then display that URL in a light box. I am having trouble with event.preventDefault() in my function though, it says it is not a function in the error console.
I have tried explicitly passing event to the function but that simply runs the function on page load rather than when clicking
Here is my code:
// Function to display widget
function displaySportsWidget(event, iframeURL) {
// Prevent Default Event Handler
event.preventDefault();
// Build iFrame HTML
var iframe = '<iframe src="' + iframeURL + '" ></iframe>';
var html = iframe;
// Inject HTML to Generate Widget
$('.leagues-wrapper').html(html);
// Display Overlay
$('.leagues-overlay').css('display', 'block');
};
// Event handlers. Pass iFrame URL into function depending on link clicked
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
$('.leagues-link.league-form').on('click', displaySportsWidget( 'http://www.example02.com'));
The code
$('.leagues-link.league-table').on('click', displaySportsWidget('http://www.example01.com'));
calls displaySportsWidget and passes its return value into on, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to hook up an event handler, you don't call it, you just refer to it. In your case, you can do that like this:
$('.leagues-link.league-table').on('click', function(e) {
displaySportsWidget(e, 'http://www.example01.com');
});
Or if you're open to changing the order of arguments in displaySportsWidget:
function displaySportsWidget(iFrameURL, event) {
// ...
}
...then you can use Function#bind:
$('.leagues-link.league-table').on('click', displaySportsWidget.bind(null, 'http://www.example01.com'));
Function#bind creates a new function that, when called, calls the original function with a given this value (in our case, we don't need any specific one, so I'm passing null) and any arguments you gave bind, followed by any arguments that were given to the bound function. So we'll get the URL (from the bind call) followed by the event object (from when the handler is called).
Function#bind isn't on really old browsers like IE8. If you need to support them, jQuery's $.proxy does something similar:
$('.leagues-link.league-table').on('click', $.proxy(displaySportsWidget, null, 'http://www.example01.com'));
While calling your method you are not passing event as parameter along with image url .so if u pass event as parameter while calling.then your code is going to work.
Thank you
I can't seem to access the variable defaultValue down in my .blur() function. I've tried various stuff but with no luck. So far I only get an empty object. What's wrong?
jQuery(document).ready(function(){
jQuery('#nameInput, #emailInput, #webInput').focus(function(){
var defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(defaultValue){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
Looks like the question is about the passing data into the .blur or .focus event.
per jQuery API - http://api.jquery.com/blur/
blur( [eventData ], handler(eventObject) )
So if you want to pass data - you can send a parameter to event - which will appear as data in event object.
see this fiddle for more info
http://jsfiddle.net/dekajp/CgP2X/1/
var p = {
mydata:'my data'
};
/* p could be element or whatever */
$("#tb2").blur(p,function (e){
alert('data :'+e.data.mydata);
});
Because your code is wrong :-) you define var inside function (var defaultValue) which is then immediately wiped out.
There are two solutions: define your var as a global var before you bind blur event, or store it in the data of object liket his (which I recommend):
$(document).ready(function(){
$('#nameInput, #emailInput, #webInput').focus(function(){
$(this).val("").data('defaultValue',jQuery(this).val());
}).blur(function(defaultValue){
if($(this).val() == ""){
$(this).val($(this).data('defaultValue'));
}
});
});
It seems to me that you don't understand the basics of JavaScript.
First of all variables in JS are localized to function's scope, so you can't declare variable with var in one function and access it in other function
Second, you can't pass anything to DOM-event handler, except event-object, this is defined by the DOM specification, sometimes you can use event data parameter to the blur jQuery method.
Try this:
jQuery(document).ready(function(){
var defaultValue;
jQuery("#nameInput, #emailInput, #webInput").focus(function(){
defaultValue = jQuery(this).val();
jQuery(this).val("");
})
.blur(function(){
if(jQuery(this).val() == ""){
jQuery(this).val(defaultValue);
}
});
});
First of all, you need to distinguish blur method (function) and handler (function) which is the argument to the blur. You was trying to pass the defaultValue exactly to handler, but that can't be done. Inside handler the defaultValue would be equal eventObject, so you can do smth like console.log(defaultValue.timeStamp) and you'll see smth like 123482359734536
In your approach you can't even use event.data argument to the blur cause it will be set at the time of blur's call (attaching handler). You need to declare a var outside of the both handlers, so it will be visible to both of them
You may consider to read some comprehensive book on JS.
I read "Professional JaveScript For Webdevelopers" by Nicolas Zakas. There is a new edition
I have this JavaScript function :
function putVote(trackid, vote) {
}
and I call this function trought :
Link
I would like to use e.preventDefault(); on putVote(), but I think I'm wrong in some ways. How can I do it?
Cheers
The simplest thing to do would be to return false from the function in the handler (return false would only work in putVote if the handler had return putVote('data1', 'data2)).
But as Pointy said, a much better technique is to attach the event handler from JavaScript, most easily achieved by using a library/framework such as jQuery or Prototype.
The easiest way:
Link
If you're using jQuery.
JS:
$("#link").click(function(evt) {
evt.preventDefault();
putVote('data1', 'data2');
});
HTML:
Link
If you're using the latest version of jQuery and the HTML5 doctype.
JS:
$("#link").click(function(evt) {
evt.preventDefault();
var $self = $(this);
putVote($self.data("one"), $self.data("two"));
});
HTML:
Link
In your case, the trick with using jQuery-style binding is that you want to be able to pass through element-specific parameters to the handler ("data1", "data2"). The "modern" way to do that would be this:
<a href="#" class='data-clickable' data-click-params='["data1", "data2"]'>Link</a>
Then, in a "ready" handler (or some other appropriate place), you'd bind your handler:
$('a.data-clickable').click(function(e) {
var elementData = $(this).data('click-params');
//
// ... handle the click ...
//
e.preventDefault();
});
The "elementData" variable will end up (in this case, anyway) being an array with two values in it, "data1" and "data2". You can give JSON-notation values to "data-foo" attributes, and when you fetch the attributes with the jQuery ".data()" method it will automatically decode the JSON for you.