Joe
Joe

Reputation: 403

Select a dropdown option using javascript

I have very little experience with javascript and I'm trying to use Chrome console to select an item in a dropdown list. I found a way how to set the index to another value, but it does not trigger the action that would happen if I clicked on it manually. I looked for an answer and tried click() and focus() functions, but nothing seems to trigger it.

document.getElementsByClassName("class-abc")[0].selectedIndex = 1

Update. @jeprubio, your answer works. Weirdly enough, it works even when I skip adding the event listener like in the code below.

var x = document.getElementsByClassName("ui-pg-selbox")[0];
x.selectedIndex = 1;
x.dispatchEvent(new Event('change'));
<select class="class-abc" role="listbox">
    <option role="option" value="10" selected="selected">10</option>
    <option role="option" value="20">20</option>
    <option role="option" value="50">50</option>
</select>

Upvotes: 2

Views: 503

Answers (2)

jeprubio
jeprubio

Reputation: 18002

You could use dispatchEvent apart from changing the selectedIndex to fire the onChange event as if you had done it manually:

var select = document.getElementsByClassName("class-abc")[0];

select.addEventListener('change',function(){
   console.log('selected: ' + this.value);
});

select.selectedIndex = 1
select.dispatchEvent(new Event('change'));
<select class="class-abc">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

Upvotes: 2

Engineer S. Saad
Engineer S. Saad

Reputation: 384

I hope this will help you !!!

function submitss() {

		var temp = document.getElementById('country_drop_down_list').value
		var temp2 = temp.split('%%')
		console.log(temp2[0], temp2[1])
	}
<select name="countryCode" id="country_drop_down_list" onchange="submitss()">

		<option value="Algeria%%213">Algeria (+213)</option>
		<option value="Andorra%%376">Andorra (+376)</option>
		<option value="Angola%%244">Angola (+244)</option>
		<option value="Anguilla%%1264">Anguilla (+1264)</option>
		<option value="Antigua%%1268">Antigua &amp; Barbuda (+1268)</option>
		<option value="Argentina%%54">Argentina (+54)</option>
		<option value="Armenia%%374">Armenia (+374)</option>
		<option value="Aruba%%297">Aruba (+297)</option>
	
</select>

Upvotes: 0

Related Questions