Nishank
Nishank

Reputation: 475

Javascript if else condition not working properly

I had developed a jsp web project, where user has to select one option from radio button, and i m sending the user selected value to other page using javascript.

JavaScript code:

function select() {
    var val1 = document.getElementsByName("President");
    var result1;
    for (var i = 0; i < val1.length; i++) {

        if (val1[i].checked) {
            console.log(val1[i].checked)
            result1 = val1[i].value;
            alert(result1);

        } else {

            alert("president vote is missing");
            return;
        }

    }
}

When the user doesn't choose an option, then javascript code is working fine and it is going to else and showing an alert message that("president vote is missing"). But when user chooses one option from the list then then the if condition is working fine and after that else condition is also getting executed , I never faced this kind of problem

Upvotes: 0

Views: 923

Answers (2)

FlokiTheFisherman
FlokiTheFisherman

Reputation: 234

Beside`s the problem is solve, i made this code if someone needs help!

<html>
<head>
    <title>STACK OVERFLOW TESTS</title>
</head>
<body>
    <input type = 'radio' name = 'President' value = 'Obama'>Obama</input>
    <br>
    <input type = 'radio' name = 'President' value = 'Bush'>Bush</input>
    <br>
    <input type = 'radio' name = 'President' value = 'Clinton'>Clinton</input>
    <br>
    <input type = 'button' id = 'button' onClick = 'showMyChoice()'> SEND </input>

    <script>

    function showMyChoice(){
        var val1 = document.getElementsByName("President");
        var result1;
        var missingVote = false;

        for(var i = 0; i < val1.length; i++){
            if(val1[i].checked){ // Check for all the radio buttons if there is one checked.
                console.log(val1[i].checked);
                result1 = val1[i].value;
                alert(result1);
                missingVote = false;
                break;
            }
            else{
                missingVote = true;
                continue;
            }
        }

        if(missingVote){
            alert('President vote is missing');
        }
    }
    </script>
</body>
</html>

Upvotes: 0

Peter Peng
Peter Peng

Reputation: 1958

I can see you doing alerts in a for loop. Can it be a scenario like this: first iteration "if" gets executed and then next iteration "else" gets executed because of "val1[1].checked" is false?

Upvotes: 2

Related Questions