Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery fill text area with linebreak and nothin if no data

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?

like image 642
Sapna Sharma Avatar asked May 19 '18 11:05

Sapna Sharma


1 Answers

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>
like image 123
Ankit Agarwal Avatar answered Nov 14 '22 21:11

Ankit Agarwal