Home > Net >  ajax response not proper binding in select option value jQuery
ajax response not proper binding in select option value jQuery

Time:10-07

  • I'm trying to get value from ajax to HTML but it's not correctly binding in the dropdown even I tried in the textbox it's not showing. I tried to add some static value it's also not showing.
  • Ajax response is properly getting in the console but when I am trying to bind in the HTML its not show proper.

enter image description here

  • HTML code:
<div  id="largeModal" tabindex="-1" role="dialog">
   <div  role="document">
      <div >
         <div >
            <h4  id="defaultModalLabel"></h4>
         </div>
         <div >
            <form method="POST" action="" accept-charset="UTF-8" >
               <label>Room Type</label>
               <h1  ></h1>
               <!-- <input type="text" > -->
               <select  tabindex="-98">
                  <option>-Select Room type-</option>
               </select>
               <div >
                  <input  type="submit" value="SAVE">
                  <button  data-dismiss="modal" type="button">CLOSE</button>    
               </div>
            </form>
         </div>
      </div>
   </div>
</div>
  • JQuery code:
$(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;  
});
});
  • AJAX response
[
  {
    "id": "1",
    "hotel_name": "Hotel Bharat",
    "room_type": "4,1,2",
    "cp_price": "98"
  },
  {
    "roomtype": "Deluxe Room"
  },
  {
    "roomtype": "Luxury Room"
  },
  {
    "roomtype": "Family room"
  }
]

CodePudding user response:

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>'
         );
      }
});
  • Related