I have this list i would like to select 3th option or the option with value "ASD"
i tried this document.querySelector(' #edit-activity-domain option:nth-child(4)').click();
or this $('#edit-activity-domain').find('option:nth-child(3').prop('selected',true).trigger('change');
<select data-drupal-selector="edit-activity-domain" id="edit-activity-domain" name="activity-domain-id" required="required" aria-required="true" style="" data-select2-id="edit-activity-domain" tabindex="-1" aria-hidden="true">
<option value="*" selected="true" data-select2-id="7">Votre domaine d'activité</option>
<option value="APT" data-select2-id="13">Accompagnement personnel et Thérapie</option>
<option value="ACE" data-select2-id="14">Artisans, Commerçants et e-Commerçants de détail</option><option value="ASD" data-select2-id="15">Associations et Syndicats</option>
<option value="OTS" data-select2-id="16">Autres services à la personne</option><option value="BIE" data-select2-id="17">Bien-Etre</option>
<option value="BET" data-select2-id="18">Bureaux d'études techniques</option>
</select>
`
CodePudding user response:
You can try with getElementsByClassName
, here I added a new class to your dropdown list selector
<select data-drupal-selector="edit-activity-domain" id="edit-activity-domain" name="activity-domain-id" required="required" aria-required="true" style="" data-select2-id="edit-activity-domain" tabindex="-1" aria-hidden="true">
<option value="*" selected="true" data-select2-id="7">Votre domaine d'activité</option>
<option value="APT" data-select2-id="13">Accompagnement personnel et Thérapie</option>
<option value="ACE" data-select2-id="14">Artisans, Commerçants et e-Commerçants de détail</option><option value="ASD" data-select2-id="15">Associations et Syndicats</option>
<option value="OTS" data-select2-id="16">Autres services à la personne</option><option value="BIE" data-select2-id="17">Bien-Etre</option>
<option value="BET" data-select2-id="18">Bureaux d'études techniques</option>
</select>
Then use getElementsByClassName()
with index 0 because this returns an array like object and you only have 1 element with this class and then just select the index of the option you want to select
document.getElementsByClassName("selector")[0].selectedIndex = 2
you can also get elementbyid if you don't want to use the class
document.getElementById("edit-activity-domain").selectedIndex = 2
or if you want to use jquery using class
$("select.selector").val("ACE");
or jquery using id
$("#edit-activity-domain").val("ACE");