Demsaas Demsaas - 1 month ago 9
Javascript Question

Select option of dropdown and make it not active?

I got select :

<select class="form-control" id="category_id_select" name="Category_Id">
@foreach (var category in Model.categories){
<option value="@category.Id">@category.Name</option>
}
</select>


And I got the input where I set value that must be selected on page load :

<input type="text" class="form-control" id="cat_id" value="@Model.CategoryId"/>


My js file is :

$(document).load(function () {
$('.combobox').combobox();
var catid = $("#cat_id").val();
$("#category_id_select ").val(catid);
$("#add_prop").click(function () {
alert(catid);
});


What am I doing wrong?

I will hide that input and wanna to have not active dropdown with already selected value.Whats solution with jquery?

Answer

You need to trigger the value change that you made :

$("#category_id_select").val(catid).change();
//Or  
$("#category_id_select").val(catid).trigger('change');

NOTE : Remove the extra space you've in your selector :

$("#category_id_select ").
______________________^

And try to use ready function :

$(function(){
     //Your code here
})

Hope this helps.

$(function () {
    var catid = $("#cat_id").val();
    $("#category_id_select").val(catid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="category_id_select" name="Category_Id">
    <option value="c1">category 1</option>
    <option value="c2">category 2</option>
    <option value="c3">category 3</option>
</select>

<input type="text" class="form-control" id="cat_id" value="c3"/>

Comments