我在页面中动态创建了表单。因此,一旦选中该表单中的复选框,我想使用jQuery发布表单。我仍然无法正确选择表单。
HTML code:
<tbody>
<tr>
<form id="" class="recmndation">
<td>sdfdsfdsfdsfsdfsdfsdfsd</td>
<td>
<input class="checkboxes" type="checkbox" name="Luxury Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Honeymoon Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Dive Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Surf Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Spa Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Over-night Resorts" />
</td>
<input type="hidden" name="hotel_id" value="2" />
</form>
</tr>
<tr>
<form id="" class="recmndation">
<td>tests</td>
<td>
<input class="checkboxes" type="checkbox" name="Luxury Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Honeymoon Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Dive Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Surf Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Spa Resorts" />
</td>
<td>
<input class="checkboxes" type="checkbox" name="Over-night Resorts" />
</td>
<input type="hidden" name="hotel_id" value="1" />
</form>
</tr>
</tbody>
jQuery代码:
<script>
$('.checkboxes').on('change', function() {
var val = $(this).parents('.recmndation').attr('id');
alert(val);
});
</script>
alert
消息始终显示&#34; undefined&#34;并且控制台中没有错误。
PHP代码:
<?php
if (!empty($hotel_list)) {
foreach ($hotel_list as $htls) {
?>
<tr>
<form id="<?php $htls->name ?>" class="recmndation">
<td><?php echo $htls->name; ?></td>
<?php
if ($rcmnd_list) {
foreach ($rcmnd_list as $rcl) {
?>
<td><input class="checkboxes" type="checkbox" name="<?php echo $rcl->rec_name; ?>" /></td>
<?php
}
}
?>
<input type="hidden" name="hotel_id" value="<?php echo $htls->hotel_id; ?>" />
</form>
</tr>
<?php
}
}
?>
答案 0 :(得分:1)
试试这个,它应该有效:
<script>
$(document).ready(function(){
$('.checkboxes').on('change', function() {
var val = $(this).closest('.recmndation').attr('id');
OR YOU CAN USE PROP
var val = $(this).closest('.recmndation').prop('id');
alert(val);
});
});
</script>
答案 1 :(得分:1)
首先,
1)您的表单ID为空!所以,你只会在警报中变空。
其次,
2)请在<table>
内提供<form>
,而不是相反。
您的代码格式应如下所示:
<form id="two" class="recmndation">
<table>
<tr>
<td>
<td><input class="checkboxes" type="checkbox" name="Luxury Resorts" /></td>
<td><input class="checkboxes" type="checkbox" name="Honeymoon Resorts" /></td>
<td><input class="checkboxes" type="checkbox" name="Dive Resorts" /></td>
<td><input class="checkboxes" type="checkbox" name="Surf Resorts" /></td>
<td><input class="checkboxes" type="checkbox" name="Spa Resorts" /></td>
<td><input class="checkboxes" type="checkbox" name="Over-night Resorts" /></td>
<td><input type="hidden" name="hotel_id" value="1" /></td>
</tr>
</table>
</form>
<script>
$('.checkboxes').on('change', function() {
var val = $(this).parents('.recmndation').attr('id');
alert(val);
});
</script>