Sid M
Sid M

Reputation: 4354

How to select the given option in dropdown

I've a dropdown

<select id="ddl1">
    <option value="0">number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
</select>

now what i'm doing is as soon as user clicks on ddl1 i change its default value to 4 like this

$(function () {

    var defaultValue = "4";

    $('#ddl1').click(function () {
        var select_val = $('#ddl1').val();

        if (select_val == "0")
            $('#ddl1').val(defaultValue);
    });
});

but now the problem is when user tries to select the default option of dropdown i.e number, option 4 is selected. Any ideas how to fix this?

The problem is when the user just clicks on dropdown -> option4 must be selected and when user clicks on option number -> option number must be selected instead of option 4.

Upvotes: 1

Views: 67

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Not sure why you're doing that but focusin or focus events can help you achieve that as follows:

$(function() {
    $('#ddl1').on('focusin', function() {
        this.value != 0 || $(this).val( 4 );
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="ddl1">
    <option value="0">number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
</select>

Upvotes: 1

indubitablee
indubitablee

Reputation: 8206

is this what you're looking for? http://jsfiddle.net/swm53ran/84/

$(function () {
    var defaultValue = "4";
    var count = 0;
    $('#ddl1').click(function () {
        if (count < 1) {
            $('#ddl1').val(defaultValue);
            count++;
        }        
    });
});

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

You should call this function on change, not click - else, like you said, as soon as you click an option is selected.

$('#ddl1').change(function () {

DEMO

Edit: You should use a class to give the feel of the default option, you don't actually want it set to selected EACH time the user clicks:

<select id="ddl1">
    <option value="0">number</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4" class="default">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
</select>

.default {
    color: blue;
}

Upvotes: 1

Related Questions