javascript - 选择标签不适用于表格中的提交按钮

标签 javascript html

我有一张 table ,上面有一个 <tr>和两个<td>在它里面。第一个<td>显示一个下拉列表,其中包含用户选择的书籍列表,第二个 <td>有一个按钮,选择一本书后会触发一个功能。该按钮工作正常,但问题是,即使该选项设置为“选择书籍”标题,它也会触发该功能,而它应该仅在选择书籍名称而不是要求用户选择书籍的标题时才起作用。书。

<table>
  <tr>
    <td>
      <div class="" style="position:relative" >
        <select id="test">
          <option value="" disabled="disabled" selected="selected">Select Book</option>

          <?php
            //API calls happening to get the list of books
          ?>

          <option value="<?php //echo id of each book; ?>"><?php //echo name of books ?></option>
        </select>
      </div>
    </td>

    <td>
      <input type="submit" value="Add to Cart" onclick="addBook()">
    </td>
  </tr>   
</table>

这是我在单击按钮时运行的 JavaScript。

function addBook() {

        //getting product name and append it in the report table
        var BookName = $("#test option:selected").text();
        var tr = "<tr><td>" + BookName + "</td></tr>";
        $("#SecondTable").append(tr);
    }

正如你在上面的JS中看到的,我还将打印“Select Book”,因为它假设“Select Book”是一本书名!

最佳答案

您可以先检查所选选项是否被禁用,然后尝试加载 View ,请检查我编辑过的函数...

function addBook() {
//getting product name and append it in the report table
var selectedbook = $("#test option:selected");
if(!selectedbook.is(":disabled"))
{ 
  var BookName = selectedbook.text();
  var tr = "<tr><td>" + BookName + "</td></tr>";
  $("#SecondTable").append(tr);
}
}

关于javascript - 选择标签不适用于表格中的提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28000705/

相关文章:

javascript - 如何使用firebug查看实时JS调用

html - 在 iframe 中隐藏图像

jquery - 重叠 <div>

javascript - 在背景中缩放图片,站点引用

javascript - jquery animate 让其他元素跳舞

php - ajax 接收到的字符串与从 php 发送的字符串不同

javascript - 使用 NVD3.js 构建有焦点的折线图。为什么我的焦点栏坏了

javascript - 将日期添加到 Date 对象

javascript - 将 JS 变量传递给 getElementById

html - 如何设置要固定的背景?