William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery: alert() jQuery objects

1.
Issue: How to use javascript alert() to display jQuery variables?
Solution: use .get([index]);

How to use javascript alert() to display jQuery variables?
alert() is a Javascript method, only accept DOM object, NOT jQuery objects. jQuery’s .get() is a good way to combine with them, it converts jQuery object to DOM object.

I use the following to get the total values of a multiple choice checkbox group.


var total = $('input[name="multi-choices"]:checked').map(function() {
	return $(this).val();
}).get().join(',');
alert(total);

It works fine, .map() returns a jQuery object instance, .get() convert it to DOM array, JS’s join() convert the JS array to string for alert().

2. more .get()


$('fieldset legend').get(0).innerHTML;
if ($(this).parent().get(0).tagName=='a') {...}
$($('div').get().reverse()).appendTo('body');

The last one is interesting, it uses JS’s reverse() to generate new DOM object, then change back to jQuery for the adding.

3. form’s .serialize()

Besides .get(), an available way is to use jQuery form’s .serialize() method to alert().
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:


$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

4. more methods between jQuery and DOM

According to jQuery, there are 4 methods to convert jQuery object to DOM object.

  • .get()
    Retrieve the DOM elements matched by the jQuery object.
  • .index()
    Search for a given element from among the matched elements.
  • .size()
    Return the number of DOM elements matched by the jQuery object.
  • .toArray()
    Retrieve all the DOM elements contained in the jQuery set, as an array.
    According to John Resig:
    Yep, it’s identical to .get(), just a different (and more usable) name. Although, .get() takes an argument for retrieving a single element and .toArray() does not.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: