Retain select dropdown value after an ajax refresh

2019-08-15 04:15发布

This could be a repetitive question but please bare me. I have a dropdown as below, I select the option yellow, I have onclick which would do an operation and this does an ajax call. So after the ajax call the dropdown is defaulted back to red option instead of staying on yellow. I am still learning jquery

<select onChange="this.options[this.selectedIndex].onclick();>
<option value="red" onclick="">red</option>
<option value="yellow" onclick="">yellow</option>
<option value="blue" onclick="">blue</option>
<option value="green" onclick="">green</option>
</select>

Thanks in advance

2条回答
在下西门庆
2楼-- · 2019-08-15 04:40

try this:

$('input[value=red]').ajaxSuccess(function(){
   $(this).prop('selected', true)
})
查看更多
放荡不羁爱自由
3楼-- · 2019-08-15 04:41

A rough example as to how you achieve this:

// before ajax
var selected_item = $('select').val(); // use a better selector

// do some ajax
$.ajax({
    url: '/',
    data: {
        foo: 'bar'
    }
    success: function(data) {

        // update the select
        $('select').html(data);

        // reapply the originally selected element
        $('select').val(selected_item);

    }
}); 
查看更多
登录 后发表回答