Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement jQuery val() for a span?

I have a few select elements that are grouped by a span. I'm creating a plugin to do some interaction with the elements. Now I would like to give my users the support of the val() function, so that they are able to get or set the 'value' of my span. Setting the value will result in the select box element to change en getting the value will result in the addition of the selectbox values.

Basically I would like my plugin to add the support for the val() method. Any ideas on how to implement this?

Code

<span id="test">
    <select id="one">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
    <select id="two">
        <option value="1">1</option>
        <option value="2">2</option>
    </select>
</span>

Challange
Get the following code to work: $('#test').val('1:1'); and $('#test').val().

like image 417
Kees C. Bakker Avatar asked May 05 '11 09:05

Kees C. Bakker


1 Answers

This is not a full plugin and I did not override val() but it should do what you want.

$.fn.value = function(value) {
    if (value) {
        var s = value.split(':');
        for ( var i = 0; i < s.length; i++ ) {
            this.find('select').eq(i).val(s[i]);
        }
    } else {
        var result = [];
        this.find('select').each( function( index, item ) {
            result.push($(item).val());
        });

        return result.join(':');

    }
}

$(function() {
    $("#test").value("2:2");
    alert($("#test").value());
});

You can try it at http://jsfiddle.net/QBSWm/1/

like image 64
DanielB Avatar answered Oct 08 '22 23:10

DanielB