5
\$\begingroup\$

I have created a proof of concept jQuery based flow diagram based upon kayen's answer to this post.

This diagram shows the flow diagram that I am seeking to create in jQuery:

enter image description here

I also wanted to make the UI as clean as possible, so I have set it that only the current question is displayed as the users works their way through the various questions.

The user can also go back to the last question at any time before they are given an answer.

The code will be used on a website.

As my code is long, I have set it out in full in my jsFiddle. The basic structure is:

HTML:

<!—question 2-->
<fieldset id="question2" style="display:none;">
    <legend>question 2</legend>
    <ul>
        <li>
            <label for="">
                <input type="radio" name="question2" value="Yes" id="rdYes" />Yes</label>
        </li>
        <li>
            <label for="">
                <input type="radio" name="question2" value="No" id="rdNo" />No</label>
        </li>
        <li>
            <input type="button" value="Back to last question" id="back2-1" />
        </li>
    </ul>
</fieldset>

jQuery:

//Test for question 2
jQuery("input[name=question2]").change(function () {

    if ($(this).val() == "Yes") {
        jQuery("#question2A").show();
        jQuery("#question2").hide();
    } else {
        jQuery("#question3").show();
        jQuery("#question2").hide();
    }
});

//Back button to question 1 from 2
jQuery("#back2-1").click(function () {
    jQuery("#q1").show();
    jQuery("input:radio").attr("checked", false);
    jQuery("#question2").hide();
});

It works, but as this is my first project it would really help me and others learning code, if someone could confirm:

  1. Is there a more efficient way to code this in jQuery?

  2. Would it be better to code it in another language, i.e. to avoid problems with older browsers?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You can simplify the javascript to be something as given below by adding some properties to the markup.

jQuery(function () {

    jQuery('input:radio[name^="question"]').change(function(){
        var $this = $(this);

        $this.closest('.question-container').hide();
        $('#' + $this.data('target')).show();
    });
});

Required changes in the markup

  1. add a class question-container to the question container ie the element with the question id like q1, question1A, etc
  2. For all radio boxes add an additional attribute data-target which will have the id of the question to be displayed if it was checked. ex Yes button in question question1A will have data-target="question1B" and No button will have data-target="question2-1A"

demo: Fiddle

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.