I have a code that waste my few hours. Here jquery closest with class not working in html table and not passing value. I use html, javascript, jquery and php here. 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. The problem is that you are printing the whole page, even when the request is POST .
Instead, you should conditionally print the page only when the request is not POST, or when it does not contain subans property. 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
}
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.