使用javascript时两个字符串相似时显示错误

时间:2016-06-05 11:28:17

标签: javascript html css

我有两列名为' Supervisor`和' Examiner'。 '审查员'使用下拉菜单列出。

我想使用javascript来验证从审查员下拉菜单中选择的值,如果该值与' Supervisor'值,下拉菜单的边框变为红色,表单的提交按钮('生成时间表')将被禁用。

这是我得到的代码,但我没有为我工作(使用dummny数据):

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
    Test
</title>
    <style>
        .error {
            border: 1px solid red;
        }
    </style>
    <script type="text/javascript">
    function validateForm() {
        return checkLecturer();
    }

    function checkLecturer() {
        var e = document.getElementById("examinerID");
        var ex = e.options[e.selectedIndex].innerHTML;

        var sv = document.forms["myForm"]["supervisorID"].value;

        if (sv === ex) {

            document.getElementById('ddldiv').className = "error";
            alert("you can\'t select " + ex);
            return false;
        }
        else {
            document.getElementById('ddldiv').className = "";
            return true;
        }
    }
    window.onload = function () {
        document.getElementById('examinerID').onchange = function () {
            checkLecturer();
        };
    };
</script>
</head>
<body>    
    <form name="myForm" onsubmit="return validateForm();" action="generateSchedule" class="sky-form">
        <table id="t01">
            <tr>
                <th>No.</th>
                <th>Student name</th>
                <th>Project title</th>
                <th>Supervisor name</th>
                <th>Examiner </th>
            </tr>

            <tr>
                <td>1.</td>
                <td>abc</td>
                <td>def</td>
                <td>
                    <input id="supervisor" type="hidden" name="supervisorID" value="Kent" />
                </td>
                <td>
                    <div id="ddldiv" style="width: 150px; height: 22px;">
                        <select name="examinerID" id="lecturerFullname" style="width: 150px; height: 30px;">
                            <option id="examiner" onkeyup="checkLecturer()">Suzy</option>
                            <option id="examiner" onkeyup="checkLecturer()">Kent</option>
                            <option id="examiner" onkeyup="checkLecturer()">John</option>
                        </select>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" name="submit" class="button" value="Submit"  />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

但是,在实际代码中,&#39; Supervisor&#39;和&#39;考官&#39;是从DB动态生成的。

这就是表格的样子:

enter image description here

