I am trying to use jQuery to select all the elements within the .html() functions and run a message on click. However this is not working, does anyone here know why?
function load_tweets(user) {
var $body = $('body');
while(index >= 0){
var $tweet = $('<div class="tweet"></div>');
$tweet.html("<span class='tweetText'>"+tweet.created_at + ' #' + tweet.user + ': ' + tweet.message+"</span>");
$tweet.appendTo($body);
index -= 1;
}
}
$("a[href='#']").click(function() {
alert($(this).attr("class"));
});
You're trying to find the elements BEFORE you insert them. You have to put your $("a[href='#']") code AFTER you insert your elements.
Or just use this instead. $("body").on("click", "a[href='#']", function() {
Related
I am doing an attach files project where I need to auto check a file name when there is only one file to be chosen to attach. It is easy to auto check it as a checkbox, but when it is checked, there is an onclick function called to update the file in the server side.
Since the <input> tag is dynamically added based on the number of required attaching files, .trigger('click') didn't work on it.
$.each(speedLetterArray, function (key, value) {
var idLine = fileId + '_b' + value.reasonCode;
var idContainer = 'sliC_f' + idLine;
var idItem = 'sli_f' + idLine;
output.push('<div style="' + cssDisplay + '" class="sliContainer" id="' + idContainer + '">');
//auto checked if only one item
if (fileCount == speedLetterArray.length) {
value.isSelected = 'true';
}
if (value.isSelected == 'true') {
output.push('<input id="' + idItem + '" onclick="updateSpeedLetterItemLists(this);" type="checkbox" name="' + idItem + '" value="' + value.reasonCode + '" class="testClass" style="margin:0px;" />');
} else {
//some code here
}
}
I used checked=checked to auto check the file, but couldn't trigger the onclick function updateSpeedLetterItemLists(this) to update the files on server side.
which works fine when I manually click it.
I tried $(.sliContainer).find('input:checkbox:first').trigger('click'); after the <input> tag or in $(document).ready, either of them works.
I thought maybe I didn't find the right object since when I use alert($(.sliContainer).find('input:checkbox:first').val()) I get "undefined" value.
You could do
$('yourelemtid').click()
Or since it is dynamically added
$( "yourelemtid" ).live( "click", function() {
});
Since the element is added after the initial javascript initialization it won't see your new elements to add the hooks onto.
jQuery Doc for .live
.live is deprecated, use this:
$(document).on( "click", "#yourelemtid", function() {
...
});
in my jsFiddle example can you see that I made a button where I add some elements and links to delete this elements. In this example it is not about going to delete the elements, but to hover the (remove)link made by clicking the button so it highlights the element with the same "number" attribute.
I have tried to use live(); and on(); for it, but it does not do anything, because the items are made after building the page.
I prefer to use on(); now because jQuery says:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live().
My jQuery code:
function numbers() {
return $('#links span').length;
}
$('#add').on('click', function () {
$('#links').append('<span number="' + (numbers() + 1) + '">Remove element ' + (numbers() + 1) + '</span><br />');
$('#elements').append('<div number="' + numbers() + '" class="element">Element ' + numbers() + '</div>');
});
$('#links span').live('hover', function () {
var number = $(this).attr('number');
if ($('#elements .element').attr('number') == number) {
$(this).addClass('highlight');
}
});
First of all, you should dynamically bind the events, since the elements are added dynamically. Second of all, you should make use of mouseenter and mouseleave events, since you want to toggle the highlighting and need to know when the cursor is leaving the element. And third of all I recommend using data--attributes instead of a custom attribute called number.
function numbers() {
return $("#links span").length;
}
$("#add").on("click", function () {
var number = numbers() + 1;
$("#links").append("<span data-number='" + number + "'>Remove element " + number + "</span><br />");
$("#elements").append("<div data-number='" + number + "' class='element'>Element " + number + "</div>");
});
// Dynamically bind mouseenter and mouseleave events, so they also apply to dynamically added elements
$("body").on("mouseenter", "#links span", function () {
var number = $(this).data("number");
$(".element[data-number='" + number + "']").addClass("highlight");
}).on("mouseleave", "#links span", function () {
var number = $(this).data("number");
$(".element[data-number='" + number + "']").removeClass("highlight");
});
FIDDLE
I have this javascript function and i qould to create a jquery selector, which was build from js function parameter value:
function myJSFunction(elementId){
var showSomeData= {
'value_1': 'abc',
'value_2': 'xyz'
};
var selector = "[name=" + elementId + "] option";
jQuery("'" + selector + "'").each(function() {
$(this).attr('title', showSomeData[$(this).val()]);
});
};
But this kind of code doesn´t work. If i set the concrete value, which i can see in the html dom by using firebug, this code works fine. What was my mistake?
Instead of using $("'" + selector + "'") use $(selector) and your issue is solved.
As stated in comments, you don't need "'" again to find the elements, use directly : jQuery(selector):
var selector = "[name=" + elementId + "] option";
jQuery(selector).each(function() {
$(this).attr('title', showSomeData[$(this).val()]);
});
remove Quotes
var selector = "[name=" + elementId + "] option";
$(selector).each(function(i,val) {
});
Demo
I have two selects that both have use a function to add elements to the other select.
Here's what I have:
$("#lecturers option").dblclick(function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
and vice versa:
http://jsfiddle.net/VJAJB/
It somehow only works once, and the newly added elements don't trigger the function.
Any idea on how to fix this?
The issue is how you bind the dblclick function to the elements. The current selector only returns the option elements you have in your select element at the time of binding. To alter this, you can use delegated events.
$('#lecturers').on('dblclick', 'option', function() {
//Do stuff here
});
This makes sure that any option element you add to the select element will trigger this event when it is double clicked.
Here is an updated fiddle: http://jsfiddle.net/VJAJB/4/
Please note that other users have given you solutions that will work. However, best practice is to limit the number of events bound to the document itself. Whenever possible, you should bind delegated event listeners to the nearest non changing element.
This happens because the handler doesn't get bound to the new elements. You can do it like this, which will bind it to a descendant (in this case body) and specify the selector it will be applied to:
$('body').on('dblclick', '#lecturers option', function ()
{
var element = $("#lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#selected_lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
$('body').on('dblclick', '#selected_lecturers option', function ()
{
var element = $("#selected_lecturers option:selected");
var value = element.val();
element.remove();
var values = value.split(";")
$("#lecturers").append('<option value="' + value + '">' + values[2] + ', ' + values[1] + '</option>');
});
If both have a parent/descendant element that is present at the time of binding, you can use that instead of 'body' to improve performance.
Fiddle: http://jsfiddle.net/VJAJB/2/
You need to use on method instead. In latest jQuery versions is:
$( document ).on( "dblclick", "#lecturers option", function ()
Updated jsFiddle
Some code of mine uses jquery to create elements <a> with a function given for click behavior:
$(alternatives).each(function (idx, elt) {
var element = $('<span class="label label-success">');
var link = $('<a class="prop' + idx + '" title="' + elt + '">' + elt + '</a>');
link.click(switchLabel);
element.append(link);
list.append(element);
});
The idea here is to catch the click event on the <a class="prop1-0" title="myTitle">my link</a> to change the text in a <span id="corr1-0">my old text</span>. The link between both element is made by the class suffix, f.i. 1-0.
I have several pairs <a>/<span>, I checked every id.
Some links work, but some do not: no error in console, nothing to trace with firebug...
The function binded is :
function switchLabel(e) {
$('#corr'+ e.target.className.substr(4)).text($(e.target).attr('title'));
}
Do you have some tips to help me track this unwanted behavior?
May I make a mistake in the implementation?
Regards
Your variables don't match, you are using index and not idx etc. and there are easier ways to create elements and event handlers ?
$.each(alternatives, function (idx, elt) {
var element = $('<span />', {'class' : 'label label-success',
id : 'corr'+idx
}
),
link = $('<a />' {id : 'prop' + idx,
title : elt,
text : elt
}
);
link.on('click', function() {
$('#' + this.id.replace('prop','corr')).text(this.title);
});
list.append( element.append(link) );
});