Shniper
Shniper

Reputation: 854

Selected value from html select menu

I'm trying to make clicking the battle button print "You have slain" + selected option + What I have now works for the first option, but if you select a different option in the dropdown and click battle it still says Fly.

Fiddle

var mon = document.getElementById('monsters');
var monster =mon.options[mon.selectedIndex].text;

$('#battle').click(function() {
    document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});

Upvotes: 3

Views: 43

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Updated fiddle

Because you're using jQuery it could be simply :

$('#battle').click(function() {
    $('#dam').text("You have hit the " + $('#monsters option:selected').text() + " for 5 damage");
});

Hope this helps.

Upvotes: 1

DinoMyte
DinoMyte

Reputation: 8868

In your solution, you have declared the values of the selected value globally which is set only once during the document load. In order to calculate the right value, you have to declare them locally during the button click.

$('#battle').click(function() {
  var mon = document.getElementById('monsters');
  var monster =mon.options[mon.selectedIndex].text;
    document.getElementById('dam').innerHTML = "You have hit the " + monster + " for 5 damage";
});

Working example : https://jsfiddle.net/DinoMyte/4dyph8jh/5/

Upvotes: 6

Related Questions