jQuery set call back on child elements - javascript

I am trying to attach an onChange callback to all the input elements under the div #dim. It selects all 3 input elements, but returns an exception:
Uncaught TypeError: Object 0 has no method 'change'
It may be because x may not be a jQuery object. How would I make this work?
function registercb() {
var sel = $("div.dim > input");
for (x in sel) {
x.change(function() {
dosomething();
});
}
}

You can simply do:
function registercb() {
$("div.dim > input").change(dosomething);
}
A few things to watch for:
Inside that iteration (don't use this, see the next point) x is the DOM element, not a jQuery object which has the .change() method, you would need to wrap it in a jQuery object like $(x), but again that isn't the correct solution here.
Don't use a for(...in...) loop to iterate an object (a jQuery object is array-like), that type of loop is for enumeration.
Most jQuery functions (almost all) run on more than one element, so just run it on the set to affect all elements, .change() is one of these.
In the cases you do need to loop, check out .each(), as it'll make your life much easier, don't use this here, it's only an example of what it would look like:
Example:
function registercb() {
$("div.dim > input").each(function() {
$(this).change(dosomething);
});
}

You don't have to loop over the elements. You can think of a jQuery object as holding a collection. When you do:
var sel = $("div.dim > input");
It means that sel has all the input elements in it, so then when you run a method like change() it will affect all of the elements in the collection. Thus you can do something like this:
function registercb() {
$("div.dim > input").change(function(){
dosomething();
});
}
Bonus knowledge: Now your problem is that when you were doing for( x in sel ) you are getting a lot of stuff on the jQuery object itself that you don't want. If you run the following code in chrome you'll see it outputting a lot unexpected stuff:
for( x in sel ){
console.log( x );
}
Instead jQuery has the each that lets you loop over the things you want:
sel.each(function(index, item){
console.log(item);
});
You can even use it on other things, which is really handy!
$([1,2,3]).each(function( index item ){
console.log( item ); // 1,2,3
})

Assuming your 'dim' div has an ID rather than a class of dim, you can simply do this:
$("#dim > input").change(function() { dosomething(); });
Working example.
In the text you refer to #dim whereas in the code you're refering to .dim - # selects by ID and . selects by class, so if your div is in the format <div id="dim"> then you won't find any matched elements with div.dim as your selector.

Related

Pure JavaScript alternative to jQuerys .find

I have this in jQuery:
$(document).bind("click touchstart", function(e) {
if (e.target.class != searchControls && !searchControls.find(e.target).length) {
//do something
});
});
What this does is checks the click and if it's not the search element a child of that element, then I can run something. What I'm trying to do is find a pure JavaScript alternative to this.
So far I have:
var searchTrigger = document.querySelector(".header__search-btn"),
productSearch = document.querySelector(".product-search"),
searchControls = document.querySelectorAll(".product-search__positioner");
document.onclick = function (e) {
if (e.target.class != searchControls && e.parentNode != searchControls)
// do something
}
}
However this still fires my function inside the if statement, so clearly I'm going wrong—not sure how wrong. Help appreciated.
document.querySelectorAll returns a collection of DOM elements. e.target.class != searchControls doesn't make sense (ignoring that target.class doesn't even exist): Assuming you mean className, you are trying to compare a string with a list of DOM elements. That will always be false.
So lets ignore that part and look at e.parentNode != searchControls. The event object doesn't have a property parentNode. Again, even if you meant e.target.parentNode, it would not make much sense, since you are testing whether a single element is identical to a list of elements.
Based in your use of .find, you basically want to know whether a node is contained in another node. Every DOM node has a method .contains, so all you have to do is iterate over the collection of DOM elements and call that method:
var contained = false;
for (var i = 0; i < searchControls.length; i++) {
if (searchControls[i].contains(e.target)) {
contained = true;
break;
}
}
This can easily be moved into its own reusable function.
There is no e.target.class. If you are checking for class name then it should be
e.target.className
Then to check for parent elements class name
e.target.parentNode.className
if you are looking to search inside the parent node then use
e.target.parentNode.querySelector("pass your selector here")
if you want to search for just child elements:
e.target.querySelector("pass your selector here")

