确定表单上是否存在字段 [英] determining if a field exists on a form
问题描述
我有一个表单字段(一系列复选框),它是从数据库动态创建的,因此表单上可能不存在该字段(如果数据库中没有匹配的值)。我有一些代码需要根据字段是否存在来执行,如果确实存在,则拉入所选的值。我似乎无法得到javascript来承认这个字段存在。这是我尝试过的:
I have a form field (a series of checkboxes) that's being created dynamically from a database, so it's possible that the field will not exist on the form (if there are no matching values in the database). I have some code that needs to execute based on whether the field exists, and pull in the values that are selected if it does exist. I can't seem to get javascript to acknowledge that this field exists, though. Here's what I've tried:
function displayAction(){
var f = document.adminForm;
var a = f.action;
if(f.prefix.value!="-") {
a = a + '&task=callExclusionDisplay&prefix=' + f.prefix.value;
}
else {
var exclusions = document.getElementById("exclusions");
if (exclusions != null){
alert("exclusions set");
a = a + '&task=callExclusionCreate&prefix=' + f.prefix.value + '&exclusions=' + exclusions.join();
}
}
alert('after if, action is ' + a);
}
代码永远不会通过if语句检查exclusion是否为null,即使我在查看页面时有许多名为exclusions的复选框(id也设置为排除)。问题是!= null,因为它是一组复选框,而不是一个表单元素?我怎样才能让它发挥作用?如果我跳过测试的null,如果数据库没有返回任何匹配的值,则代码会抛出有关排除的错误。
The code never passes the if statement checking to see if exclusions is not null, even though when I look at the page there are a number of checkboxes named exclusions (with the id also set to exclusions). Is the issue with !=null because it's a group of checkboxes, rather than a single form element? How can I get this to work? If I skip the test for null, the code throws errors about exclusions not being defined if the database doesn't return any matching values.
推荐答案
您正在使用 document.getElementById
,但表单元素具有名称。
尝试 f.elements.namedItem(exclusions)
而不是 exclusions!= null
You're using document.getElementById
, but form elements have a name.
Try f.elements.namedItem("exclusions")
instead of exclusions != null
这篇关于确定表单上是否存在字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!