3

I have many of these multiple choice selections in a control panel, and I wish to get the data entered into the text fields using JQuery. Preferably the format would be Question, AnswerOpt1, AnswerOpt2.... I have tried the code supplied below, and some variations of it, but have been unsuccessful.

HTML

<div class="formRow">
    <label>Multiple Choice: </label>
    <div class="formRight">
        Question: <input type="text" class="MCQuestion" />
    </div>
    <div class="formRight MCAns">
        Answer Option1: <input type="text" class="MCAnswer"/>
    </div>
    <div class="formRight MCAns">
        Answer Option2: <input type="text" class="MCAnswer"/>
    </div>
</div>

<div><a href="#" id="Save">Save</a></div>
<div id="log"></div>

Javascript

$("#Save").on("click",function() {
    $(".MCQuestion").each(function(){
        if($(this).val()!=""){
            $(this).parent().find(".MCAnswer").each(function(){
                $('#log').after($(this).val());
            });
        }
    });
return false;
});
Blease
  • 1,380
  • 4
  • 38
  • 64

2 Answers2

4

When you're traversing up to the parent element of .MCQuestion you're only getting to .formRight. Use closest to go up to the .formRow then back down to each .MCAnswer:

$("#Save").on("click",function() {
    $(".MCQuestion").each(function(){
        if($(this).val()!=""){
            $(this).closest(".formRow").find(".MCAnswer").each(function(){
                $('#log').after($(this).val());
            });
        }
    });
    return false;
});
freejosh
  • 11,263
  • 4
  • 33
  • 47
1

Replace

$('#log').after($(this).val());

with

$('#log').append($(this).val() + ' ');

EDIT

Also this line is a problem

$(this).parent().find(".MCAnswer")

replace with

$(this).closest('.formRow').find(".MCAnswer")

.parent gets the immediate an parent of the element in question. But elements with class MCAnswers are present inside the formRow element and not the immediate parent.

Also a better idea to cache your selectors when using it multiple times.

Code

$("#Save").on("click", function () {
    $(".MCQuestion").each(function () {
        var $this = $(this),
            value = $this.val();
        if (value != "") {
            $this.closest('.formRow').find(".MCAnswer").each(function () {
                $('#log').append(value + ' ');
            });
        }
    });
    return false;
});

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105