3

How can I sett the value and text of a select option from javascript?

function getYear() 
{
    var d = new Date();
    var year = d.getFullYear();
    return year;
}


<select name="dateformat" onchange="change_date();" id="dateformat">
   <option value="??" >??</option>
</select>

I want the value of getYear() in place of ??.

2 Answers 2

6
var option = document.getElementById("dateformat").options[0];
option.value = option.text = getYear();

Edit: I thought OP meant to find a way to add an option to a <select>. But it seems it's more like editing an existing one. So there.

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

Comments

1

There you go:

var year = getYear();
var combo = document.getElementById('dateformat');
combo.options[combo.options.length] = new Option(year ,year );

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.