我有一个非常简单的函数,应该在我的表单上查看一个值,如果它不是null或为空,添加一些文本和carraige返回到该var并保存以供以后使用,以便稍后将其中的几个放在一起,使用空值跳过任何一个。我在这个特定的表单上有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不是我的强项。 HALP!
希望评论有意义:
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";
}
}
}