我需要在<td>
元素内添加文本。我可以通过AJAX正确获取该值,但是我会绕圈去尝试将其添加到<td>
单元格中。
table
是高尔夫比赛的起始页,因此有很多行都是一样的。我使用下拉列表选择一个玩家,然后AJAX呼叫获得了该玩家的让分,我想将其插入下一个<td>
单元格
<tr>
<td id='firstTeeTime'>
<input type="time" class="text-center form-control par" name="teetime1" id="teetime1" value=''>
</td>
<td>
<select class="form-control member" id = "selectedMember" name="member" required>
<option value="" selected>Select Member..</option>
<?php
$sql = mysqli_query($link, "SELECT playerId, firstName, surname FROM members WHERE isActive = 1 ORDER BY surname ASC");
while ($row = $sql->fetch_assoc())
{
echo "<option value=".$row['playerId'].">". $row['firstName']." ". $row['surname']."</option>";
}
?>
</select>
</td>
<td class="playingHandicap"></td>
</tr>
$('.member').change(function() {
var selectedMemberID = $(this).val();
console.log('memberID is ' + selectedMemberID);
var selectedEventID = $('#selectedEvent').val();
$.ajax({
type: 'POST',
url: 'php/getHandicap.php',
data: {
selectedMemberID: selectedMemberID,
selectedEventID: selectedEventID
},
datatype: 'text',
success: function(response) {
var hcap = $.parseJSON(response);
//round exact up or down to nearest integer
var playingHcap = Math.round(hcap);
console.log('Playing Handicap is ' + playingHcap);
$(this).closest('tr').find('.playingHandicap').html(playingHcap);
很抱歉提出一个简单的问题,但四处搜寻,但我似乎无济于事。
答案 0 :(得分:2)
这里有两个问题。首先,您将playingHcap
附加为字符串文字。如果要插入变量值内包含的文本,请删除该变量周围的引号。
第二,this
处理函数中的success
不会是引发change
事件的元素。您需要在AJAX请求之外的范围中存储对该元素的引用。试试这个:
$('.member').change(function() {
var selectedMemberID = $(this).val();
var selectedEventID = $('#selectedEvent').val();
var $member = $(this);
$.ajax({
type: 'POST',
url: 'php/getHandicap.php',
data: {
selectedMemberID: selectedMemberID,
selectedEventID: selectedEventID
},
datatype: 'text',
success: function(response) {
var hcap = $.parseJSON(response);
var playingHcap = Math.round(hcap);
$member.closest('tr').find('.playingHandicap').text(playingHcap);
}
});
});