Get ID of table row in for statement

I have this line of code in my JavaScript:
for (var row in $('#alertsbody > tr')) {
. . .
}
I need to test that the ID of the row matches a value. However,
if (row.attr('id') == myRowId) {
. . .
}
Generates a "TypeError: row.attr is not a function" error.
What's the right way to get the ID of the row?
Do not use a for..in loop to iterate over the elements of a jQuery collection. for..in iterates over all properties of an object, and a jQuery collection has a hell of a lot of properties, only some of which are actual elements of the collection. Use jQuery's provided .each() function -> http://api.jquery.com/each/
A sidenote, the variable row in for(row in something) will contain property names, not the values of the properties.
jQuery selector returns an array of elements wrapped by a jQuery object. Using your code, row would represent a property of the object, which would work for the numeric properties; but would break for all the other properties (see below for why this is bad).
Again, the following should not be used, but using your code, you would implement the in looping construct by caching your selector:
var $tr = $('#alertsbody > tr');
for (var row in $tr) {
// perform any property validation here
if (isNaN(row))
continue; // try next property
// id validation
if ($tr[row].id == myRowId)
. . .
}
Warning / Better Alternative
This is a bad idea. This is because you should not loop through the object in this manner, instead you should iterate over the jQuery object using .each().
$tr.each(function(){
if(this.id == myRowId)
...
})
Alternative
Some alternatives are to skip the loop entirely and select the rows by id eg($('#myRowId') or $('tr#myRowId')though, tr is not necessary as there should only be one id per HTML page) and perform some action. Or, if you already have some looping construct in place or need an alternative checking mechanism, you can use the .is() function:
var domElement = document.getElementById('myRowId');
var $jqElement = $('#myRowId');
$tr.each(function(){
var $this = $(this);
if( $this.is('#myRowId') )
...
if( $this.is( domElement ) )
...
if( $this.is( $jqElement ) )
});
As you're writing it, you could use the each function to iterate, and then JQuery wrap each element before checking the id:
$("#alertsbody > tr").each(function(i, tr) {
if ($(tr).attr('id') == myRowId) {
//do something
}
});
However, given what you're trying to do, wouldn't it make more sense to just get the element with the specific id?
$(myRowId)
The only time you'd need to iterate multiple elements would be to select by a non-unique attribute such as class, and even then you could incorporate that into the JQuery selector:
$("#alertsbody > tr."+myRowClass)

jQuery append() for multiple elements after for loop without flattening to HTML

I have a loop:
for (index = 0; index < total_groups; index += 1) {
groups[index].list_item = $(list_item_snippet);
// Closure to bind the index for event handling
(function (new_index) {
groups[index].list_item.find('.listing-group-title')
.html(groups[index].Group.Name)
.click(function(e){
fns.manageActiveGroup(new_index, groups);
return false;
});
})(index);
// Append to DOM
mkp.$group_listing.append(groups[index].list_item);
};
I would rather not call append() each time the loop fires.
I know that I could use a String and concatenate the markup with each loop iteration and append the string to mkp.$group_listing at the end, however this flattens the object and the bindings are lost (I am not relying on IDs).
Is there a way to perhaps add my objects to an array and append them all in one go at the bottom without flatening to HTML?
Assumptions:
$(list_item_snippet) contains some HTML defining a list item (and includes an element with class .listing-group-title).
groups is a block of JSON defining a 'group' in my script
The closure works perfectly
Edit:
Found that I can use the following syntax to append multiple elements:
mkp.$group_listing.append(groups[0].list_item, groups[1].list_item );
But i obviously need to automate it - it's not an array it's just optional additional function parameters so I'm not sure how to do this.
To append an array of elements to a selector you can use this:
$.fn.append.apply($sel, myArray);
In your case, since it's actually the .list_item property of each array element that you need you can use $.map to extract those first:
$.fn.append.apply(mkp.$group_listing, $.map(groups, function(value) {
return value.list_item;
}));
Instead of bind it the way you've done, if you bind it using on() like below,
$(document).on('click', '.listing-group-title', function() {
// click handler code here
});
You can flatten the HTML and append it in one statement and it'll still work.
Note: For better efficiency, replace document in the above statement to a selector matching the closest parent of .listing-group-title
Yes. Use the jQuery add method to add all your items to a jQuery object. Then append that one object.
http://api.jquery.com/add/
EDIT: Example:
var arr = $();
for (index = 0; index < total_groups; index += 1) {
groups[index].list_item = $(list_item_snippet);
// Closure to bind the index for event handling
(function (new_index) {
...
})(index);
// Add to jQuery object.
arr.add(groups[index].list_item));
};
mkp.$group_listing.append(arr);

