Why does javascript onchange event only work in first modal from a data table
您好,感谢您抽出宝贵时间阅读我的问题。
这是我的第一篇文章,我尽量做到全面,并按照发帖的预期要求!
我的设置
我有一个从 mysql 数据库填充的数据表,每一行都有一个"编辑"按钮。
"编辑"按钮打开一个包含该行数据的模式。这一切正常。
在模态表单中,我有一个带有"onchange"事件的"select"下拉元素来触发消息。
问题
从第一个模式中(从第一个表格行的"编辑"按钮打开)
消息被触发没有问题 - 在链接到第一行的模式窗口中。
但是,如果我单击任何其他行的"编辑"按钮以启动它的模式 - 然后我更改"选择"下拉值,则不会显示消息 - 好像没有处理 javascript 函数一样。
我目前的研究
花时间在 Stack Overflow 上搜索和搜索后,我认为问题可能与非唯一 ID 或类名有关 - 并且可能每个记录行的它们应该不同?
我尝试通过使用行的 ID 号动态生成 ID 名称和类名称来实现这一点 - 所以每个模式都有自己的唯一 ID 用于"选择"元素 - 但这并没有解决问题。
我还认为这可能是脚本保留旧数据的缓存问题,但是如果我第一次单击第一行,或者单击其他几个后单击第一行,这并不重要在它之前的行,它只是成功处理 onchange 事件的第一行。
我的文件
index.php(显示数据表和"编辑"按钮)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <table> <thead> <th>Fruit ID</th> <th>Fruit Name</th> <th>Action</th> </thead> <tbody> <tr> <td><?php echo $row['fruitID']; ?></td> <td><?php echo $row['fruitName']; ?></td> <td> " data-toggle="modal" class="btn btn-warning">Edit <?php include('button.php'); ?> </td> </tr> </tbody> </table> |
button.php(带有'select'元素和消息div的模态内容)
1 2 3 4 5 6 7 8 9 10 11 12 13 | " tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <select class="mySelector" id="mySelector" name="mySelector" onchange="show_value()"> <option value="Apple">Apple</option> <option value="Orange">Orange</option> <option value="Banana">Banana</option> <option value="Mango">Mango</option> </select> |
脚本(在 button.php 底部触发消息)
1 2 3 4 | function show_value() { selected_value = document.getElementById("mySelector").value; document.getElementById("result").innerHTML ="Selected value is"+selected_value; } |
你可以通过使用 this.id 在 javascript 中传递当前 id 这是一个例子
1 | <input type="text" id="username" class="form-control" name="username" onchange="formhelper(this.id)"> |
现在在你的函数中你可以使用这个id作为你喜欢的例子
1 2 3 4 5 | function formhelper(currentID) { consolele.log('the current id is ' + currentID); } |
你也可以使用这个例子的 php 标签动态地创建 id
1 | id="<?= $value['id']?>" |
您只需将您的 id 作为参数传递,如下所示。由于您已经拥有来自 $row[\\'fruitID\\'] 的唯一 id,因此您可以将该数字附加到每个 id 上,这样它们也将是唯一的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | " tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <select class="mySelector" id="mySelector<?=$row['fruitID']?>" name="mySelector" onchange="show_value('mySelector<?=$row['fruitID']?>', 'result<?=$row['fruitID']?>')"> <option value="Apple">Apple</option> <option value="Orange">Orange</option> <option value="Banana">Banana</option> <option value="Mango">Mango</option> </select> "> function show_value(input_id, output_id) { selected_value = document.getElementById(input_id).value; document.getElementById(output_id).innerHTML ="Selected value is"+selected_value; } |
您可以轻松获取选择元素的值...
1 2 3 | function show_value(e) { // e param is the event selected_value = e.value; // use e.val to get the event target value (in this case the select element value) } |
在我尝试处理显示值的最佳方式时请耐心等待