1

I am trying to submit a form, consistent solely of a dropdown menu in order to get to another page. I cannot figure out how to select the dropdown however. The below sample is a representation of what I am dealing with.

<select name="p_term" size="1" id="term_input_id">
<option value="">None
</option><option value="201605">Summer Session: May - Aug 2016
</option><option value="201601">Second Term: Jan - Apr 2016
</select>

I have tried

document.getElementById('term_input_id').value='201601';

but PhantomJS will not run the rest of my code with this line in there.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
spanner1122
  • 106
  • 1
  • 11
  • Does [my answer here](http://stackoverflow.com/a/32771797/1816580) or [here](http://stackoverflow.com/a/30988637/1816580) work? – Artjom B. Mar 12 '16 at 09:54

1 Answers1

2

select elements are not like inputs, you cannot assign value directly.

var val = 201601;
var sel = document.getElementById('term_input_id');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
    if(opt.value == val) {
        sel.selectedIndex = j;
        // or:
        // opt.selected = true
        break;
    }
}

(From this excellent answer)

Then, you have to trigger onchange event that is redirecting page to another location:

var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
sel.dispatchEvent(evt);  

(From this answer)

but PhantomJS will not run the rest of my code with this line in there.

To find out what error is causing your script to break, subscribe to page.onError callback.

Community
  • 1
  • 1
Vaviloff
  • 16,282
  • 6
  • 48
  • 56
  • @ArtjomB. if it's fired with a `change` event on ` – Leo Mar 12 '16 at 10:06
  • @ArtjomB, thanks, you're right, the answer was useless, updated with example to trigger `change` event. – Vaviloff Mar 12 '16 at 16:13