1

To begin with, I'm new to Javascript.

I have a form with a select element with various options and I do not have access to change the form. There are no id's to the options, but just the values as shown in the code below.

    <form>
    <select class="country" name="country" id="countryid">
        <option value="usa" selected="selected">USA</option>
        <option value="canada">Canada</option>
        <option value="japan">Japan</option>
        <option value="china">China</option>
        </select>
    </form>

My goal is to populate the field in the above form automatically based on the url parameters. For example, www.example.com?country=china should populate China in the form field. The following is the javascript code:

<script>
var param1var = getQueryVariable("country");

function displayresult(){
    //document.getElementById(param1var).selected=true; //if there was id given in     the form field
        //cannot use document.getElementByValue(param1var).selected=true;
    //document.querySelectorAll('input[value=' + param1var + ']').selected=true; does not work
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}
</script>
  1. I cannot use document.getElementById(param1var) because there is no id.
  2. Javascript does not support document.getElementByValue(param1var).
  3. document.querySelectorAll is not working.

Is there a way that I can reference the element using the option value?

Thanks!

PSL
  • 123,204
  • 21
  • 253
  • 243
Anirudh Gooner
  • 69
  • 2
  • 11
  • You could just loop through the options until you find the value you’re looking for … – CBroe Nov 12 '13 at 23:03
  • duplicate - http://stackoverflow.com/questions/9490906/how-to-change-a-select-value-from-javascript – McAden Nov 12 '13 at 23:03
  • possible duplicate of [Is there any fast way to get an – showdev Nov 12 '13 at 23:04

1 Answers1

3

You can just do it this way by setting the value of the select element. Also note that value is case sensitive, plus make sure that the function displayresult runs on onload or after the element appeared in the html.

document.getElementById("countryid").value=param1var; 

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243