我正在使用JS / Ajax函数来回显选择框中的Selected值。我用MySQL DB中的值填充这些选择框。该函数适用于文本输入字段,但现在我使用它与这些选择框我没有得到任何响应。
我可以使用JS从选择框中回显选定的值吗?或者,还有更好的方法? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
PHP / HTML
try {
$pdo = get_database_connection();
$sql = "SELECT *
FROM `categories`
WHERE `master_id` = 0";
$statement = $pdo->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
<form action="" method="post" id="category_form'" name="category_form'">
<select name="main" id="main" size="7" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="subc1" id="subc1" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc2" id="subc2" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc3" id="subc3" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
</form>
<div id="special"></div>
答案 0 :(得分:1)
看起来你正在用jQuery选择错误的元素。
变化:
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
要:
$('#main').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});