I am a new javascript learner. I did this but don't understand why always "you rock" alert pops up when I click. Thanks in advance
function favColors() { var example = document.getElementById('example'); if(document.getElementById('favorite').value=example.options[0].text) { alert("you rock"); }else { alert("have no color taste"); } document.getElementById('favorite').value=example.options[example.selectedIndex].text; }
<form> <select id="example" onChange="favColors()"> <option>Black</option> <option>Red</option> <option>White</option> <option>Pink</option> </select> <p> Your favorite sport is: <input type="text" id="favorite"> </p> </form>
Your IF
clause needs a ==
instead of a single =
. It should look like this:
if(document.getElementById('favorite').value==example.options[0].text) {
instead of
if(document.getElementById('favorite').value=example.options[0].text) {
.
Hope it helps.
Also, this:
document.getElementById('favorite').value=example.options[example.selectedIndex].text;
needs to be the first statement of right after defining example
.
Update:
example.options[example.selectedIndex].text
needs to be applied to document.getElementById('favorite').value
before you can use it for comparison. =
sign is for assignment and ==
is for comparison. So your IF
statement needed updating accordingly. Read this . You're using an assignment instead of a comparison operator inside of your if statement.
Assignment operator
//sets x to 5
x = 5
//sets y to an empty object
y = {}
//sets y to 5
y = x
Regular comparison operator
//evaluates to true
5 == 5
//evaluates to true
'5' == '5'
//evaluates to true
'5' == 5
//evaluates to false
'5' == 0
Strict comparison operator (the one you should be using)
//evaluates to true
5 === 5
//evaluates to true
'5' === '5'
//evaluates to false
'5' === 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.