0
<select name="ethinicity" >
            <option value="type1">Asian</option>
            <option value="type2">African</option>
            <option value="type3">Caucasion</option>
            <option value="type4">Hispanics</option>
            <option value="type5">Other Populated Groups</option>
</select>

I am using

document.getELementsByname("ethinicity").value="type2"

to change its value,but it donot work in that way,why i can't do like this? and give me other way to do this but i donot want to put this in form and then changing it like

document.formName.ethinicity.value="type2"

Thanks in advance!

2
  • It is not duplicate i already checked all of them, but cant find any single answer which is specific to my question. Commented Jul 23, 2015 at 21:12
  • you need to change the selectedIndex of your select...This is a duplicate. Commented Jul 23, 2015 at 21:14

2 Answers 2

1

You can do this:

document.getElementsByName("ethinicity")[0].selectedIndex = 1;

You should give your select an id like this:

<select id="ethinicity" name="ethinicity" >

document.getElementById("ethinicity").selectedIndex = 1;
Sign up to request clarification or add additional context in comments.

5 Comments

document.getElementsByName("ethinicity")[0].value ="type2";why i cannot do like this
@sony never said you couldn't but I would recommend using an id instead of name to retrieve elements...
thnks, i will use this.
@sony no problem glad I could help!
If i use index 1 instead of 0 like this document.getElementsByName("ethinicity")[1].value ="type2" what would happen actually, as in console nothing is changing.why so?
1

You need to pass the name of the elements as a parameter to the function you are using to select them alongwith first array index:

document.getELementsByName("ethinicity")[0].value="type2"

3 Comments

I am already doing this, i mentioned it
you are not doing this. please check your question you have missing parenthesis.
yeah u r right but still it was wrong u forgot to add array index i think.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.