1

I need to create a form with Javascript to get around a CORS issue (meaning: I cannot submit this form using AJAX because the API I am using does not allow it).

However I am having problems setting the value with Javascript. The following does not work for me:

var form = document.createElement("form");

var formElement = document.createElement("select");
formElement.value = "foo";
formElement.id = "bar";

form.appendChild(formElement);

document.body.appendChild(form);

see jsbin.

3 Answers 3

3

select elements have option elements to go with it:

var formElement = document.createElement("select");
var optionElement = document.createElement("option");

optionElement.value = "foo";
optionElement.text = "foo"
optionElement.selected = true;

formElement.appendChild(optionElement);
formElement.id = "bar";

Demo: http://jsbin.com/tebasecahi/1/edit?html,js,output

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

1 Comment

Thanks, going to marked this as the answer (because it was first).
1

First you need to create the select list (before you create options):

var selectList = document.createElement('select');

Then add that to the form:

form.appendChild(selectList);

Then you can create the option and append that to the selectList:

var option = document.createElement("option");
option.value = 'foo';
option.id = 'bar';
option.selected = true;
option.text = 'foobar';

Finally, append that to the selectList and then the form to the body

selectList.appendChild(option);
document.body.appendChild(form);

See jsBin

Comments

-2

Try using setAttribute method instead of value.

var form = document.createElement("form");

var formElement = document.createElement("select");
formElement.setAttribute('value', "foo");
formElement.id = "bar";

form.appendChild(formElement);

document.body.appendChild(form);

5 Comments

Please consider posting a reason for the minus 1. The code I have posted is valid and working.
select elements need options, else it's just a blank select. And your code didnt change anything from OP's, you use setAttribute instead of just defining the property.
That's false. If you inspect with the original code, you do not see a value property on the select element. By using setAttribute you are able to add this prop which is what the question was: "However I am having problems setting the value"
Perhaps you should update your question from setting select value to setting option values.
All I knew is I needed to set a value that the server could grab. If I knew it was options I wouldn't have asked on stack overflow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.