javascript - 使用 JQuery 提交动态表单

标签 javascript php jquery mysql

我不太确定我能做到这一点,但值得一试。

我有一个表,其中至少有 10 个项目来自 Mysql 数据库。它们是您可以出价的项目。这个想法是每一行(因此,每个项目)都有一个可以单击以输入出价的按钮。此按钮会打开一个弹出窗口,其中包含用于输入出价的文本字段和用于提交表单的按钮。

为了识别用户出价的项目,我需要它的 ID 以及出价金额。金额真的很容易获得,但我在商品 ID 上苦苦挣扎。

这是我的:

$(document).ready(function(){
 $(".show").click(function() {
   $("#popup").show();
   	  var $id = document.getElementsByClassName('show')[0].value;
   	  console.log($id);
   	  $("#jugador").val($id);
 });

 $("#close, #submit").click(function() {
   $("#popup").hide();
 });
});
#popup {
  position: relative;
  z-index: 100;
  padding: 10px;
}

.content {
  position: absolute;
  z-index: 10;
  background: #ccc;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #000;
  z-index: 5;
  opacity: 0.4;
}
<td><button class="show" id="bid" value="<?php echo $row2["id"];?>"><img src="pictures/bidIcon.png" width="30" height="30"></button></td>

/*Popup*/

<div id="popup" style="display: none;">
 <div class="overlay"></div>
  <div class="content">
    <header>
     <div id="close">✖</div>
    </header>
    <form name="form1" method="post" action="bid.php">
     <fieldset>
      <label for="bid">Bid:</label>
      <input type="text" name="bidAmount" id="bidAmount" size="8" />
      <input type="hidden" name="item" id="item" />
      <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
    <footer>
    <button type="button" id="submit">Bid Now</button>
    </footer>
   </form>
  </div>
</div>

我已经尝试了一段时间,但没有成功。无论我点击哪个按钮,我总是会得到第一个元素的项目 ID。

我想要的是否可行?这是正确的方法吗?我应该使用不同的吗?

非常感谢。

最佳答案

只需更改这一行:

var $id = document.getElementsByClassName('show')[0].value;

对此:

var $id = $(this).val();

问题在于,使用 document.getElementsByClassName('show')[0].value 您正在查询第一次出现的 .show 按钮。使用 $(this) 而不是您将访问当前单击的按钮。

JQuery 将事件绑定(bind)到您附加事件的目标,因此 this 将始终是对事件目标的引用。使用 $(this) 将创建目标元素的 jQuery 对象,允许将 jQuery 函数应用于该元素。

作为旁注,您不应该重复元素 ID。每个 id 在 html 文档中都必须是唯一的,因此最好为每个按钮设置不同的 id。

希望对您有所帮助。

关于javascript - 使用 JQuery 提交动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50467007/

相关文章:

javascript - 在隔离作用域指令中,在作用域上定义变量和在 Controller 上定义变量之间有什么区别吗?

php - Laravel 4 Migration 添加外键时出现语法错误

javascript - 导航元素的滑动背景仅适用于 2 个元素,不能更多

javascript - 像 k2.pl 一样平滑的水平滚动

javascript - 将 HTML 中的对象分组以进行 Javascript 操作

javascript - 将 JSON 文件导入运行在 Grunt 服务器上的 Angular 应用程序

php - 如何将 php 变量用于 .css 文件

php - 如何从表中的自动增量获取值并将其用于另一个表?

jQuery val() 返回值返回函数?

javascript - 如何从对象数组更新单个值然后更新状态