我有一个非常简单的函数,该函数应查看表单上的值,如果它不是null或为空,则添加一些文本,然后对返回的var进行卡拉OK,然后将其保存以供以后使用,稍后将它们一起删除,跳过任何带空值的值。在此特定表单上,我有11个文本框,尽管我仅从将其扩展为两个开始,但稍后我将添加所有11个文本框。
我的(第一个)问题是,在将值分配给var时出现语法错误。如果有更多方法可以更好地做到这一点,我不会感到惊讶。
function CompileEm() {
document.getElementById("txtFileNote").value = null
var s1 = document.getElementById("txt1").value
if (s1 !== null && s1 !== '') {
document.getElementById("txtFileNote").value = "1st Entry: " + s1 + '\n'
}
var s2 = document.getElementById("txt2").value
var t2 = document.getElementById("txtFileNote").value
if ((isNullOrEmpty(s3)))
if (s2 !== null && s2 !== '') {
document.getElementById("txtFileNote").value = t2 + '\n' + "2nd Entry: " + s2 + '\n'
}
}
我承认javascript不是我的强项。小心!
答案 0 :(得分:0)
希望这些评论有意义:
function CompileEm()
{
document.getElementById("txtFileNote").value = ''; // use empty string to start with
var total = 11; // you should really get this dynamically, like using document.querySelectorAll('XXX').length, where 'XXX' is the CSS query that targets all your boxes. probably something like 'input[type="text"]' but I don't know what your HTML looks like.
for (var i = 0; i < total; i++)
{
var text = document.getElementById("txt" + i).value; // this assumes you've ID'd all your textboxes like txt1, txt2, txt3, ...
if (text) // if not null or empty
{
// concatenate with +=
document.getElementById("txtFileNote").value += "Entry #" + i + ": " + text + "\n";
}
}
}
编辑:
如果文本框ID的格式不正确,则必须遍历document.querySelectorAll('XXX')
的数组结果:
function CompileEm()
{
document.getElementById("txtFileNote").value = ''; // use empty string to start with
var allTextBoxes = document.querySelectorAll('input[type="text"]'); // modify this selector to match your needs
for (var i = 0; i < allTextBoxes.length; i++)
{
var textBox = allTextBoxes[i];
if (textBox.value) // if not null or empty
{
// concatenate with +=
document.getElementById("txtFileNote").value += "Entry with ID " + textBox.id + ": " + textBox.value + "\n";
}
}
}