[英]How can I get selected row using jQuery?
This is my table row within the tbody
of my table.这是我表格中的
tbody
行。 I get dropdown value, text value but I can't get selected row value.我得到下拉值,文本值,但我无法获得选定的行值。 My row value returns "undefined".
我的行值返回“未定义”。
$(document).on("click", "#skorKartDegerle", function() { $("#modal_evaluation").modal("show"); }); $(document).on("click", "#btnKaydet", function() { var arrList = []; var isEmptyAnswer = false; $("#evaluationTable > tbody > tr").each(function() { var line = $(this).find(".answerLine").val(); var ddlVal = $(this).find(".answerddl").val(); var txtVal = $(this).find(".answertxt").val(); var obj = '{"line":"' + line + '","ddlVal":"' + ddlVal + '","txtVal":"' + txtVal + '"}'; arrList.push(obj); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr class="answerLine" value="2"> <td>FR002</td> <td>Koton Mağazacılık</td> <td>1800</td> <td>A</td> <td>Kabul</td> <td class="select" value="0"> <select class="answerddl"> <option value="1">Kabul</option> <option value="2">Ret</option> </select> </td> <td><input type="text" class="answertxt"></td> </tr> </tbody> </table>
Part of the issue is because tr
elements do not have a value
attribute.部分问题是因为
tr
元素没有value
属性。 To do what you require you could use a data
attribute instead, to store custom metadata on the element.要执行您需要的操作,您可以改用
data
属性,将自定义元数据存储在元素上。 The other part is that this
is a reference to the tr
element.另一部分是
this
是对tr
元素的引用。 You're then calling find()
on the element you're looking to target, so it will not be found as that method looks for descendants only.然后,您在要定位的元素上调用
find()
,因此不会找到它,因为该方法仅查找后代。
In addition it's worth noting that you can make the logic more succinct by using map()
to build the array instead of explicitly looping with each()
and also that it would be better practice to store objects in the array and only JSON encode it before transferring via AJAX.此外值得注意的是,您可以通过使用
map()
构建数组而不是使用each()
显式循环来使逻辑更简洁,而且最好将对象存储在数组中,并且之前只有 JSON 对其进行编码通过 AJAX 传输。
$(document).on("click", "#btnKaydet", function() { var isEmptyAnswer = false; let arrList = $("#evaluationTable > tbody > tr").map((i, tr) => { let $tr = $(tr); return { line: $tr.data('value'), ddlVal: $tr.find(".answerddl").val(), txtVal: $tr.find(".answertxt").val() } }).get(); console.log(arrList); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="evaluationTable"> <tbody> <tr class="answerLine" data-value="2"> <td>FR002</td> <td>Koton Mağazacılık</td> <td>1800</td> <td>A</td> <td>Kabul</td> <td class="select" value="0"> <select class="answerddl"> <option value="1">Kabul</option> <option value="2">Ret</option> </select> </td> <td><input type="text" class="answertxt"></td> </tr> </tbody> </table> <button id="btnKaydet">Click me</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.