Jquery fill text area with linebreak and nothin if no data

  • A+
Category:Languages

I am trying to show JSON data in a textbox. Data is in this format:

address{ "street":"1st main Road" "building_name":"Florence" "Floor":"" "city":"New York" } 

I have tried this:

$('#id_address').val(address.street+'/n'+address.building_name+'/n'+address.Floor+'/n'+address.city); 

But issue is that if there is no data in Floor then there will a linebreak between floor and city. How to avoid line breaks if there is no data in address line?


You can use Object.keys(address) to get the keys of the address property and loop over that and check if the value is empty or not. Then prepare the value for the textarea accordingly based on the condition address[key] !== ''. For more perfection use a condition index+1 !== allKeys.length to prevent /n for the last item.

var address = {   "street":"1st main Road",   "building_name":"Florence",   "Floor":"",   "city":"New York" };  var textValue = ''; var allKeys = Object.keys(address); allKeys.forEach(function(key, index){   if(address[key] !== ''){     textValue += address[key];      if(index+1 !== allKeys.length){        textValue += '/n';      }   } }); console.log(textValue); $('#id_address').val(textValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id='id_address' rows='5'></textarea>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: