0

I have created a basic drop down list. I am simply trying to select the value currently showing in the drop down list, save it in a variable, and print it in the console. The end goal is to compare that variable to another variable to determine if the selection was correct.

I am a novice , so I assuming no one needs to know my poor attempts here...

<div id="Selections">
    <div id="game1">
        <p> Saturday 1:00PM EST   Team 1 vs Team 2 </p>
        <select id="game1Pick">
            <option>Team 1</option>
            <option>Team 2</option>
        </select>
    </div>
</div>

I expect the console to print whatever I have selected, but I keep getting errors.

mullac
  • 693
  • 6
  • 17
  • 1
    This is a JavaScript or a JQuery question -- it should not be tagged with "Java", as the Java language is not involved at all. – arcy May 02 '19 at 22:53
  • 1
    *"I am a novice , so I assuming no one needs to know my poor attempts here..."* Yes, we do. You showing your attempt changes this question from a coding request to an "I have an issue with logic, help me" valid question. – Taplar May 02 '19 at 23:00

3 Answers3

0

You need an onchange function to detect what value you have selected. Example:

<div id="Selections">
    <div id="game1">
        <p> Saturday 1:00PM EST   Team 1 vs Team 2 </p>
        <select id="game1Pick" onchange="myFunction()">
            <option>Team 1</option>
            <option>Team 2</option>
        </select>
    </div>
</div>

<script>
function myFunction() {
  var x = document.getElementById("game1Pick").value;
  console.log('Selected Value is -> ', x);
}
</script>
vjeta
  • 1,178
  • 2
  • 11
  • 18
0

var teamVal = "team-1";
$('#game1Pick').on('change', function(){
  if($(this).val() == teamVal){
    alert('variable matches the option');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Selections">
    <div id="game1">
        <p> Saturday 1:00PM EST   Team 1 vs Team 2 </p>
        <select id="game1Pick">
            <!--use value 1st for options -->
            <option value="">--select--</option>
            <option value="team-1">Team 1</option>
            <option value="team-2">Team 2</option>
        </select>
    </div>
</div>

Please check this I did some changes in HTML and I use some jQuery for it.

Arindam Sarkar
  • 224
  • 1
  • 13
0

Below i have directly passed the selected object in onChange. And If you also want the value before onchange also you can refer this link. Getting value of select (dropdown) before change

function printValue(obj) {
    console.log('Selected Value is --> ', obj.value);
    //put the condition 
}
 <div id="Selections">
    <div id="game1">
        <p> Saturday 1:00PM EST   Team 1 vs Team 2 </p>
        <select id="game1Pick" onchange="printValue(this);">
            <option>Team 1</option>
            <option>Team 2</option>
        </select>
    </div>
</div>