更新

     <label class="select">
        <center>
        <%
          try{
               //connection
                String query="select s.studentID,s.studentName,s.projecttitle,s.lecturerID, l.lecturerID, l.lecturerFullname from student s JOIN lecturer l ON s.lecturerID = l.lecturerID where rownum <=5";
                Connection con=DriverManager.getConnection(url,username,password);
                Statement stmt=con.createStatement();
               ResultSet rs=stmt.executeQuery(query);
               int i=1;
         %>
        <table id="t01">
        <tr>
        <th>No.</th>
        <th>Student name</th>
        <th>Project title</th>
        <th>Supervisor name</th>
        <th>Examiner </th>
        </tr>
        <% while(rs.next()){ %>
        <tr>
        <td><%= i++ %>.</td>
        <td>
         <input type="hidden" name="studentID" style="" value="<%=rs.getString("studentID") %>">
        <%=rs.getString("studentName") %></td>
         <td style="width:30%;"><%= rs.getString("projectTitle") %></td>
         <td>
        <input id="supervisor" type="hidden" name="supervisorID" style="" value="<%=rs.getString("lecturerID") %>">
        <%=rs.getString("lecturerFullname")%>
        </td> //FOCUS ON HERE

           <td>

        <select name="examinerID" id="lecturerFullname" onchange="checkLecturer()">
        <option selected disabled>Examiners Name</option>
                                                                         <%
         try{
                                                                             //connection
              String query1="select lecturerID, lecturerFullname from lecturer ";
              Connection con1=DriverManager.getConnection(url1,username1,password1);
              Statement stmt1=con1.createStatement();
              ResultSet rs1=stmt1.executeQuery(query1);
               while(rs1.next())
                                                                             {

                                                                         %>

    <option value="<%=rs1.getString("lecturerID") %>"><%=rs1.getString("lecturerID") %> - <%=rs1.getString("lecturerFullname") %></option> //FOCUS ON HERE

         <%
        //closing connection for rs1 and exception  %> 
                                    </select>

        </td>

       </tr>
<%
        //closing connection for rs and exception
%>
</table> 

<footer>
<button type="submit" name="submit" class="button"> Generate schedule</button><br><br>

 </footer></center>

3 个答案:

答案 0 :(得分:0)

为您的选项添加值,并删除ID,ID应该是唯一的,而不是选项元素

[100%] Build Java tests
Buildfile: /home/myaccount/setups/OpenCV/opencv-2.4.13/build/modules/java/test/.build/build.xml

build:

compile:
    [mkdir] Created dir: /home/myaccount/setups/OpenCV/opencv-2.4.13/build/modules/java/test/.build/build/classes
    [javac] Compiling 104 source files to /home/myaccount/setups/OpenCV/opencv-2.4.13/build/modules/java/test/.build/build/classes

jar:
    [mkdir] Created dir: /home/myaccount/setups/OpenCV/opencv-2.4.13/build/modules/java/test/.build/build/jar
      [jar] Building jar: /home/myaccount/setups/OpenCV/opencv-2.4.13/build/modules/java/test/.build/build/jar/opencv-test.jar

BUILD SUCCESSFUL
Total time: 6 seconds
[100%] Built target opencv_test_java
[sudo] password for myaccount: 
Sorry, try again.
[sudo] password for myaccount: 
/bin/sh: 1: cd: can't cd to /home/myaccount/setups/OpenCV/opencv-2.4.13/build
make[2]: *** [3rdparty/libtiff/CMakeFiles/libtiff.dir/depend] Error 2
make[1]: *** [3rdparty/libtiff/CMakeFiles/libtiff.dir/all] Error 2
make: *** [all] Error 2
OpenCV 2.4.13 ready to be used
myaccount@vm-20161023-002:~/setups$

删除onkeyup事件,因为这是一个select元素,请使用onchange事件。

<option value="Suzy">Suzy</option>
<option value="Kent">Kent</option>
<option value="John">John</option>

现在您只需使用

即可提取值
<select name="examinerID" id="lecturerFullname" style="width: 150px; height:30px;" onchange="checkLecturer()">

并在checkLecturer函数中添加错误类,就像你一样,

注意:如果可能的话添加jquery或angular,这将使你的生活变得更加简单

使用jquery:

document.getElementById("lecturerFullname").value

function checkLecturer() {
        // btw this is the name of the drop down not the id
        // var e = document.getElementById("examinerID"); 
        var ex = document.getElementById("lecturerFullname").value;

        var sv = document.forms["myForm"]["supervisorID"].value;

        if (sv === ex) {

            document.getElementById('ddldiv').className = "error";
            alert("you can\'t select " + ex);
            return false;
        }
        else {
            document.getElementById('ddldiv').className = "";
            return true;
        }
    }

答案 1 :(得分:0)

我已经为您提供了一个小例子来说明解决问题的方法:

小提琴:https://jsfiddle.net/csapyn8q/2/

HTML

<table>
  <thead>
    <tr>
      <th>Supervisor</th>
      <th>Examiner</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>
        <select class="dropdown">
          <option>George Smith</option>
          <option>John Doe</option>
        </select>
      </td>
    </tr>
    <tr>
      <td>Jim Hawkins</td>
      <td>
        <select class="dropdown">
          <option>Leslie Bell</option>
          <option>Jim Hawkins</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

JS

function validate(e) {
  var select = e.target;
  var index = select.selectedIndex;
  var examiner = select.children[index].textContent;
  var supervisor = select.parentNode.parentNode.children[0].textContent;

  if (examiner === supervisor) {
    select.className = select.className + " error";
  } else {
    select.className = select.className.replace(" error", "");
  }
}
var dropdowns = [].slice.call(document.querySelectorAll(".dropdown"));
dropdowns.forEach(function(dd) {
  dd.addEventListener("change", validate);
});

CSS

.error {
  border: 1px solid red;
}

我们实际上正在做的是绑定我们的下拉列表,在每次更改时调用validate()函数,并添加红色边框,以防审查员和主管相同。

答案 2 :(得分:0)

你应该试试这个:

function validateForm() {
    return checkLecturer();
}  

function checkLecturer(arg) {
    var examinerValue = arg.value;
            console.log(examinerValue);
    var sv = document.forms["myForm"]["supervisorID"].value;

    if (sv === examinerValue) {

        document.getElementById('lecturerFullname').className = "error";
        alert("you can\'t select " + ex);
        document.getElementById('submit').setAttribute("disabled", "true");
        return false;
    }
    else {
    document.getElementById('submit').removeAttribute("disabled");
        document.getElementById('lecturerFullname').className = "";
        return true;
    }
}
window.onload = function () {
    document.getElementById('examinerID').onchange = function () {
        checkLecturer();
    };
};

html中不应该有多个id。这是错误的做法。