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() {
...
});
I am trying for hours now:
I want to have a dynamically generated list which has split buttons to the right. These buttons should fire an onClick-Event like every button does. The problem is that an click on these buttons fires the onClick event of the listview, which should do something else.
Clicking on the item approves it and the split-button deletes the entry for example.
Is this possible? I couldn't find any tutorials or advices in the docs..
Here is a DEMO
When adding the dynamic list items, apply identifying classes to the 2 anchors. In this example, the main anchor is mainLink and the split button is deleteItem. Then setup click handlers for the 2 classes uses event delegation ($(document).on("click", ".mainLink", ... so that dynamically added items will be handled:
$(document).on("pagecreate", "#page1", function () {
var dynamicItems = '';
for (var i = 0; i < 5; i++) {
dynamicItems += '<li data-itemid=' + i + '><h2>ITEM' + i + '</h2><p>Description</p><a class="deleteItem" href="#">';
}
$("#thelist").empty().append(dynamicItems).listview("refresh");
$(document).on("click", ".mainLink", function () {
alert("Approve " + $(this).parents("li").data("itemid"))
});
$(document).on("click", ".deleteItem", function () {
alert("Delete " + $(this).parents("li").data("itemid"))
});
});
I've made a constructor in my script that formats <div>s so they can be created and destroyed on the fly.
Here's the function:
function formatDiv(target,divId,divClass,content,onclick)
{
$("#"+target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\' onclick=\'" + onclick + "\'>" + content +"</div>");
}
What I've been trying to do with this is pass in a function call as a string from an array, like "Main()" for main menu, and assigning it to the <div>'s onclick="" property. This worked fine prior to upgrading my code with jquery, but now when I click on <div>, the console returns: ReferenceError: Main is not defined.
Assuming that this was caused by the inclusion of jquery (as it still works in my old backup), I decided to update the constructor to us jquery's .click event handler,
resulting in this:
function formatDiv(target,divId,divClass,content,onclick)
{
$("#"+target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\'>" + content +"</div>");
$("#"+divId).click(function(){$(onclick)});
}
, and I changed the formatting of the functions to be called in the array piping info to the onclick parameter from "Main()" to Main.
Now when clicking on a <div>, nothing happens at all, no errors or anything.
What is the best way to add an onclick handler to my <div>s? Am I using .click incorrectly? Jquery is still new to me (despite w3schools lessons and the tutorials on jquery's site), so I'm forced to guess that I'm using it incorrectly. Any help would be appreciated.
Here's the whole script:
$(document).ready(function () {
$(Main);
//main menu
function Main()
{
var mainList = [">New List",">Show Lists",">Delete Lists"];
var onClick = [NewList,Main,Main];
var mainMenu = new Menu("Main Menu","menuMain",mainList,onClick);
mainMenu.contentMenu();
}
//new list menu
function NewList()
{
var mainList = ["> Create a New List"];
var onClick = [Main];
var newListMenu = new Menu("New List","menuMain",mainList,onClick);
newListMenu.contentMenu();
}
//menu class
function Menu(name,divClass,content,onclick)
{
$("#interface").html(null);
//title
formatDiv("interface",name,divClass,name,null);
//return
if(name != "Main Menu")
{
formatDiv(name,null,"return","^ Main Menu","Main()");
}
//display options
this.contentMenu = function()
{
for(i=0; i<content.length; i++)
{
formatDiv("interface",content+i,"menuContent",content[i],onclick[i]);
}
}
}
//format divs
function formatDiv(target,divId,divClass,content,onclick)
{
$("#"+target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\'>" + content +"</div>");
$("#"+divId).click(function(){$(onclick)});
}
});
Since your divs are created dynamically, you can't use .click() to bind as that only binds to elements that already exit when the script runs. You can however use .on() and bind to an existing element on the page. A worst case would be something like the body element but you can probably find an element closer to where the divs reside than that.
For example:
$("#"+target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\'>" + content +"</div>");
$('body').on('click', "#"+divId, function(){$(onclick)});
From the .on() documentation:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page. Or, use delegated events to attach an event
handler, as described next.
It sounds like you are looking for live() type functionality.
You don't actually want to use .live() though. Here is a good answer to why you want to actually use .on().
If you want to call a function just use functionName() instead of $(functionName) so change your code like this
$(document).ready(function () {
Main();
....
//display options
this.contentMenu = function () {
for (i = 0; i < content.length; i++) {
formatDiv("interface", "content" + i, "menuContent", content[i], onclick[i]);
}
}
....
//format divs
function formatDiv(target, divId, divClass, content, onclick) {
$("#" + target).append("<div id=\'" + divId + "\' class=\'" + divClass + "\'>" + content + "</div>");
$("#" + divId).click(onclick);
}
lets start by how you are making a div with jquery. The way you are making a div is correct but not the most efficent.
You can make any html element with jQuery with the following syntax
$('<NODE_NAME>')
so for a div it will be
$('<div>')
Now that we have a jquery object we need to add attributes to it, we do that with the attr method. we
pass it an object of attribute name/value pairs.
$('<div>').attr({
className: divClass ,
id: divId
});
Now, to add the content in the div we use the .html method
$('<div>')
.attr({
className: divClass ,
id: divId
})
.html(
content
);
and finally we add the onclick handler
$('<div>')
.attr({
className: divClass ,
id: divId
})
.html(
content
)
.click(
onclick
);
What you are doing wrong with the onclick handler is wrapping it in $(). This does not make sense, you want to call the main function, not pass it as a value
to the jquery function.
I want to set the menu to active when click on it. This is what I've tried :
<script language="javascript" type="text/javascript">
var select;
$(document).ready(function () {
$.getJSON(url, function (data) {
$.each(data, function (index, dataOption) {
var new_li = $("<li class='level1' id='select_list'><a href='javascript:void(0);' id='" + dataOption.ID + "' class ='selectedcategory'>" + dataOption.Name + "</a>");
$('a#' + dataOption.ID).click(function () {
select = "selected";
$('.level1').attr("id",select);
});
});
});
});
</script>
What I tried to do is to set the id of 'level1' to selected, when I click on that link. But my coding is set all the link to selected, even I click only 1 link.
Could anyone give me the solution please.
Thanks so much.
That happens because you are calling .attr() on all .level1 element instead of only the one being clicked by its child so,
change
$('.level1').attr("id",select);
to
$(this).parent().attr('id', select);
You also need to remove the "selected" id from the other <li>'s by
$('.level1').removeAttr('id');
So the complete code looks like:
$('a#' + dataOption.ID).click(function () {
$('.level1').removeAttr('id');
$(this).parent().attr("id", 'selected');
});
One suggestion though, class is usually used in situation like this when you want to have a selected type of a list of menu, if you are using class you'd do something like
$('a#' + dataOption.ID).click(function () {
$('.level1').removeClass('selected');
$(this).parent().addClass('selected');
}
Looks more concise that way, but I'll leave it up to you :)
I have the following code to create two buttons (one on the left one on the right) for each texbox on the page. Idea is to make an increment/decrement textbox. Code works fine with one textbox but with 2 or more every button increment/decrements all textboxes.
Any idea how to create buttons on the fly and attach them to a textbox for increment/decrement?
jQuery.fn.incrementer = function() {
this.val(0);
this.before("<input class='incrementer_minus' type='button' value=' - '/>");
var myobj = this;
$(".incrementer_minus").live('click', function(){
$(myobj).val(parseInt(JQ(myobj).val()) - 1);
});
this.after("<input class='incrementer_plus' type='button' value=' + '/>");
$(".incrementer_plus").live('click', function(){
$(myobj).val(parseInt(JQ(myobj).val()) + 1);
});
}
JQ("#increment").incrementer();
JQ("#increment2").incrementer();
You are associating the click event with every instance of incrementer_minus and incrementer_plus when you do:
$(".incrementer_plus").live('click'...
You instead need to just attach the event to the specific one that was just created.
I changed your code to do so, and I also used bind instead of live, since you just don't need live.
I also changed JQ to jQuery for my convenience. You can change it back.
Test it out: http://jsfiddle.net/mAsr9/
jQuery.fn.incrementer = function() {
var myobj = this;
this.val(0);
// Create new element, and insert before 'this'
jQuery("<input class='incrementer_minus' type='button' value=' - '/>").insertBefore(this)
// Then bind the click event to that new element
.bind('click', function(){
$(myobj).val(parseInt(jQuery(myobj).val()) - 1);
});
// Create new element, and insert after 'this'
jQuery("<input class='incrementer_plus' type='button' value=' + '/>").insertAfter(this)
// Then bind the click event to that new element
.bind('click', function(){
$(myobj).val(parseInt(jQuery(myobj).val()) + 1);
});
}
$(function() {
jQuery("#increment").incrementer();
jQuery("#increment2").incrementer();
});
You are after the spinners.. Here are some of the plugins ..
http://plugins.jquery.com/project/spinbox
http://docs.jquery.com/UI/Spinner
http://www.command-tab.com/2007/05/07/jquery-spinner-plugin/
Have a look at the jQuery Increment plugin:
http://sean-o.com/increment
I created it for just such a use, hopefully it can (still?) be of help to you.