Jaydev Vara
Jaydev Vara

Reputation: 45

ajax response not proper binding in select option value jQuery

enter image description here

<div class="modal fade" id="largeModal" tabindex="-1" role="dialog">
   <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h4 class="modal-title1" id="defaultModalLabel"></h4>
         </div>
         <div class="modal-body">
            <form method="POST" action="" accept-charset="UTF-8" >
               <label>Room Type</label>
               <h1 class="modal-title1" ></h1>
               <!-- <input type="text" class="apple"> -->
               <select class="apple" tabindex="-98">
                  <option>-Select Room type-</option>
               </select>
               <div class="modal-footer">
                  <input class="btn  btn-lg bg-indigo waves-effect" type="submit" value="SAVE">
                  <button class="btn  btn-lg bg-black waves-effect" data-dismiss="modal" type="button">CLOSE</button>    
               </div>
            </form>
         </div>
      </div>
   </div>
</div>
$(document).off('click', '.hotel_add').on('click', '.hotel_add', function () {
var id = $(this).attr('id');
var pos = $(this).closest('.hotel-result').data('pos-id');
$.get("<?php echo base_url('hotel/hotelDataGet') ?>/" + id + '/' + pos, function (result) {
var data = JSON.parse(result)
$.each(data,function(index,value){
console.log(value);
$('#defaultModalLabel').html(value.hotel_name);
$('.apple').append('
<option value="'+value['roomtype']+'">'+value['roomtype']+'</option>
');
});
$("#largeModal").modal();
//debugger;  
});
});
[
  {
    "id": "1",
    "hotel_name": "Hotel Bharat",
    "room_type": "4,1,2",
    "cp_price": "98"
  },
  {
    "roomtype": "Deluxe Room"
  },
  {
    "roomtype": "Luxury Room"
  },
  {
    "roomtype": "Family room"
  }
]

Upvotes: 2

Views: 559

Answers (1)

Ryan Wilson
Ryan Wilson

Reputation: 10765

hotel_name only exists on the first object of your response, and the roomtype does not exist in your fist object, so you can change to this:

$.each(data,function(index,value){
     //check to see if this object has the property "hotel_name"
     if(value.hasOwnProperty("hotel_name"){
         $('#defaultModalLabel').html(value.hotel_name);
     }
     //check to see if this object has the property "roomtype"
     if(value.hasOwnProperty("roomtype") {
         $('.apple').append(
             '<option value="' +
              value['roomtype'] + 
              '">' +
              value['roomtype'] +
              '</option>'
         );
      }
});

Upvotes: 1

Related Questions