如果数组值为空,则不添加组合器

时间:2019-03-14 15:24:36

标签: jquery

我有一个文本合并器,您可以在其中添加文本区域并水平合并所有行。您可以选择要在文本之间插入的连字符。但是,当textarea为空时,尽管当前它不显示,但我不希望它显示连字符。如何确保当一行的值为空时,该行不显示连字符?

HTML:

<head>
<title>Column Combiner</title>
<script type="text/javascript" src="assets/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="assets/js/global.js"></script>
<link rel="stylesheet" href="assets/css/main.css">
</head>
<body>
<table>
<tr class="tables"></tr>
</table>
<form method="get">
<input id="add" type="button" value="Voeg veld toe">
<input class="combiner" id="combiner" type="text" name="combiner">
<input id="get" name="submit" type="button" value="Combineer">
<div id="values"></div>
</form>
</body>

jQuery:

$(document).ready(function() {
//add input fields
var field_count = 0;
$('#add').click(function(){
    $('#get').show();
    $('#combiner').show();
    field_count++;
    $('table tr.tables').append('<td><textarea id="textarea" class="inputfield" cols="40" rows="15" name="tname' + field_count + '"></textarea></td>');
});

//connect results with hyphen
$('#get').click(function() {
    $('#values').html('<textarea cols="40" rows="15">' + getCombinedValues() + '</textarea>');
});
});

function getCombinedValues() {
var lines = [];

//split each text field to an array of lines
$('.inputfield').each(function() {
    lines.push($(this).val().split('\n'));
});

//switch rows and columns(horizontal now)
lines = lines.reduce((prev, next) => next.map((item, i) =>
    (prev[i] || []).concat(next[i])
), []);

//combine each line with the combiner value
var combiner = $("input.combiner").val();
lines = $.map(lines, function(e) {
    return e.join(combiner);
});

console.log(lines);

//combine all lines to a single string
return lines.join("\n");

}

1 个答案:

答案 0 :(得分:1)

使用以下命令检查textarea的值:

var myval = $(mytextarea).val()

然后使用if来检查值是否具有长度:

if(myval.length > 0){
 //Here your code when have content
}