how to pass arguments into an event handler to make it unique? - javascript

please run this jsfiddle as an example.
http://jsfiddle.net/AFzqt/11/
in my example, i have a link saying same as above, if you fill out the first box it will copy the value in the second box. look at the code, and look at the display. theres a reiteration of the code just to have the boxes appear twice. well... in my real use of this, i ideally want there to be about 40 of these buttons.
is there a way to do this without copying the code 40 times?
i am new to jquery, usually in another language i would just pass in arguments, but with this syntax I don't see how i can do that? how can i handle this?
feel free to dabble around on my jsfiddle, and hopefully link a new revision, with the goal of reducing the handling of those 2 'same as above' buttons into just one function with the entry id's as parameters

If you add the changeButton class to each of the buttons it will be easier to select each of them to bind the event handler:
Same as Above
Then we can select each of the elements like so:
$(".changeButton").on("click", function(e) {
//select the previous jQuery Mobile select widgets, we will use just the previous two
var $allPrev = $(this).prevAll('.ui-select').find('select');
//change the value of the immediate previous select widget to the value of the one preceding it
$($allPrev[0]).val($($allPrev[1]).val()).selectmenu("refresh");
e.preventDefault();
});
Here is a demo: http://jsfiddle.net/AFzqt/12/
This code will work for umpteen buttons since it works by using intuitive knowledge of the HTML structure (each link uses the previous two select widgets, no matter where on the page the link resides).

What about something like this?
function bind_click(button_id, target_id, origin_id) {
$(button_id).on("click", function(e) {
$(target_id).val($(origin_id).val());
$(target_id).selectmenu("refresh");
e.preventDefault();
});
}
$(function() {
bind_click("#changeButton2", "#entry_20", "#entry_18");
bind_click("#another", "#entry", "#entry2");
// More binding declarations
});

Related

jQuery clone misunderstanding

I'm not understanding this cloning process... this is what's happening, there are four pictures, three clicks, first photo is the initial state.
In the third picture there are two boxes, that's fine, but rather than each box having one project name input and add task button, there are two in the first box, and normal in the second box. Click the button again and it becomes 3:2:1, next click it would be 4:3:2:1, etc... I don't want that. I just want boxes to be added with one piece per box.
code
function addProject() {
$(project).clone().appendTo(".projectPanel");
$(projectNameInput).clone().appendTo(".project");
$(addTaskButton).clone().appendTo(".project");
}
Your problem is your appendTo it appends the element to all elements in the set of matched elements so everything with the class "project". for more information on it try looking at the jquery appendTo documentation. to fix it try something like this
function addProject() {
var newProject=$(project).clone();
newProject.appendTo(".projectPanel");
$(projectNameInput).clone().appendTo(newProject);
$(addTaskButton).clone().appendTo(newProject);
}
using the return value of $(project).clone() allows you to grab only the new project rather than all of the projects that currently exist

Change events on dynamically added selects using the Chosen plugin

I'm using the Chosen plugin on my site, and so far it has been working perfectly. However, I'm in a situation where I added a select dynamically and activated the Chosen plugin on those selects. These Chosen selects are being produced fine, but I cannot figure out how to bind a click event to the element. Chosen offers this( $("#form_field").chosen().change( … );) as a way to do something on the change event, however, this does not work since my select was added dynamically.
I have tried $('#el').change and $(document).on("change", "#el", function()) as well without any success.
Original Answer:
From http://harvesthq.github.io/chosen/#change-update-events
"If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content."
$("#form_field").trigger("chosen:updated");
...so just call that after you add the new element.
Edit:
After reviewing this http://jsfiddle.net/amindunited/reh5p0tg/3/
I can see that the issue was that the change() listener for the second select was being attached before that select was added to the page.
I have updated the fiddle code to work:
http://jsfiddle.net/amindunited/reh5p0tg/4/
EDIT
Another way to make it work is to stuff everything inside an init function:
function init_new_content(){
$("#form_field").chosen();
}
init_new_content();
And then call it whenever you know you made a change (for example on ajax)
$.ajax({...},
success: function( data){
init_new_content();
},
...

JS library show/hide element on checkbox status

I'm fairly new to JS and am trying to write my own library using this blog post, and would like a hand. (Apologies if this is too vague for an SO question)
I'm trying to write a function that shows or hides a queried element based on the status of a queried checkbox (and another for a radio button if I can't do it in one method) on a form.
So I'm looking to end up with something like this:
$(divId).checkToggle(checkBoxId);
So the div will start as hidden. When the checkbox is clicked, the div will toggle to visible. When the checkbox is unchecked, I'd like the div to hide again and any input fields inside it to be cleared (the probably will be only one input field).
I know that this function isn't really going to be very combine-able or reusable, but I would use it so often for just that one thing that I'm going to overlook it.
Okay, enough preamble. Here's what I have so far.
Could I have some suggestions on how to change/finish my checkToggle method? Thanks!
This worked for me:
$(document).ready(function(){
$('#checkbox1').change(function() {
if($(this).attr('checked')) {
$("#myDiv").slideDown(1000);
}
else
{
$('#myDiv').slideUp(1000);
}
});
});

