my code and my problem is:
<script type="text/javascript">
$(document).ready(function() {
// this variable is used to set the dynamic elements
tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me'; // setting the element which I want to trigger later
});
$('#'+tagFlag).click(function(e) {
// do sthing here
});
});
</script>
</head>
<body>
make the element
<p id="me">some words here</p>
</body>
</html>
but.when I set the tagFlag,and click the "p" nothing is happen.BTW.there is error when tagFlag had been set nothing.So.How can I get what I want?
Thank you very much!!
Maybe you should look at the jQuery live() method that will assign event to all existing and future elements.
http://api.jquery.com/live/
There is no element wit the ID "a1". If you want the first anchor element use
$.("a:eq(0)")
instead.
If that's not it, report back please.
use a jquery object and add the clicked elements to it:
$(document).ready(function() {
$tagFlag = $("");
$("#a1").click(function(event) {
event.preventDefault();
$tagFlag.add($(this));
});
$tagFlag.click(function(e) {
// do sthing here
});
});
You can attach a .click() handler to document and check if the target of the click was the element you cared about, similar to how .live() behaves internally, like this:
$(function() {
var tagFlag = '';
$("#a1").click(function(event) {
event.preventDefault();
tagFlag = 'me';
});
$(document).click(function(e) {
if(tagFlag && //is it even set?
(e.target.id == tagFlag || $(e.target).closest('#'+tagFlag).length)) {
//do work here
}
});
});
You can give it a try here, the only change to your markup is the addition of a child element (to show click bubbling/handling working) and giving the anchor that a1 ID I think you intended for it to have in the question.
Alternatively if you know the set of elements that may be clicked, give them a class and bind a handler to them, checking the ID like I have above...or unbind the class and rebind to the specific ID each time, there's a few ways to go about this :)
Related
how can I target separately elements from a multitude of elements with the same classes or other properties. I cannot add different classes on each element so I need to target each element when I'm working on.
I have tried this so far but it is targeting all elements with input:text because my wrong condition of targeting each separately element working on.
var selector = $('input:radio').prop("checked", true);
var element = $ ('input:text');
$(selector).on('change', function( event ) {
if(this){
$(element).prop('disabled', true);
alert('disable only this element when radio is selected');
}
else{
alert('others input:text not disabled');
$('input:text').prop("disabled", false);
}
})
Fiddle:
By using DOM navigation method, you can do it really easily. Just use this :
var selector = $('input:radio').prop("checked", true);
var element = $ ('input:text');
$(selector).on('change', function( event ) {
var el = $(this).closest('.input-group').find('input:text');
element.prop('disabled', function(){
return !el.is(this);
})
});
Fiddle : http://jsfiddle.net/D2RLR/5874/
For dynamic input, you'll need to use Event delegation (read more here):
//document should be closest static element
$(document).on('change', 'input:radio', function(){
var el = $(this).closest('.input-group').find('input:text');
$('input:text').prop('disabled', function(){
return !el.is(this);
})
})
I don't understand exactly what you're trying to do, but you can use $(this) to target the element that triggered the event instead of trying to use a selector.
I think something like this is what you want:
$(selector).on('change', function( event ) {
$("input:text").prop("disabled", true);
$(this).parent().siblings("input:text").prop("disabled", false);
})
It disables all of the input:text and then enables the one whose radio button was selected.
Try this:
$(selector).on('change', function( event ) {
$('input:text').prop("disabled", false);
$(this).closest('.input-group').find(element).prop('disabled', true);
})
http://jsfiddle.net/D2RLR/5869/
Why not simplify?
Demo Fiddle
$('input:radio').on('change', function (event) {
$('input[type=text]').prop('disabled', false);
$(this).parent().next('input[type=text]').prop('disabled', 'false');
})
As others said, its not exactly clear what you're trying to do, or how general is your question. If the elements matching your selector have exactly the same attributes (including class), you may need to base on the context they are embedded on, or as a last resource, you may be able to base on the order of these elements.
Context: If you're looking for "p.many_like_me" , and you know the element you're trying to match is inside of #parent_id, you just refine your selector as "#parent_id p.many_like_me"
Order: If you know you're looking for the third element on the DOM matching your selector, you can use get() to select it: $("p.many_like_me").get(2) (get takes an index zero-based).
If you need to select them based on an event triggered by a nearby or somehow-related element, then some of the other answers given here are ok.
In jQuery.click() method it's possible to get the class of element which has fired the event using even.target. I want to check if the element which has been clicked or one of its parent has some specific class.
<div class="c1">Click</div>
<script>
$(document).click(function(e){
if($(e.target).hasClass("c1"))
alert("It's C1");
});
</script>
But it always failes because c2 has been clicked. Despite using .parent(), I'm wondering if there is a way to check the propagation on on-click event.
From what you said is C1 was clicked and you want to know if
You need to see if the element is inside that was clicked.
var target = $(e.target);
if (target.hasClass("c2") || target.find(".c2").length) {
alert("C2 is a child");
}
EDIT, now what you orginally asked is not what you really wanted.
Now if it is a parent it is as simple as
var target = $(e.target);
if (target.hasClass("c1") || target.parents(".c1").length) {
alert("C1 child was clicked");
}
or as Ian pointed out
if (target.closest(".c1").length) {
alert("C1 child was clicked");
}
You can use $(this).hasClass instead of $(e.target). Also $(this).parent() will lead to parent of a target
I need to trigger click events of "a" tags which are in "deletable" class. I saw some similar question in SO, but following code doesn't work for me. What i'm trying to do is to delete relevant <li> from <ul>.
$(document).ready(function () {
$('.deletable').live("click", function () {
alert("test"); // Debug
// Code to remove this <li> from <ul>
});
});
<form ...>
<ul>
<li>OneDelete</li>
<li>TwoDelete</li>
<li>ThreeDelete</li>
</ul>
</form>
I assume i'm using incorrect object hierarchy inside $('...') tag. But i don't have enough js/jquery/DOM knowladge to solve this problem. please help.
EDIT
Thanks for the answers, but none of them works for me. Actually i'm adding <li>s dynamically. There maybe a problem. Please check,
#sps - a listbox
#add - a button
#splist - another listbox
#remove - a button
$(document).ready(function() {
$('#add').click(function(e) {
var selectedOpts = $('#sps option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#splist').append($(selectedOpts).clone());
$('ul').append('<li>' + selectedOpts.text() + 'Remove' + '</li>');
e.preventDefault();
});
$('#remove').click(function(e) {
var selectedOpts = $('#splist option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$(selectedOpts).remove();
e.preventDefault();
});
});
The .live() method of jQuery has been deprecated. You can get similar functionality using $('body') and delegating to .deletable like I did in the following code:
$('body').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
The preventDefault method is used to keep the link from loading a new page should there be something targeted in the href attribute. If you keep the same HTML structure as you have in your example, then you can simply take the anchor element (this) and grab the parent, then remove it from the DOM.
It would be wise to, instead of using $('body'), target the container for the .deletable anchors, which, in this case, would be $('ul'). The function would look like this:
$('ul').on('click', '.deletable', function(e){
e.preventDefault();
// this is the li that was clicked
$(this).parent().remove();
});
Using $('body') means that every event on the page would have to be filtered to see if it originated from a .deletable anchor. By scoping it to the ul preceding your li's, you limit the number of times your function is called increasing performance.
Some things first: if you're using jQuery 1.9, the .live() function is not anymore supported. Versions prior, that particular function is deprecated anyway, so you shouldn't really use it.
That being said, your syntax looks about correct. So I'm assuming that it's your hierarchy inside the handler function that's incorrect.
Something like this should work if you're trying to delete the parent <li>:
$('.deletable').on('click', function (e) {
// since you're working with a link, it may be doing wonky default browser stuff
// so disable that for now
e.preventDefault();
// then we delete the parent li here:
$(this).parent('li').remove();
});
If you really want to make that into a delegate signature, something like this should work:
$('form').on('click', '.deletable', function (e) {
// same banana
});
you can use $('a.deletable') selector ... this finds the <a> with class deletable.
u can go through the on delegate events too.. here is the docs
try this
$('a.deletable').on("click",function(){
alert("test"); // Debug
// Code to remove this <li> from <ul>
$(this).parent("li").remove();
});
if in case your <li> is added dynamically..
$(document).on("click",'a.deletable',function(){ .... //even more better if u replace the document with closest elements to a.deletable ..like $(form)
live() is depricated..
$('a.deletable').live("click",function(){
alert("test"); // Debug
$(this).parent('li').remove();
});
I'm working with Prototype on a script to detect all Select Tags under a Div and then add an event/observer on each one!
Here is the code to find the Elements I need:
Event.observe(window, 'load', function() {
var tab=$("product-options-wrapper").descendants();
var attCode=[];
var j=0;
for (i=0;i<tab.length;i++) {
if (tab [i].tagName =="SELECT") {
attCode[j++]=tab[i].id
}
}
});
I have all the Ids I need.
How can I add an observer (on change) for each one?
$(id).on("change", function(event) {
alert(id+"__"+$(id).value);
});
Prototype supports event delegation out of the box. Event.on takes on optional second selector parameter. So in your case:
$("product-options-wrapper").on('click', 'select', function(event, element) {
// This callback will only get fired if you've clicked on a select element that's a descendant of #product-options-wrapper
// 'element' is the item that matched the second selector parameter, in our case, the select.
....
});
That parameter can be any CSS selector string:
$('my-element').on('click', '.some-class', function(event, element) { ... });
Check out Element.select, too. That will condense the code in your original question down to essentially one line:
$("product-options-wrapper").select('select');
This one seems kind of confusing because your selector string is 'select' (you want all SELECT elements under #product-options-wrapper). You could also do:
$$('#product-options-wrapper select');
These both return an array of matched elements.
HTH
You only need a click handler on the div (in other words, use event delegation)
var tab = $("product-options-wrapper");
tab.on('click',function(e){
e = e || event;
if ( /^select$/i.test((e.target || e.srcElement || {}).tagName) ){
//do stuff
}
});
That should do. Please post your html or even better a jsfiddle if you need more help.
$(function(){
$('#product-options-wrapper select').on("change", function(e) {
alert(id+"__"+$(this).val());
});
});
I guess you forgot the . at the beginning of product-options-wrapper to indicate its a class? Or is it really a tag?
I am trying to add an onClick event to an anchor tag ...
Previously i had ...
<a href="somlink.html" onClick="pageTracker._link(this.href); return false;">
But i am trying to avoid the inline onClick event because it interferes with another script..
So using jQuery i am trying the following code ...
<script>
$(document).ready(function() {
$('a#tracked').attr('onClick').click(function() {window.onbeforeunload = null;
pageTracker._link(this.href);
return false;
});
});
</script>
with the html like so <a id="tracked" href="something.html">
So my question is should this be working, and if not what would be the best solution?
The correct way would be (as for jQuery)
$('#tracked').click(function() {
pageTracker._link($(this).attr('href'));
return false;
});
This will add an "onclick" event on any element with tracked id. There you can do anything you want. After the click event happens, the first line will pass href attribute of the clicked element to pageTracker.
As for your original question, it wouldnt work, it will raise undefined error. The attr works a bit different. See documentation . The way you used it, would return the value of the attribute and I think that in that case its not chainable. If you would like to keep it the way you had it, it should look like this:
$('#tracked').click(function() {
$(this).attr('onclick', 'pageTracker._link(this.href); return false;');
return false;
});
You can also try
var element1= document.getElementById("elementId");
and then
element1.setAttribute("onchange","functionNameAlreadyDefinedInYourScript()");
// here i am trying to set the onchange event of element1(a dropdown) to redirect to a function()
I spent some time on this yesterday. It turned out that I needed to include the jQuery on $(window).ready not $(document).ready.
$( window ).ready(function() {
$('#containerDiv a').click(function() {
dataLayer.push({
'event': 'trackEvent',
'gtmCategory': 'importantLinkSimilarProperties',
'gtmAction': 'Click',
'gtmLabel': $(this).attr('href')
});
});
});