Home > Jquery, html > Select element, return 2 values

Select element, return 2 values

I had a problem earlier today: I needed to have a select box that returns 2 or more values in stead of 1.
I got this far:
The value of the options gets the id of the item that is displayed in each option.
I do have an other value that should be linked on this option. Is there an easy way to do this?

<select id="category" name="data[cat]">
    <option label="0" value="12">A</option>
    <option label="0" value="7">B</option>
</select>

I tried to do this with entering the second value into a label attribute but then the problem is that i don’t know the correct way to get the label value of the selected option. This is written in Jquery.
To get the selected option I use:

$("#category").livequery('change', function () {
var catId = ($(this)[0].value);
});

the solution seems to be quite simple:

The label attribute is used by some browsers to display the content of the option, so your list box might display two 0 options.

A better solution might be to do the following:

<select id="category" name="data[cat]">
    <option value="12,0">A</option>
    <option value="7,0">B</option>
</select>

and split the value in the event handler, e.g.

$("#category").livequery('change', function () {
    var values = ($(this)[0].value).split(",");
    var catId = values[0];
    var otherId = values[1];
});

Wasn’t that easy

Bookmark and Share
Categories: Jquery, html Tags: , , , , ,
  1. May 17th, 2009 at 06:39 | #1

    Do you have a working sample I could look at? I would appreciate it.

  2. May 18th, 2009 at 13:16 | #2
  3. May 18th, 2009 at 17:57 | #3

    Thank for taking the time with the example. I still seem to be doing something wrong. I pasted my code below. What I’m trying to do is pass multiple values for option test

    Your help is appreciated

    html
    ==============================

    All
    test
    Goods
    Services
    Wants

    Your script modified to use weblog_id
    ===============================

    jQuery(function($) {

    $(“#weblog_id”).change(function () {
    var values = ($(this)[0].value).split(“,”);

    console.log(“first value = ” + values[0]);
    console.log(“second value = ” + values[3]);
    });

    });

  4. May 18th, 2009 at 18:02 | #4

    Why do you use values[3] ?

  5. May 18th, 2009 at 20:09 | #5

    Below is the form code. Hopefully it shows in the comment. I’m trying to pass values 2,3


    All
    test
    Goods
    Services
    Wants

  6. May 18th, 2009 at 20:13 | #6

    I Removed the in the code so you get a better Idea.

    select id=”weblog_id” name=”data[cat]”
    option value=”null” selected=”selected”>All/option
    option value=”2,3″test/option
    option value=”3″>Goods/option
    option value=”2″>Services/option
    option value=”5″>Wants/option
    /select

  7. May 19th, 2009 at 01:59 | #7

    Ok, Think I finally got it to work.

  1. No trackbacks yet.