Cláudio
Cláudio

Reputation: 23

How to evaluate and generate a result from a html form using javascript

as the title says i need to create a game but my problem is that I don't know how to read the radio buttons using javascript and based on the options, it generates a scenario with the game mode with the difficulty the player picks. I am using one text input for the nickname and 2 fieldsets like this one for the player to select the type of the game and difficulty.

            <fieldset>
            <legend>Dificuldade:</legend>
                    <input type="radio" name="dificuldade" value="easy"> easy </input>
                    <input type="radio" name="dificuldade" value="medium"> medium </input>
                    <input type="radio" name="dificuldade" value="hard"> hard </input>
            </fieldset>

Upvotes: 1

Views: 1035

Answers (1)

LukeGT
LukeGT

Reputation: 2352

I suggest you use jQuery, it makes life so much easier:

$('[name=dificuldade]:checked').val()

JSFiddle: http://jsfiddle.net/3bc9m/

Otherwise you would have to go through each of the radio buttons in the DOM, and check their checked property. When you find the one with checked === true, you can then read its value property. Like this:

var fieldset = document.getElementById('difficuldade'); // You'd need to set an ID to the fieldset element
var curr = fieldset.firstChild;

while (curr != null) {
    if (curr.checked) {
        break;
    }
    curr = curr.nextSibling;
}

curr.value; // This is your selected value

JSFiddle: http://jsfiddle.net/3bc9m/1/

As Nate mentioned, make sure the DOM is ready, otherwise this will not work. This means that all of your code should be run on the onload event of the body element. See this for more details: http://www.w3schools.com/jsref/event_body_onload.asp

Upvotes: 2

Related Questions