Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dropdown selected=selected in Safari does not work

I have got a subscribe form with several tabs. You can click backwards and forwards in this form.

For drop downs I use a jquery to preselect a previous choice, so people do not have to re-answer this specific question on clicking backwards.

This script works fine for Chrome and Firefox, however for Safari it does not work at all. Somehow I just can't get this to work.

Can you please have a look at it and tell me what I am doing wrong?

the script:

if (repeat_visit !== '') {
    $('#repeatVisit').find('option').each(function(){
        if ($(this).val() === repeat_visit) {
            $(this).attr('selected','selected');
        }
    });
}

The attribute is set to the option so it looks like: Yes

I can see this does happen, but it seems that Safari does not change the page when the selected attribute is added after the page load. So somehow I need to trigger this change event.

like image 315
BonifatiusK Avatar asked Sep 25 '13 11:09

BonifatiusK


Video Answer


2 Answers

I found the answer!

You can use .prop('selected', true) in stead off attr('selected','selected');

like image 125
BonifatiusK Avatar answered Sep 22 '22 10:09

BonifatiusK


The following function works in current Safari, Safari Mobile, Chrome, Edge, and Firefox as of this writing.

This handles the issue where the .prop calls MUST be done before the .attr calls or the entire thing is ignored, and the redraw issue in firefox.

    function updateSelect(selectname, value){
        $('select[name="'+selectname+'"] option').prop('selected',false);
        $('select[name="'+selectname+'"] option').removeAttr('selected');
        $('select[name="'+selectname+'"] option[value="'+value+'"]').prop('selected',true);
        $('select[name="'+selectname+'"] option[value="'+value+'"]').attr('selected','selected');
        $('select[name="'+selectname+'"]').val(value).change();
    }
like image 21
Miles Prower Avatar answered Sep 18 '22 10:09

Miles Prower