验证下拉列表使用javascript从php回显到html?

时间:2011-10-25 19:11:38

标签: php javascript mysql html forms

好的,这个问题的标题可能有点令人困惑,我会试着向你解释一下: 我有一个包含多个表单字段的数组的php文件,如下所示:

$var = array(0 => '<input type=....>', 1=> '<input type=....>');

我创建了一个while循环来遍历数组以在表中显示它们,如下所示:

echo '<table>';
  while($row = mysql_fetch_array($result)){
    $num = $row['fieldId'];
    $field = $num.' '.$row['field'];
    echo '<tr><td>'.$field.'</td>';
    echo '<td>'.$var[$q].'</td></tr>';
    echo '<tr><td>&nbsp;</td></tr>';
    $q++;
  }; echo '</table>';

我将这个php文件包含在一个html文件中,这样我就可以得到一个包含两列的表,第一个用数据库中的$ field,第二个用$ var [$ q]这是从$获取的一些输入字段var数组。 信不信由你真正有效,现在问题是在$ var数组里面我有一个<select>字段有多个选项,我想用一些javascript来验证那个字段,但由于某种原因我无法得到<option value="SOMEVALUE">中指定的值。我不知道为什么,但我不能,有一件事我觉得奇怪的是,在那个$ var数组我有一些单选按钮,我 CAN 用javascript验证。

更多信息: 包含php文件的html文件包含:

<html>....
<form name="mainForm">
  <?php
    include 'myPhpFile.php';
  ?>
  <input type="button" name="btnNext" onclick="functionToValidate();">
</form>
...</html>

所以基本上当我包含我的php文件时,它创建一个表并添加字段,用mysql数据库填充它们,并使用上面显示的$ var数组输入一些字段 一切正常,但问题是,当我点击下一个按钮时,它调用一个javascript函数来验证字段,一切正常,直到它到达<select>输入, 我可以验证单选按钮,文本字段和textareas但我无法验证那些<select>

这是我正在使用的javascript函数:

function myFunctionNameHere(){
if(!document.mainForm.p1_1[0].checked && !document.mainForm.p1_1[1].checked)
      alert("1 - some warning here");
    else if(!document.mainForm.p1_2[0].checked && !document.mainForm.p1_2[1].checked)
      alert("2 - some warning here");
    else if(!document.mainForm.p1_3[0].checked && !document.mainForm.p1_3[1].checked)
      alert("3 - some warning here");
    else if(!document.mainForm.p1_4[0].checked && !document.mainForm.p1_4[1].checked)
      alert("4 - some warning here");
    else if(!document.mainForm.p1_5[0].checked && !document.mainForm.p1_5[1].checked)
      alert("5 - some warning here");
    else if(!document.mainForm.p1_6[0].checked && !document.mainForm.p1_6[1].checked)
      alert("6 - some warning here");
    else if(document.mainForm.p1_7.value == "")
      alert("7 - some warning here");
    // this condition does not work:
    else if(document.mainForm.p1_8.selectedIndex == 0)
      alert("8 - some warning here);
   // can't get the selectd field from the html select field
    else
      window.location = "OTHERPAGE.html";
}

这几乎就是函数所做的,所有条件都有效,除了那个我发表评论的条件。 (我还在学习,所以不要嘲笑我的代码......拜托。)

很抱歉我实际上解决了这个问题,我的php数组的html代码中有一些错误。现在它确实有效。 感谢。

1 个答案:

答案 0 :(得分:0)

这是您在javascript中访问选择值的方式:

<form name="mainform">
    <select name="dropbox_select">
        <option value="value0">option0</option>
        <option value="value1">option1</option>
        <option value="value2">option2</option>
    </select>
</form>

document.forms.mainform.dropbox_select.options[0].value
document.forms.mainform.dropbox_select.options[1].value
document.forms.mainform.dropbox_select.options[2].value