2

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>
2

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

2 Comments

The code works without adding an event listener and just by using dispatchEvent line. What does new Event('change') mean in this case?
I put the listener just to console log that the change is triggered, to prove it. Without the dispatchEvent it's not triggered. If you look at the docs of dispatchEvent you'll see that it needs an Event object as parameter. I'm glad I could help
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.