如何在JavaScript中将用户输入与属性值进行比较?

时间:2014-07-01 06:02:00

标签: javascript

我有这样的代码,我想在循环中比较name的属性值和存储在变量“user”中的用户输入的输入。我怎么能这样做?

<form>
<input type="radio" name="two">
<input type="radio" name="three">
<input type="radio" name="four">
<input type="radio" name="five">
<input type="radio" name="six">
</form>

3 个答案:

答案 0 :(得分:1)

请参阅this答案,了解如何在本机javascript中循环显示单选按钮的示例,为方便起见,此处引用:

<html>
    <head>
        <script>
            var userChoice;

            var setUserChoice = function(event) {
                event.preventDefault();
                var choices = event.target.userChoice;

                for (var i =0; i < choices.length; i++) {
                    if (choices[i].checked) {
                        userChoice = choices[i].value;
                    }
                }

                event.target.choice.value = userChoice;
            }

            window.onload = function() {
                var form = document.getElementById('userInput');
                form.addEventListener('submit', setUserChoice, false);
            };
        </script>
    </head>

    <body>
        <form id="userInput">
                <input type="radio" name="userChoice" id="userChoice_rock" value="rock">Rock</input> </br>
                <input type="radio" name="userChoice" id="userChoice_paper" value="paper">Paper</input> </br>
                <input type="radio" name="userChoice" id="userChoice_scissors"value="scissors">Scissors</input> </br>
                <input type="radio" name="userChoice" id="userChoice_lizard" value="lizard">Lizard</input> </br>
                <input type="radio" name="userChoice" id="userChoice_spock" value="spock">Spock</input> </br>
                <input type="submit" value="Enter" /></br>
                <output name="choice"></output>
        </form>
    </body>
</html>

答案 1 :(得分:0)

您可以比较此小提琴中的值:http://jsfiddle.net/5wd8p/

<强> HTML

<form action="demo.html" id="myForm">
    <form>
        <input type="radio" name="two">
        <input type="radio" name="three">
        <input type="radio" name="four">
        <input type="radio" name="five">
        <input type="radio" name="six">
    </form>
    <input type="submit" value="Submit">
</form>

<强> JQuery的

$(function () {
    // Handler for .ready() called.
    var user = "three"; //default value: depends on youur code..

    //Loop through each radio element of the DOM
    $("input[type=radio]").each(function(){
        //Compare values of the "name" attribute and the user var
        if (user == $(this).attr("name")){
            alert("Same: " + $(this).attr("name"));
        }else{
            alert("Different: " + $(this).attr("name"));
        }
    });
});

答案 2 :(得分:0)

试试这个:

 document.getElementsByName(user)[0]