0

I am very new at HTML/CSS/JavaScript, and I was wondering how I would use a variable that I declared in HTML, and do something with it in JavaScript. In the code below, I created a selection box, and I want to output a message using something along the lines of "if(...) then alert("")". How would I do the equivalent of

if(value == "chrome") {alert("you are using Chrome");}

"Value" is in HTML, but the comparison would be done in JS. Here is the code:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Hello, Internet!</title>
</head>
<body>
<h1>
    <p>Webstorm</p>
</h1>
<h2>
    <p>Browser ID</p>
</h2>
    <h3>
        <p>Select which browser this is running on:</p>
        <select>
            <option>[Select Browser]</option>
            <option value = "chrome">Chrome</option>

                <!--How would I use "value"? -->

            <option value = "firefox">Firefox</option>
            <option value = "IE">InternetExplorer</option>
        </select>
    </h3>

</body>

</html>
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
jordpw
  • 181
  • 2
  • 16

2 Answers2

1

You can always assign the option with an id and then using javascript to read the selected value as a variable

  <select id="example">
        <option>[Select Browser]</option>
        <option value = "chrome">Chrome</option>

            <!--How would I use "value"? -->

        <option value = "firefox">Firefox</option>
        <option value = "IE">InternetExplorer</option>
    </select>

Your Javascript

    var x = document.getElementById("example").selectedIndex;
    console.log(x);
FRizal
  • 448
  • 7
  • 15
1

You can replace the line of <select> with the following:

<select onchange="if(this.options[this.selectedIndex].value == 'chrome') {alert('you are using Chrome?');} " >

It will only alert "you are using Chrome?" when the chrome is selected. Is this what you want?

Phil
  • 157,677
  • 23
  • 242
  • 245
yetsun
  • 1,010
  • 12
  • 12