yokogeri yokogeri - 3 years ago 179
Ajax Question

Display correctly the selected value

I use an AJAX to display my categories. My problem is when I select a category, the dropdown come back always at this initial position

For example, if I click "Panneaux lumineux", the dropdown go back to "Select your categorie" automatically. in this case "Panneaux lumineux" is not selected.

Tk

<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22">&nbsp;&nbsp;&nbsp;Barrières</option>
<option value="21">&nbsp;&nbsp;&nbsp;Entrée</option>
</select>
<input name="current_category_id" value="20" type="hidden" />
</div>
</div>

Answer Source

Above the $.ajax function call add

var selectedOptionVal = $('#category_id').val();

to save the value you selected.

then use that value to make the correct option selected when you recreate the html. So then try changing

for (index in data) {
    var category_id = data[index]['id'];
    var category_name = data[index]['text'];
    options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}

to

for (var index in data) {
    var category_id = data[index]['id'];
    var category_name = data[index]['text'];
    var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
    options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download