Jquery使用换行符填充文本区域,如果没有数据则填充文本区域

时间:2018-05-19 11:10:34

标签: javascript jquery html

我试图在textbox中显示JSON数据。 数据采用以下格式:

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

我试过这个:

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

但问题是,如果楼层中没有数据,那么楼层和城市之间会有一个换行符。如果地址行中没有数据,如何避免换行?

5 个答案:

答案 0 :(得分:6)

您可以使用Object.keys(address)获取address属性的键并循环遍历该值并检查该值是否为空。然后根据条件textarea相应地准备address[key] !== ''的值。为了更加完美,请使用条件index+1 !== allKeys.length来阻止最后一项\n



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>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

我知道你已经接受了答案,但无论如何,这是我的解决方案。

我建议你采用一体化解决方案,不要使用任何循环或复杂的东西 只有现有的功能/方法,我认为这是最简单的解决方案!...而且它是vanilla Javascript!

请参阅下面的代码中的评论:

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

// Get values from the object, join them with new lines, and replace the multiple new lines
var textValue = Object.values(address).join('\n').replace(/[\n]+/g, '\n');
// Display in console
console.log(textValue);

我希望它有所帮助。

答案 2 :(得分:2)

我会推荐

$('#id_address').val([
  address.street,
  address.building_name,
  address.Floor,
  address.city
].filter(Boolean).join("\n"));

甚至

const keysToShow = ["street", "building_name", "Floor", "city"];
$('#id_address').val(keyToShow.filter(k => k in address).map(k => address[k]).join("\n"));

如果您想保证值的预期顺序,请不要使用Object.keysObject.valuefor … in循环。

答案 3 :(得分:1)

我会使用追加而不是硬编码 - 所以将来你可以有更多的价值观:

例如:

myObj = { "name":"John", "age":30, "car":null };

$.each(myObj,function(data,value){
if (value !== null ) {
    $('#addres').append(data + '-' + value + '<br>');
}
});

答案 4 :(得分:1)

  `
var html ='';
if(address.street != ''){
   html = html + address.street +'\n';
}if (address.building_name != ''){
   html = html + address.building_name +'\n';
}if (address.Floor != ''){
   html = html + address.Floor +'\n';
}if (address.city != ''){
   html = html + address.city;
}
$('#id_address').val(html);

`
Try this one