-1

I have an ajax that return values from an another page, I want to target a value that matches from the value ajax returns and select it on the tag.

Here's my code so far:

        success: function(data) {
            $("select[name='account_type']").val(data.account_type).prop('selected', true);
        },

I want to target this:

   <select class="form-control">
          <option value="0">DEBIT</option>
          <option value="1">CREDIT</option>
   </select>

So if the ajax call returns value of 1, then CREDIT should be :selected

xcomsw
  • 155
  • 2
  • 3
  • 14

4 Answers4

1

For ajax:

success: function(data) {
            $("select[name='account_type']").val(data.account_type).prop('selected', true);
        },

For HTML

<select name="account_type" class="form-control">
          <option value="0">DEBIT</option>
          <option value="1">CREDIT</option>
   </select>
Dhrutika Rathod
  • 540
  • 2
  • 6
  • 22
1

Set name of select element as you are using it

<select name="account_type" class="form-control">

and .prop() is not required so just remove it.

$("select[name='account_type']").val(1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select name="account_type" class="form-control">
  <option value="0">DEBIT</option>
  <option value="1">CREDIT</option>
</select>
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

prop is not needed:

 success: function(data) {
            $("select[name='account_type']").val(data.account_type);
        },

then give name else use $("select.form-control")

   <select name=account_type class="form-control">
          <option value="0">DEBIT</option>
          <option value="1">CREDIT</option>
   </select>
jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22
0

Your HTML :

<select class="form-control" name="account_type">
  <option value="0">DEBIT</option>
  <option value="1">CREDIT</option>

Your ajax response function :

success: function(data) {
$('select[name="account_type"]').find('option[value=data.account_type]').attr("selected",true);

},

Justinjs
  • 130
  • 7