我正在尝试使用jquery删除下拉列表中的重复选项。搜索相关问题但仍无法解决问题。希望你们能帮助我。谢谢!这是我的代码:
$(document).ready(function() {
$("#cat").change(function() {
$.ajax({
type: "GET",
url: "getPositionTitle.php",
data: "s_department=" + $(this).find(":selected").val(),
cache: false,
success: function(msg){
$("#position_title").empty();
my_position_title_array = $.parseJSON(msg);
for (i = 0; i < my_position_title_array.length; i ++) {
$("#position_title").append('<option value="' + my_position_title_array[i].position_title + '">'
+ my_position_title_array[i].position_title + '</option>');
}
$("#position_title").trigger('change');
}
});
var usedNames = {};
$("select[name='my_position_title_array'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
});
$("#cat").trigger('change');
});
// Post data to postPositionData.php when user changes form
$("#position_title").change(function() {
// Serialize form data
var yourFormData = $(this).serialize();
// POST
$.ajax({
type: "POST",
url: "doOfferedJob.php",
data: yourFormData
});
});
</script>
<tr>
<td><label for="applied_department">Department:</label></td>
<td>
<select id="cat" applied_position_title="category" name="applied_department">
<?php
$query = "SELECT id, department FROM department";
$result = mysqli_query($link, $query) or die(mysqli_error());
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value ='" . $row['department'] . "'>" . $row['department'] . "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><label for = "position_title">Position Title:</label></td>
<td>
<select id="position_title" name="position_title">
<option value="1"></option>
</select>
</td>
</tr>
答案 0 :(得分:0)
虽然我同意A. Wolff的评论,这应该在服务器端管理,你仍然可以调整你的for循环如下:
var positionTitles = [];
for (i = 0; i < my_position_title_array.length; i ++) {
if( positionTitles.indexOf( my_position_title_array[i].position_title) === -1 ) {
$("#position_title").append(/* ... */);
} else {
positionTitles.push( my_position_title_array[i].position_title );
}
}
也就是说,只有,如果...... position_title是一个真正的字符串,而不是一些字符串ish对象。