Как проверить, установлен ли хотя бы один переключатель в этой функции?

#javascript #jquery

#javascript #jquery

Вопрос:

Я провожу тест с помощью PHP, но сначала я использую JavaScript для перехода между вопросами, а затем отправляю форму, и пусть PHP сделает все остальное.

Я создал две функции JavaScript с именем ChangeQuestion() и BackQuestion() .

 function ChangeQuestion(prev, next) {
    $('#'   prev).fadeOut(600, function() {
        $('#'   next).fadeIn(600);
    });
}

function BackQuestion(last, prev) {
    $('#'   prev).fadeOut(600, function() {
        $('#'   last).fadeIn(600);
    });
}
  

Они довольно простые. Но что я хотел бы сделать, это проверить, установлен ли хотя бы один переключатель в вопросе, прежде чем продолжить работу с функцией. Вы сможете увидеть в моей разметке / HTML, как я использую вышеуказанные функции.

Прежде всего, вот jsFiddle: http://jsfiddle.net/3XdUA /

Вот моя разметка:

 <form id="quiz1" name="quiz1" method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
    <div id="starter">
        Hello! Welcome to the HTML Quiz powered by PHP. Click on Start to begin.
        <br /><br />
        <button type="button" onclick="ChangeQuestion('starter','question1');$('#qIndicator').fadeIn(800);">Start amp;raquo;</button>
    </div>
    <div id="question1" style="display:none;">
        1. What does HTML stand for?
        <br />
        <br />
        <input type="radio" name="q1" id="q1-a1" /> 
        <label for="q1-a1">Hyperlinks and Text Markup Language</label>
        <br />
        <input type="radio" name="q1" id="q1-a2" /> 
        <label for="q1-a2">Home Text Markup Language</label>
        <br />
        <input type="radio" name="q1" id="q1-a3" /> 
        <label for="q1-a3">Hyper Text Markup Language</label>
        <br />
        <input type="radio" name="q1" id="q1-a4" /> 
        <label for="q1-a4">Hyper Text Marking Language</label>
        <br /><br />
        <button type="button" onclick="ChangeQuestion('question1','question2');$('#qIndicator').html('Question 2 of 10');">Next amp;raquo;</button>
    </div>

    <div id="question2" style="display:none;">
        2. What is the proper way to add a blue background to the <code>amp;<body></code> and remove the margin amp;amp; padding?
        <br />
        <br />
        <input type="radio" name="q2" id="q2-a1" /> 
        <label for="q2-a1">amp;<body backgroundColor="blue" padding="0" margin="0"amp;></label>
        <br />
        <input type="radio" name="q2" id="q2-a2" /> 
        <label for="q2-a2">amp;<body style="background-color: blue; margin: 0; padding: 0;"amp;></label>
        <br />
        <input type="radio" name="q2" id="q2-a3" /> 
        <label for="q2-a3">amp;<body style="backgroundColor: blue; margin: 0px; padding: 0px;"amp;></label>
        <br />
        <input type="radio" name="q2" id="q2-a4" /> 
        <label for="q2-a4">amp;<body background="blue" padding="0" margins="0"amp;></label>
        <br /><br />
        <button type="button" onclick="BackQuestion('question1','question2');$('#qIndicator').html('Question 1 of 10');">amp;laquo; Back</button>
        <button type="button" onclick="ChangeQuestion('question2','question3');$('#qIndicator').html('Question 3 of 10');">Next amp;raquo;</button>
    </div>

    <div id="question3" style="display:none;">
        3. Which of the following font styling tags isnamp;#39;t valid?
        <br />
        <br />
        <input type="radio" name="q3" id="q3-a1" /> 
        <label for="q3-a1">amp;<smallamp;></label>
        <br />
        <input type="radio" name="q3" id="q3-a2" /> 
        <label for="q3-a2">amp;<strongamp;></label>
        <br />
        <input type="radio" name="q3" id="q3-a3" /> 
        <label for="q3-a3">amp;<emamp;></label>
        <br />
        <input type="radio" name="q3" id="q3-a4" /> 
        <label for="q3-a4">amp;<largeamp;></label>
        <br /><br />
        <button type="button" onclick="BackQuestion('question2','question3');$('#qIndicator').html('Question 2 of 10');">amp;laquo; Back</button>
        <button type="button" onclick="ChangeQuestion('question3','question4');$('#qIndicator').html('Question 4 of 10');">Next amp;raquo;</button>
    </div>

    <div id="question4" style="display:none;">
        4. Suppose you have this HTML on your page:
        <br /><br />
        <code>
            amp;<a name="target4"amp;>Old listingamp;</aamp;>
        </code>
        <br /><br />
        How would you link to the above target?
            <br />
            <br />
            <input type="radio" name="q4" id="q4-a1" /> 
            <label for="q1-a1">amp;<a url="#target4"amp;>Check Old Listing as wellamp;</aamp;> </label>
            <br />
            <input type="radio" name="q4" id="q4-a2" /> 
            <label for="q1-a2">amp;<a href="#target4"amp;>Check Old Listing as wellamp;</aamp;></label>
            <br />
            <input type="radio" name="q4" id="q4-a3" /> 
            <label for="q1-a3">amp;<link url="target4"amp;>Check Old Listing as wellamp;</linkamp;> </label>
            <br />
            <input type="radio" name="q4" id="q4-a4" /> 
            <label for="q1-a4">amp;<a href="Listing.target4"amp;>Check Old Listing as wellamp;</aamp;></label>
            <br /><br />
            <button type="button" onclick="BackQuestion('question3','question4');$('#qIndicator').html('Question 3 of 10');">amp;laquo; Back</button>
            <button type="button" onclick="ChangeQuestion('question4','question5');$('#qIndicator').html('Question 5 of 10');">Next amp;raquo;</button>
        </div>

            <div id="question5" style="display:none;">
                5. What does HTML stand for?
                <br />
                <br />
                <input type="radio" name="q2" id="q2-a1" /> 
                <label for="q1-a1">Hyper Tool Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a2" /> 
                <label for="q1-a2">Home Text Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a3" /> 
                <label for="q1-a3">Hyper Text Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a4" /> 
                <label for="q1-a4">Hyper Text Marking Language</label>
                <br /><br />
                <button type="button" onclick="BackQuestion('question4','question5');$('#qIndicator').html('Question 4 of 10');">amp;laquo; Back</button>
                <button type="button" onclick="ChangeQuestion('question5','question6');$('#qIndicator').html('Question 6 of 10');">Next amp;raquo;</button>
            </div>

            <div id="question6" style="display:none;">
                6. What does HTML stand for?
                <br />
                <br />
                <input type="radio" name="q2" id="q2-a1" /> 
                <label for="q1-a1">Hyper Tool Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a2" /> 
                <label for="q1-a2">Home Text Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a3" /> 
                <label for="q1-a3">Hyper Text Markup Language</label>
                <br />
                <input type="radio" name="q2" id="q2-a4" /> 
                <label for="q1-a4">Hyper Text Marking Language</label>
                <br /><br />
                <button type="button" onclick="BackQuestion('question5','question6');$('#qIndicator').html('Question 5 of 10');">amp;laquo; Back</button>
                <button type="button" onclick="ChangeQuestion('question6','question7');$('#qIndicator').html('Question 7 of 10');">Next amp;raquo;</button>
            </div>

        </form>
  

