How to get the jQuery `$(this)` id? - javascript

How can I get the id of the element that triggered the jQuery .change() function?
The function itself works properly, but I need a specific action for a selector with id="next".
$("select").change(function() {
[...snip....]
alert( $(this).attr('id') ); // <---- not working
}
Any ideas why the alert above isn't working?

this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
Live example
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
Live example
(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)

Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});

Related

javascript click event not firing action

On page load, I have a search box that, once used, populates a div with multiple images. The javascript from the search uses this function to append all images into the div
function appendSomeItems(url, id, name, style) {
return '<div><div class="md-card md-card-hover"> <div id="getImage" class="gallery_grid_item md-card-content"> <img class ="uk-align-center imageClick"></a> <div class="gallery_grid_image_caption"> <span class="gallery_image_title uk-text-truncate">' + name + '</span> <span>' + style + '</span> </div></div></div></div>';
}
This works perfectly. Now I'm trying to make it so that when I click any one of the images it triggers an action (in this case a console log)
$('.imageClick').click(function handleImage() {
console.log(good);
});
However, it does nothing. No error but no console log.
What am I doing wrong here?
You need to use event-delegation in order to bind an event to dynamically created elements:
This approach uses document as the parent element, however, a good practice is to use the closest parent element.
$(document).on('click', '.imageClick', function handleImage() {
console.log(good);
});
Try with .on() to attach event on dynamically created element. This will allow attaching the event to the elements that are added to the body at a later time:
$('body').on('click', '.imageClick' function handleImage() {
console.log(good);
});
The problem is that you are calling $(".imageClick").click() before you dynamically create the items.
This means that jQuery doesn't actually bind the click listener to the items, since when $(".imageClick").click() is run, the elements don't actually exist yet.
Try this:
$("body").on("click", ".imageClick", function handleImage() {
console.log("good");
});
Also see this post for more information: In jQuery, how to attach events to dynamic html elements?

Jquery how to trigger click on an element that gains focus

I am working with caph framework and i trying to click in every id focused
$(event.currentTarget).on('selected',function() {
var value = $(this).prop('id');
$('#' + $(this).prop('id')).trigger('click');
});
You can access the event target with $(this) in jQuery. To automatically click on the selected element you could do
$(event.currentTarget).on('select', function() {
$(this).click()
// or $(this).trigger('click')
};
If I understand your question right though you're asking how to click every element with a given ID - please note that you should be using classes for this, as IDs are supposed to be unique. You could achieve that with the following:
$(event.currentTarget).on('select', function() {
$('.yourClassName').click()
};
This will click on every element with the given class.

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

How to get HTML element from event in jquery?

In a jQuery function I am getting event on form's element click event. Now I want to get its html. How it is possible ?
For Example:
function(event, ID, fileObj, response, data) {
alert( $(event.target) ); // output: [object Object]
alert( event.target ); // output: [object HTMLInputElement]
alert( $(event.target).html() ); // output: (nothing)
}
I want to get form object who's element is clicked through event
Thanks
You can try event.target.outerHTML, however I'm not sure how well supported it is across all browsers. A more convoluted but sure to work solution would be to wrap the element in another element, then take the html of the parent element:
$('<div/>').html($(event.target).clone()).html();
If your event is a click you can bind it using the click() method from jQuery. Use this to reach your element, like the code below:
$('#id').click(function(event){
console.log($(this));
});
Most elegant solution I found is to simply use the properties on the event target.
Here is an example how to detect the event source html tag.
This example assumes you have bound a list item click event of unordered list with CSS class name myUnorderedList but you want to disable the default action if an anchor tag is clicked within the list item:
$('ul.myUnorderedList').on('click', 'li', function(event){
console.log('tagName: '+ event.target.tagName); //output: "a"
console.log('localName: '+ event.target.localName);//output: "a"
console.log('nodeName: '+ event.target.nodeName); //output: "A"
if(event.target.tagName == 'a')
return; // don't do anything...
// your code if hyperlink is not clicked
});

jquery created select, and triggering on change

I cannot seem to get this to work. I am using jquery to create an html select, and I want some code to execute when its value changes.
code follows:
<script type ="text/javascript">
var firstweddingturn = '400';
$('#weddingturn').change(function() {
alert ("Wedding select change triggered!");
//var wedturn = $('#weddingturnselectid').val();
//$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')
});
$(document).ready(function() {
var html = [];
html[html.length] = '<select name="weddingturn" id="weddingturn">';
var a = firstweddingturn;
var b = Number(firstweddingturn) + 16;
while (a < b) {
// do some code
html[html.length] = '<option name="asdf" value = "1">' + a + '</option>';
a++;
} // end while
html[html.length] = '</select>';
$('#div1').append(html.join(''));
});
</script>
What am I doing wrong?
You need to use .delegate() (or .live()) since you are adding the select dynamically. When you attach an onChange handler with .change() it is only attached to existing matching elements, not elements which are added later on. To attach an event to all matching elements including those added to the page later, you use the .delegate() function, like this:
$('body').delegate('#weddingturn','change', function(){
alert('Wedding select changed to ' + $(this).find('option:selected').val() );
});
However, as some people point out, you can merely attach the event handler immediately after adding the <select> to the DOM. That way, you can still use .change() and your code should run faster.
Include this:
$('#weddingturn').live('change', function() {
alert ("Wedding select change triggered!");
//var wedturn = $('#weddingturnselectid').val();
//$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')
});
in your $(document).ready
And change it to use live
When the .change() event is bound, the element does not exist yet. You have 2 choices:
Bind the event after you create the element (the simplest and recommended option)
Use .delegate() (or .live()) to tell jQuery to bind the event to any element matching the selector whenever it is added to the DOM. If you choose this option, delegate() is the preferred method if you are using a recent version of jQuery > 1.4.2 since it is more performant than live().
You'll need to bind using live, since it is loaded post-DOM load:
$("#weddingturn").live("change", function() {
});
Also, I would place this within scope of $(document).ready, preferably after the code which loads it (just for the sake of logical linearity.)
You're hooking up the event handler BEFORE you've created the element.
(you can use .live() or you can just swap the order of operations)
your are dynamically adding the select to the DOM, at the time of declaration of your event handler the select doest not exists so the event handler doesn't get binded to the element use .live to attach the event handler to dynamically added element
$('#weddingturn').live('change',function() {
alert ("Wedding select change triggered!");
//var wedturn = $('#weddingturnselectid').val();
//$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')
});
DEMO
jquery live
You are setting the change function on a select that does not yet exist. Move that .change call to after the .append

Categories

Resources