[英]Jquery closest function with class not alerting in javascript code become undefined value
I have a code that waste my few hours. 我有一个浪费我几个小时的代码。 Here jquery closest with class not working in html table and not passing value.
在这里,与类最接近的jQuery在html表中不起作用并且不传递值。 I use html, javascript, jquery and php here.
我在这里使用html,javascript,jquery和php。 Can anyone rewrite the code freshly.
任何人都可以重新编写代码。
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "test.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
}
?>
Assuming that you want the alert to show the value "A" , JavaScript is not the issue. 假设您希望警报显示值“ A” ,那么JavaScript就不是问题。 The problem is that you are printing the whole page, even when the request is POST .
问题是,即使请求是POST ,也要打印整个页面。
Instead, you should conditionally print the page only when the request is not POST, or when it does not contain subans property. 相反,仅当请求不是POST或不包含subans属性时,才应有条件地打印页面。 Like this:
像这样:
<?php
if (isset($_POST['subans'])) {
$subans = $_POST['subans'];
if (!empty($subans)) {
echo $subans;
}
} else {
?>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function () {
$(".senddata").on("click", function () {
console.log(this)
var subans =
$(this).closest(".datadivision").find("input[name='subans']").val();
var data = 'subans=' + subans;
$.ajax({
type: "POST",
url: "stack.php",
data: data,
cache: false,
success: function (html) {
alert(html);
}
});
});
});
</script>
<table>
<tr class="datadivision">
<input type="hidden" name="subans" value="A" >
<td class= "senddata">
<label><input type="radio" name="subans" value="something"> This is a
line</label>
</td>
</tr>
</table>
<?php
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.