简体   繁体   中英

Add new object into existing json

I have dropdown like this.

<input id="tripFrom" type="text" 
   angular-select2="{type:'typeahead',placeholder:'- Select -'}" 
   select-typeahead-params="{removeTripId:currentTrip.customerDetails.tripToID, type:'startsFrom'}" 
   select-typeahead-url="getTripFrom('startsFrom')"
   ng-model="currentTrip.fromTripID" 
   select-text="currentTrip.startingAreaName" 
/>

For this dropdown I am getting data like this:

{"success":true,
 "items":[
   {"id":56565,"text":"andra"},
   {"id":56568,"text":"tamilnadu"}
 ]
}

My question is when I add some new text in dropdown (which is not present in dropdown )I need to create its as new object inside of items .

When I blur the dropdown new added data should be displayed in that dropdown as selected.

This what I have added:

$('#s2id_autogen8_search').change(function(){
  var data=[];var items={};
  var newAddress=$('#s2id_autogen8_search').val();
  var newId=Math.floor(Math.random()*1000000+1);
  var newTripAddress={id:newId,text:newAddress}
  items.id=newId;
  items.text=newAddress;
 data.push(items)
  /*$("#tripFrom").select2({
    data : newTripAddress})*/
});

But my input is not displaying when I blur it. What I did wrong?

Try using the blur instead of the change event.

$('#s2id_autogen8_search').change(function(){

// use this instead 

$('#s2id_autogen8_search').on('blur', function(){

It might be as simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM