user1824797
user1824797

Reputation: 89

Determine if ONLY ONE option is selected in multi select

With the following code, I am using a multi select box to enable the user to select multiple options. I am displaying a preview image of the selected option in another div when the user selects one of the options.

This all works, however I would like to be able to update the div with the image preview to show a placeholder image when more than one item is selected.

Ideas?

<select multiple id="opt1-opts">
      <option value="diesel_nova_rts_06_1996">Nova RTS-06 - 1996</option>
      <option value="diesel_nova_rts_06_1998">Nova RTS-06 - 1998</option>
      <option value="diesel_nova_rts_06_1999">Nova RTS-06 - 1999</option>
      <option>Nova 40LF - 2011</option>
      <option value="new_flyer_40lf_2011">New Flyer 40LF - 2011</option>
      <option value="orion_v_1995">Orion V WC - 1995</option>
      <option value="orion_v_1996">Orion V WC - 1996</option>
      <option value="orion_v_1999">Orion V WC - 1999</option>
      <option>Orion 40LF - 2011</option>
</select>
<div id="dialog-bus-type-image-info-area">
      <img src="imgs/LFS60102.JPG" border=0>
</div>

//bus type dialog scripts
$("#opt1-opts").change(function(){
    $("#dialog-bus-type-image-info-area").empty().append("<img src='imgs/busTypes/" + $("#opt1-opts option:selected").val() +".jpg' border='0'/>");
});

Upvotes: 1

Views: 670

Answers (2)

Pat Dobson
Pat Dobson

Reputation: 3299

Here's a fiddle : http://jsfiddle.net/moonspace/zQQbL/

HTML:

<select multiple id="opt1-opts">
      <option value="diesel_nova_rts_06_1996">Nova RTS-06 - 1996</option>
      <option value="diesel_nova_rts_06_1998">Nova RTS-06 - 1998</option>
      <option value="diesel_nova_rts_06_1999">Nova RTS-06 - 1999</option>
      <option>Nova 40LF - 2011</option>
      <option value="new_flyer_40lf_2011">New Flyer 40LF - 2011</option>
      <option value="orion_v_1995">Orion V WC - 1995</option>
      <option value="orion_v_1996">Orion V WC - 1996</option>
      <option value="orion_v_1999">Orion V WC - 1999</option>
      <option>Orion 40LF - 2011</option>
</select>
<div id="outputs"></div>

JS:

$("#opt1-opts").change(function(){
    var selectCount = $("#opt1-opts :selected").length;
    if (selectCount == 1){
        $('#outputs').html("ONLY one selected");
    }else{
        $('#outputs').html("");
    };
});

That should do it . . .

Upvotes: 2

Luis Masuelli
Luis Masuelli

Reputation: 12333

$("#opt1-opts option:selected").length will give you how many children options are selected.

Upvotes: 2

Related Questions