Someone asked me how did i make the’s shopping chart on its order page. To be honest, it’s just a simple form with lots of javascript functions to make it interactive. The basic principle of the form is the use of jQuery’s .attr().

Here’s how it works:

  1. It is basically a form
  2. Most of its fields are text field
  3. To make it interactive, most of the text fields are hidden. Some fields are filled by click-the-image-or-text then insert the information attached to the object into the hidden text field
  4. When you hit the order button, the hidden text field is sent along with the shown text field.

Here’s the code to make the thing works:

The HTML markup

Optimize the use of image’s title attribute. Set a class for images that is intended to be the selector.

<img src="images/thumb-1.png" alt="image no.1" title="image no.1" />
<img src="images/thumb-2.png" alt="image no.2" title="image no.2" />

Assign an ID to the intended text field.

<input type="text" id="image-selected" value="" />

Create a previewer DOM. Since the text-field will be hidden, we need something that will be used to show the user which image that they have been selected.

<h3 id="preview-word"><span id="preview-selected-image"></span> has selected.</h3>

The JavaScript (jQuery)

Here are what we’re going to do. if the image is clicked:

  1. get the value of clicked image’s title attribute
  2. insert the clicked image title value to assigned text field.
  3. insert the clicked image title to assigned DOM which is built for previewing purpose.
  4. the preview text is hidden by default, show it.

For usability purpose, it’s a good idea to make selected item different from the unselected else. It reduces confusion. So:

  1. Change all image background to its default background color
  2. Change the clicked image background color to particular background color

Here’s to code:


// this is where the trick happens
var data = $(this).attr('title');
$('#image-selected').attr('value', data);

// for decorative and usability purpose
$('.selector').css('background-color', 'white');
$(this).css('background-color', '#960000');

To make it clearer, here’s view the demo page of this tutorial. View the page source to view it in action:

View the demo.

2 thoughts on “Filling Form Field by Clicking Image Using jQuery’s .attr()

  1. aaahhh..many thanks amigo !

    1. My pleasure. Nice to hear that 😀

Share Your Thought