Jet
Jet

Reputation: 45

Javascript set default value on dropdownlist not working

<select id="modalAdd_DDLSample"> </select>
<option value=0> PC</option>
<option value=1> MAC </option>
<option value=2> Rasberry </option>
$("#modalAdd_DDLSample").val("1");
$("#modalAdd_DDLSample").val(1);
$("#modalAdd_DDLSample").val('1');
$("#modalAdd_DDLSample").val("1");
$('#modalAdd_DDLSample option[value="1"]').attr("selected",true);
$('#modalAdd_DDLSample option[value="1"]').attr("selected","selected");

I have tried many ways to set dropdownlist value to default value 1(MAC) when form is load but none of them works, did I missed something important? Appreciate your help

Upvotes: 0

Views: 1762

Answers (4)

Kishore Newton
Kishore Newton

Reputation: 175

<select id="modalAdd_DDLSample"> 
   <option value="0"> PC</option>
   <option value="1"> MAC </option>
   <option value="2"> Raspberry </option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
    let value="1"; 
    $("#modalAdd_DDLSample").val(value);
</script>

Upvotes: 1

Ayu Anggraeni
Ayu Anggraeni

Reputation: 26

Your select code is wrong, the options should be written inside select tag.
This is the html code.

<select id="modalAdd_DDLSample"> 
    <option value=0> PC</option>
    <option value=1> MAC </option>
    <option value=2> Rasberry </option>
</select>

don't forget to include the jquery library
this is the javascript code

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript">
    $(function(){
      $("#modalAdd_DDLSample").val(1);
    });
</script>

When the page is loaded, it will automatically set modalAdd_DDSSample value to MAC. Result here

Upvotes: 1

yasin-munshi
yasin-munshi

Reputation: 86

Your JS Code is right but you have issue in the HTML code

Check Out the code example

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
<select id="modalAdd_DDLSample"> 
    <option value=0> PC</option>
    <option value=1> MAC </option>
    <option value=2> Rasberry </option>
</select>
  <script>
    $(function(){
      $("#modalAdd_DDLSample").val("1");
    });
  </script>
  </body>
</html>

Upvotes: 0

Icewine
Icewine

Reputation: 1851

Put the options into the select and write selected in the one you want default.

<select id="modalAdd_DDLSample">
  <option value=0> PC</option>
  <option value=1 selected> MAC </option>
  <option value=2> Rasberry </option>
</select>

Upvotes: 1

Related Questions