gpt4 book ai didi

javascript - 多个选项框同名jquery ajax

转载 作者:行者123 更新时间:2023-11-30 15:23:46 25 4
gpt4 key购买 nike

我有多个同名的选择框。现在,当我从第一个选择框中选择值时,它会提交那个值并更新数据库。当我选择另一个选择框上的项目时,它会提交第一个选择框的值。我觉得 javascript 不对。知道哪里出了问题吗?

这是我的 html:

<?php foreach ($result as $row): ?>
<select class="form-control" name="category[]" required>
<option value="" disabled selected>Select The Category </option>
<option value="station">Station</option>
<option value="equipment">Tools/Equipment</option>
<option value="supplies">Supplies</option>
</select>
<input id="taskID" value="<?php echo $row['id']; ?>" hidden></input>
<?php endforeach; ?>

j查询:

$(document).on('change', 'select[name="category[]"]', function(event){
$('select[name="category[]"]').each(function(){
var formData = {
'task': $('select[name="category[]"]').val(),
'name': $('input[name="taskID[]"]').val(),
};
$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
});
});

地址簿.php

if (isset($_POST['task'])) {

$task = $_POST['task'];
$id = $_POST['name'];

$stmt = $con->prepare("UPDATE members SET task = ? WHERE id = ?");
$stmt->bind_param('ss', $task, $id);
$stmt->execute();

}

最佳答案

将类属性更改为:class="form-control categorySelect"

$('.categorySelect').change(function(event){
for(selectInstance of $('.categorySelect')){
var formData = {
'task': $(selectInstance).val(),
'name': $(selectInstance).next().val()
};


$.ajax({
type: 'POST',
url: 'php/addressBook.php',
data: formData,
dataType: 'html',
encode: true
})
.done(function(msg) {
$(".alert").html(msg);
})
.fail(function(data) {
console.log(data);
})
event.preventDefault();
}

});

关于javascript - 多个选项框同名jquery ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43301392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com