How to select the last option in a dynamic drop-down list

Asked

Viewed 40 times

0

I have a dynamic drop-down, in which the amount of options varies. I would like to know how to select the last option automatically.

Ex.:

<select name="pagarme_installments" id="pagarme-installments">
    <option value="0">Por favor, selecione o número de parcelas</option>
    <option value="1">1x de 238,80 (sem juros)</option>
    <option value="2">2x de 119,40 (sem juros)</option>
    <option value="3">3x de 79,60 (sem juros)</option>
    <option value="4">4x de 59,70 (sem juros)</option>
    <option value="5">5x de 47,76 (sem juros)</option>
    <option value="6">6x de 39,80 (sem juros)</option>
    <option value="7">7x de 34,11 (sem juros)</option>
    <option value="8">8x de 29,85 (sem juros)</option>
    <option value="9">9x de 26,53 (sem juros)</option>
    <option value="10">10x de 23,88 (sem juros)</option>
    <option value="11">11x de 21,71 (sem juros)</option>
    <option value="12">12x de 19,90 (sem juros)</option>
</select>

The solution I thought of was to find the maximum amount of options existing at the drop-down, then a condition in which if the option with the value is equal to the maximum of options, enter the attribute selected. The problem is that I don’t know how to get this value from each option to test on each of them. Get the maximum value I got in the following way:

<script>
  var theSelect = document.getElementById('pagarme-installments');
  var ultimoValor = theSelect.options[theSelect.options.length - 1].value;
</script>

Could someone give me a light? If there is a way to do this in php, it is. I only found a way to do it in js.

Thank you in advance for your attention.

  • 1

    if you prefer to use jQuery library use $("#pagarme-installments option:last"). attr("Selected", "Selected");

1 answer

2


Hello,

You can use 'Document.querySelectorAll':

document.querySelectorAll('#pagarme-installments option:last-child').item(0).selected =  true

In querySelectorAll we use the CSS selector syntax.

In this case, we are selecting the last 'option' within '#pagarme-installments'.

As it returns the collection of elements, we need to take the first (which is the only) item: item(0)

And set the attribute 'Selected' to true

  • I was thinking of a much more complicated solution than this one. It worked perfectly! I just didn’t quite understand why to use item(0). If you were not uncomfortable and could explain to me a little better I would be very.

  • Glad it worked. Using item(0)' was to access the html element of the option. This is because querySelectorAll returns a Nodelist, which is a collection of objects. In this case we only have one of these objects, so item 0.

Browser other questions tagged

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