开发者

multiple select with jquery

<select id="example" name="example" multiple="multiple"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> <option value="5">Option 5</option> </select>

<span class="click" id="1">one </span>
<span class="click" id="2">two </span>
<span class="click" id="3">three </span>
<span class="click" id="4">four </span>

$('.click').click( function() {
    $(this).css('background-color', 'red');
    $('#example').val($(this).attr('id'));
});

how can i make th开发者_如何学Cat use multiple select and if i click again span with background-color=red then css background-color is again white?

LIVE EXAMPLE:

http://jsfiddle.net/pUeue/28/


I assume you mean that click on multiple items successively results in multiple select options being selected, if this is the case then: This Fiddle will do the job for you. I switched to using a class as this is (a) better, and (b) easier. If you can't use a class, then it'd be easy enough to tweak. The main solution however is:

$('.click').click( function() {
    var item = $(this);

    if(item.hasClass('Active')) {   
        item.removeClass('Active');
        $('#example > [value="' + this.id + '"]').removeAttr('selected');
    }
    else {
        item.addClass('Active');
        $('#example > [value="' + this.id + '"]').attr('selected', 'true');
    }
});

Basically using .val() will select one item, what you need to do is set the "selected" property on the items you want to be selected, allowing multiple ones be selected at once. if you were using jQuery 1.6 or above, I would advise switching from attr/removeAttr to simply ".prop('selected', true/false); as selected is a DOM property.


You can set all .click elements backgrounds to white before you set the current one to red:

$('.click').click( function() {
    $('.click').css('background-color', '#FFF');
    $(this).css('background-color', 'red');
    $('#example').val($(this).attr('id'));
});


try this:

$('.click').click( function() {
    if($(this).css('background-color')=='red')
        $(this).css('background-color', 'white');
     if($(this).css('background-color')=='white')
        $(this).css('background-color', 'red');
    $('#example').val($(this).attr('id'));
});


$('.click').click( function() {
    $('.click').css('background-color', '#FFFFFF');
    $(this).css('background-color', 'red');
    $('#example').val($(this).attr('id'));
});


You can grab the select with any of the following selectors: select, select[mutliple=multiple], select#example.

Personally I'd go with the last one.

Toggling color can be achieved with these small snippet:

$('.click').click(function (e) {
  var target = $(this);
  target.css('background-color', ('red' === target.css('background-color') ? 'white' : 'red'));
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