SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Changing <option SELECTED> onclick

    Hello all

    Had a look around here and found some similar issues that someone with a better brain for javascript could probably adapt to this one.. but alas I don't have that brain!

    It's fairly simple, I have <select> menu which, by default when the page loads, would have the first <option> as selected. I want this to change when someone clicks on an image - ie there are 4 images and 4 <option>s and clicking the corresponding image would jump the menu to the related <option>.

    Out of interest is this the kind of thing something like jQuery could be told to do? I need to pull my finger out and start using that I think, rather than struggling around on my own.

    Thanks for any help.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    jQuery does make it easier to perform the event part of the process.

    Place a class name on each image, attach an event on to them.

    Code javascript:
    $('img.option').click(handleImageOption);

    The handler needs to have an easy way to know what value to change the option to, so we could use an id attribute on each image that combines the select name with the desired option index

    Code javascript:
    function handleImageOption() {
        var img = this,
            matches = /([^\d]*)(\d*)/.exec(img.id),
            selectName = matches[1],
            selectOption = Number(matches[2]);
        $('[name=' + selectName + ']').get(0).selectedIndex = selectOption;
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Apr 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect, thanks a lot.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •