ashokkumarn12
ashokkumarn12

Reputation: 145

Javascript Adding If Statement In Select tag ID

This is my drop down using select and the id is beh_type

<select class="form-control" id="beh_type">
<option value="0">Auto</option>
<option value="1">Man</option>
</select>

and this is my multiple select list and the id is mult_type

<select multiple="multiple" class="form-control" id="mult_type">
<option value="0">Auto</option>
<option value="1">Man</option>
</select>

and this is my JavaScript code for single click using if condition and the code to be executed for mult_type not for beh_type

if($("select").attr("id") == "mult_type"){        
$("select").mousedown(function(e){
        e.preventDefault();

            var select = this;
        var scroll = select.scrollTop;

        e.target.selected = !e.target.selected;

        setTimeout(function(){select.scrollTop = scroll;}, 0);

        $(select).focus();}
    }).mousemove(function(e){e.preventDefault()});

Upvotes: 0

Views: 773

Answers (2)

Nirbhay Jha
Nirbhay Jha

Reputation: 675

You just need to change the position of "if". The correct code would be

$("select").mousedown(function(e){
 if($("select").attr("id") == "mult_type"){    
    e.preventDefault();
    var select = this;
    var scroll = select.scrollTop;

    e.target.selected = !e.target.selected;

    setTimeout(function(){select.scrollTop = scroll;}, 0);

    $(select).focus();}
}).mousemove(function(e){e.preventDefault()});

Upvotes: 1

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

If you need that event for select with id value as mult_type then add those event using the id selector:

$("#mult_type").mousedown(function(e){
    e.preventDefault();

    var select = this;
    var scroll = select.scrollTop;

    e.target.selected = !e.target.selected;

    setTimeout(function(){select.scrollTop = scroll;}, 0);

   $(select).focus();
}).mousemove(function(e){e.preventDefault()});

Upvotes: 2

Related Questions