Да, он длинный. Извините за это. Но я предоставил jsFiddle, который было бы намного проще понять. (из-за предварительного просмотра и т. Д.)

Я знаю, как проверить, выбран ли переключатель, но я не знаю, как убедиться, что он выбран с помощью этой функции.

Ответ №1:

используйте :radio:checked

 function ChangeQuestion(prev, next) {
    var current = $('#'   prev);
    var selection = current.find(":radio:checked").attr("id");
    if (selection) {
        alert(selection);
    }
    current.fadeOut(600, function() {
        $('#'   next).fadeIn(600);
    });
}
  

альтернативой моему обновлению было бы

 function ChangeQuestion(prev, next) {
    var current = $('#'   prev);
    if (prev != "starter") {
        var selection = current.find(":radio:checked").attr("id");
        if (selection === undefined) {
            alert("no selection");
        } else {
            alert(selection);
            current.fadeOut(600, function() {
                $('#'   next).fadeIn(600);
            });
        }
    } else {
        current.fadeOut(600, function() {
            $('#'   next).fadeIn(600);
        });
    }
}
  

Мне просто не нравилось повторять

     current.fadeOut(600, function() {
        $('#'   next).fadeIn(600);
    });
  

смотрите здесь

Комментарии:

1. Спасибо! Но это не останавливает его, если ничего не выбрано.

2. Да, я понимаю, я тоже устал. Спасибо.

Ответ №2:

Используйте :checked псевдоселектор.

 function ChangeQuestion(prev, next) {
    var prevQ = $('#' prev);
    var numChecked = prevQ.find('input[type=radio]:checked').length;

    if( prev !=='starter' amp;amp; numChecked == 0 ) {
        // no radio checked in this question
        return;
    }

    prevQ.fadeOut(600, function() {
        $('#'   next).fadeIn(600);
    });
}
  

Комментарии:

1. У меня есть только одна небольшая проблема. Поскольку я помещаю $('#qIndicator').html('Question # of 10'); в onclick, он по-прежнему помещает, например, «Вопрос 2 из 10», даже если функция заставила их остановиться на вопросе 1, чтобы выбрать ответ. Есть идеи, как это исправить?

2. Я понял эту часть. Я просто поместил его внутрь функции и добавил несколько дополнительных операторов if.

Ответ №3:

Вы также можете использовать $("[name=q1]").is(":checked") просто для проверки, выбрано ли что-то. Конечно, замените q1 на любой вопрос, который у вас есть. В вашем случае похоже, что вы будете использовать q1 , q2 , и т.д.

Комментарии:

1. это будет выполнять поиск по всему DOM каждый раз. вам было бы лучше воспользоваться $("#" prev "[name*=q1]:checked")