0

I have some code for a personality quiz but I'm not sure how I can increase the size of this code without dragging it on. Here is the HTML code:

<h3>1. How old are you?</h3>
<input type="radio" mess="whats up" name="q1" value="A" class="correct"/> A. 1-50.
<input type="radio" mess="You did it" name="q1" value="B" class="correct"/> B. 50-100.
<input class="button" type="submit" value="Submit" /> <input type="reset" value="Clear" />
<p class="answer"></p>

And here is the JavaScript code:

var checked;
$('.button').click(function(){
    checked = $('input:checked').attr('mess');
    $('.answer p').remove();
    $('.answer').append("<p>"+checked+"</p>");
});
$('input[value="Clear"]').click(function(){
    $('.answer p').remove();    
});

I want do do that same kind of thing but for a quiz with maybe five questions and all the questions that the user answers turns into one big final answer for them and the answer is different depending on which radio buttons they choose. So is there any other way I can do that but without repeating the code for each radio button?

Captain John
  • 1,859
  • 2
  • 16
  • 30
user3135197
  • 35
  • 1
  • 6
  • call a function to do validation & store scores and other stuffs in global variable – Abraham K Jan 05 '14 at 17:59
  • 1
    For custom attributes, you should use the HTML5 data attribute, i.e. `data-mess` instead of `mess`. You can then access it with the jQuery `.data()` method. – Terry Jan 05 '14 at 18:14
  • data-mess is what will happen here quickly indeed. Perhaps the OP should look into something that provides more structured data-bindings like Backbone.js or Angular.js – Max Jan 05 '14 at 18:17
  • May I ask: what does mess do? –  Jan 05 '14 at 18:25
  • Does this help? http://jsfiddle.net/2pG9R/ – maxedison Jan 05 '14 at 18:29
  • 1
    @Max -- I get the impression that those frameworks will be way over the OP's head at this point. – maxedison Jan 05 '14 at 18:30
  • @maxedison You are probably right. But I think the earlier you have some exposure for best practices the better for your career. – Max Jan 05 '14 at 18:32

2 Answers2

0

As noted in the comments, use data-* custom attributes instead of your own attributes in conjunction with this in your jQuery to make your code re-usable. I would also recommend containing each question in its own element like a wrapping div.

$('.button').click(function () {
    var checked = $(this).parent().find('input:checked').data('mess');
    $(this).parent().find('.answer p').remove();
    $(this).parent().find('.answer').append("<p>" + checked + "</p>");
});
$('input[value="Clear"]').click(function () {
    $(this).parent().find('.answer p').remove();
});

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
0

I made a function for you because it looked like fun :D

Here's a working jsFiddle

And the code:

// Add as many questions as you like!
addRadioQuestion("How old are you?", ["1-50","50-100"]);

// Question is a string and options is an array of strings
function addRadioQuestion (question, options) {

    if ($.isArray(options) && typeof question === "string") {
        // Get the number of previous questions
        var qNum = $('.question').length + 1;

        // Create a containing div
        var questionDiv = $('<div/>').addClass('question');

        // Add title to questionDiv
        questionDiv.append($('<h3/>').text(qNum + ". " + question));

        // Add a radio button for each option
        for (var i = 0; i < options.length; i++) {
            // Converting from numbers to lettters using ASCII
            var optionVal = String.fromCharCode(65 + i);

            var option = $('<input/>')
                .attr('type', 'radio')
                .attr('data-message', options[i])
                .attr('name','q' + qNum)
                .attr('value', optionVal)
                .addClass('correct')

            var optionText = $('<label/>')
                .text(optionVal + '. ' + options[i])
                .append(option);

            questionDiv.append(optionText);
        }

        // Append Submit Button
        questionDiv.append($('<input/>')
            .addClass('button')
            .attr('type', 'submit')
            .attr('value', 'Submit')
            .on('click', function() {
                var theirAnswer = $(this).closest('.question').find('input:checked').attr('data-message');
                console.log($(this).closest('.question').find('input:checked').attr('data-message'))
                $(this).siblings('.answer').text(theirAnswer);
            }));

        // Append Clear Button
        questionDiv.append($('<input/>')
            .addClass('button')
            .attr('type', 'reset')
            .attr('value', 'Clear')
            .on('click', function() {
                $(this).closest('.question').find('input:checked').prop('checked', false);
                $(this).siblings('.answer').text("");   
            }));

        // Append answer paragraph
        questionDiv.append($('<p/>').addClass('answer'));

        questionDiv.appendTo('body');
    }
}

It looks pretty basic without any CSS, but you can make it looks pretty if you want!

tylerargo
  • 1,000
  • 10
  • 13