select html element id using jquery and .change()

I have several <select> boxes all using the same prefix and I would like to set up a recursive function to essentially do the work for me.
$('[id^="by_"]').change(function(e)
{
var elem = e;
console.log(e.value);
});
Based on this code is my intention pretty clear? Am I on the right track?
console prints out: undefined
I think you're on the right track - the selector you're using matches a prefix of "by_", and you're binding the change event to all of them. Make sure you put this in $(document).ready or similar. Are you having any problems with this code? Instead of using the e parameter, I would just use this inside of the function to refer to the element and $(this) to get the jQuery object of it. So to get the value, you'd use:
this.value
// or
$(this).val()
(ignore the e and elem stuff, although it wouldn't be a bad idea to store $(this) in something like elem so you can have a reference to it instead of re-creating the jQuery object every time you need it)
When using callbacks to events with jQuery, the (first) parameter of the callback is an event object that explains many things about the event that occurred ( http://api.jquery.com/category/events/event-object/ ) and does not hold the element - that's what this is for!
e in your code is the event object which has no value property, you should use this instead:
$('[id^="by_"]').change(function(e) {
var elem = this;
console.log(this.value);
});
Or if you want to use event object, you can use target property:
e.target.value
Since you're already using jQuery, why not something like this:
$('[id^="by_"]').change(function(e)
{
var $elem = $( this );
console.log( $elem.val() );
});
Isn't it more something like that:
$('[id^="by_"]').change(function()
{
console.log($('option:selected',this).val());
});
​
jsfiddle

Javascript array not working as expected

I'm pretty new to js/jquery. For each checkbox with the ID of check$ (where $ is a sequential number), I want to toggle the class "agree" of the surrounding span that uses the same check$ (but as a class). I don't want to have to hard-code the list of matching checkboxes, as this may vary.
Here's my code. This function works as expected:
agree = function (checkbox, span) {
$(checkbox).change(function(){
$(span).toggleClass('agree');
});
};
This is what I'm trying to pass to the above function, which does not work:
$(function() {
var elemid = 'check',
checks = Array($('[id^='+elemid+']').length);
console.log(checks);
for (i=0; i < checks; i++) {
agree('#'+elemid+checks[i], "."+elemid+checks[i]);
}
});
console.log(checks) returns [undefined × 4]. The number of elements is correct, but I don't know why it's undefined, or whether that is even significant.
The following code works as expected, but as I say, I'd rather not have to specify every matched element:
$(function() {
var checks = ["check1", "check2", "check3", "check4"];
for (i=0; i < checks.length; i++) {
agree('#'+checks[i], "."+checks[i]);
}
});
Thanks.
Edit: Thanks to Jack, I was overlooking the most simple method. I added the same class to all checkboxes and spans, and solved the problem with this:
$('input.check').change(function(){
$(this).closest('span.check').toggleClass('agree');
});
I might be totally missing something, but I'm pretty sure you are just trying to attach a change handler to each checkbox. In this case you can give them all the same class. I'm also guessing at your html structure for the span.
For reference:
http://api.jquery.com/closest/
http://docs.jquery.com/Tutorials:How_jQuery_Works
$('.yourcheckboxclass').change(function(){ //grab all elements with this class and attach this change handler
$(this).closest('span').toggleClass('agree');
});
The reason that the array is full of undefined values, is that you are just getting the number of items in the jQuery object, and create an array with that size. The jQuery object is discarded.
Put the jQuery object in the variable instead:
var elemid = 'check', checks = $('[id^='+elemid+']');
checks.each(function(){
agree(this, "."+elemid+checks[i]);
});

Categories

Resources