Paste into text field TideSDK

I have the following code, I want a user to be able to copy or paste into a text field,
basically imitating a ctrl+c or ctrl+v
My problems are:
how to make sure the context menu only appears in text fields
how to paste the text into the region.
I have been through the docs and so far I have this NOT working:
var menu = Ti.UI.createMenu();
menu.addItem('Copy', function() {
var data =$.("#this").val()
Ti.UI.Clipboard.getData('text/plain',data);
});
menu.addItem('Paste', function() {
var data =Ti.UI.Clipboard.getData('text/plain');
$.("#this").val(data)
});
function showrightmenu(){ Ti.UI.getCurrentWindow().setContextMenu(menu);}
I could call this using oncontextmenu= "showrightmenu()" but now, how to paste something in this line:
$.(#this).val(Ti.UI.Clipboard.setData('text/plain'))
AM GROPING IN THE DARK. I'm a newbie to TideSDK, this is my first project.
Question 1
I'm new to TideSDK as well and might be wrong, but as far as I can tell from the API documentation, context menus are bound to a window, and displaying different context menus when right clicking different parts of the window would require you to each time change the window's context menu...
Example:
//Create different menus
var context_menu = Ti.UI.createMenu();
var copy_menu = Ti.UI.createMenu();
//Add menu items etc.
...
//Change context menus on click events depending on clicked element
$('#some-element').mousedown(function(event){
if(event.which==3){//detect right click
editor_window.setContextMenu(context_menu);
}
});
$('#text-field').mousedown(function(event){
if(event.which==3){//detext right click
editor_window.setContextMenu(copy_menu);
}
});
This way, when you click the element with id some-element, the first context menu is shown, and when you click the #text-field element, the second context menu is shown.
Note that this won't work if one element is inside the other, because then both events are fired.
Question 2
In this code you supplied:
$.(#this).val(Ti.UI.Clipboard.setData('text/plain'))
You want to use Ti.UI.Clipboard.getData and not Ti.UI.Clipboard.setData, since you want to get the text stored in the clipboard and then put it into the text field. Also, you might want to change $.(#this) to $("#this") or $(this).
This should work:
$("#some-element").val(Ti.UI.Clipboard.getData('text/plain'))
Remark
You seem to be confused about how to use jQuery. To select an element, you use $() and not $.(). Also, with $("#example") you select the DOM element with the id example. $(this) is used inside a function called when an event is fired, and refers to the element on which the event was fired. $("#this") is not the same as $(this). Hope that helps a bit...

jQuery searchable checkbox list and tristate checkbox

I'm building a simple asp page on which I have list of peoples with checkbox on left of every name.
I've managed to create a simple jQuery script that allows hiding and showing rows of table based on input:
http://jsfiddle.net/Tq97v/ (first part)
As You can see I can enter part of name and then specific row are hidden.
Using red "x" I can uncheck all checkboxes.
What I'm trying to do now is to change that static red "x" into tristate checkbox.
Don't have idea how to even start.
Do I must add change listener to every checkbox in my list?
Second thing - how to create multiple instances of the same "plugin" on site.
Right now I'm identifying input by it, but it would be nice to call function with that input as param, and it would fine table after that input and create necessary logic.
This way I could call function multiple times on page to have more than one list.
I'm not asking for whole solution (of course it is always welcome :) ) but what I need is idea how to accomplish this in efficient way and as optimized as possible, because sometimes my list has 500+ elements.
P.S. don't look at HTML code, it is ASP generated.
I found this plugin: https://github.com/bcollins/jquery.tristate, but I have no idea how to use it with my list.
UPDATE:
I've managed to turn my code into functions, but right now I must call 3 functions for every list.
Here is my updated code: http://jsfiddle.net/65MEV/4/
How can I change it to one function? Will it be better?
This is my updated code. Still thinking about way of doing that Indeterminate Checkbox instead of my remove image.
UPDATE2
I build working code :)
http://jsfiddle.net/65MEV/9/
But I would like to improve it as much as possible.
Any suggestions are welcome!
A tristate checkbox is like the Three-Portal Device: an illusion.
What you actually want is to make the checkbox indeterminate (by setting the property of the same name to true). To implement this, you will need a change (or click) handler on each checkbox, then you'll need to check if all of them are in the same state, and if not then you set the indeterminate property. It's a hassle, really, because you rarely see indeterminate checkboxes and so most users don't know what to do with them. To be avoided, if possible.
To create multiple instances of the same plugin access elements relatively to an other element.
For example: in your case instead of keeping the item in a jQuery object var $tableRows = $('table.myList tr'); access them in the event.
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if(lastInput==sValue) return;
var $tableRows = $(this).next().next().find("table.myList tr");
if (sValue == '') {
$tableRows.show();
} else {
$tableRows.each(function () {
var oLabel = $(this).find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
}
});
lastInput=sValue;
}
});
and you only have your actual list.
And for the tree state checkbox you don t need a plugin just add a button or link and every click check it status you can keep the status by jQuery data and change the element image according to this data.

Categories