How to use custom element attributes in JQuery

Have a look at the following snippet of very basic HTML.

<input type="button" class="my_button" value="Submit" product_id="1234">

You’ll recognise this as a FORM button, with a value of “Submit” and a DOM element class of “my_button”.

Nothing strange in that. But what’s this 3rd attribute in the element, “product_id”? That’s not a valid HTML attribute, is it?

No, its not. Its a custom attribute that I’ve added. It could be anything, and it will have no impact on the output of the button in the browser.

So why add it?

Custom HTML attributes, blended with a Javascript Framework like JQuery, are an excellent way to develop fluid UIs in web applications.

Let’s use the above example. Let’s say we have a list of products in a shopping cart application, and we want to give the user the option to add products to a cart, but we want to do this with AJAX, so we don’t have to refresh the page each time.

Our web application renders the list of products, each with a Submit button that has a custom HTML attribute “product_id” with a value of the product’s catalogue ID.

So, in our Javascript, we use JQuery to trigger our required Javascript when the document loads. Standard stuff.

$(document).ready(js_Init);

In our initialisation function, we then attach another function, js_addToCart(), to the Click event on any element with class, “my_button”.

function js_Init() {
	$(".my_button").live("click", function(event) {
                  js_addToCart($(this).attr("product_id"));
        });
}

Now, notice the argument that we pass to this function.

Its a JQuery object first and foremost, that is, the element on which the Click event occurred. The argument we want is the value of the attribute of that element called “product_id”.

Our js_addToCart() function now has the catalogue ID of the product the user wants to add to their cart, which we can process with JQuery without ever having to do a FORM submission.

You can add as many custom attributes to an element as you wish, and pass as many of this back to JQuery as you wish, which means you should never really have to use a HTML form again.

One thought on “How to use custom element attributes in JQuery

  1. Alex

    You should probably use “data-” prefixed attributes in order to make them valid according to HTML5 standards

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>