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!

3

1 Answer 1

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

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

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.