Select select option according to url parameter

Asked

Viewed 48 times

0

i have the script below that takes a parameter from the URL(if it has), searches all selects of the page and selects the option with the same value(same value of the parameter). If you don’t have a parameter in the URL, it selects the first option from the select. So far, blz! I need that if you have a parameter in the URL it looks in all the selects of the page and if it finds it selects and if it does not exist in the NEXT select, it marks the first option.

if (hash !== undefined) {
$('.kit-list').each(function (i) {
    $('.kit-list:eq(' + i + ') select option').filter(function () {
        return $(this).text() == hash.size.replace('%20', ' ');
    }).prop("selected", true);
    $('.kit-list:eq(' + i + ') select').change();
});
} else {
$('.kit-list').each(function (i) {
    $('.kit-list:eq(' + i + ') select').find('option').eq(1).attr('selected', 'selected');
    $('.kit-list:eq(' + i + ') select').change();
});
}
  • Example of HTML? Example of values that can be in the hash?

1 answer

0

I solved my problem as follows(I don’t know if it’s the best but it worked):

if (hash !== undefined) {
    $('.kit-list').each(function (i) {
        if ($('.kit-list:eq(' + i + ') #espec_0_opcao_0 option[value=' + hash.size.replace('%20', ' ') + ']').length > 0) {
            $('.kit-list:eq(' + i + ') #espec_0_opcao_0 option').filter(function () {
                return $(this).text() == hash.size.replace('%20', ' ');
            }).prop("selected", true);
            $('.kit-list:eq(' + i + ') #espec_0_opcao_0').change();
            console.log('sim')
        } else {
            console.log('nao')
            $('.kit-list:eq(' + i + ') #espec_0_opcao_0').find('option').eq(1).attr('selected', 'selected');
            $('.kit-list:eq(' + i + ') #espec_0_opcao_0').change();
        }

    });
} else {
    $('.kit-list').each(function (i) {
        $('.kit-list:eq(' + i + ') select').find('option').eq(1).attr('selected', 'selected');
        $('.kit-list:eq(' + i + ') select').change();
    });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.