2013-06-25 28 views
1

我在控制面板中有很多这些多项选择选项,我希望使用JQuery将输入的数据输入到文本字段中。格式最好是Question,AnswerOpt1,AnswerOpt2 ....我已经尝试了下面提供的代码和它的一些变体,但一直不成功。JQuery获取div中所有输入的值

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; 
}); 
+1

使用附加,而不是后 –

回答

1

更换

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

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

编辑

而且这条线是一个问题

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

更换

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

.parent获取有关元素的直接母公司的。但类别MCAnswers的元素存在于formRow元素中,而不是直接父元素。

在多次使用时缓存选择器也是一个更好的主意。

代码

$("#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

+0

谢谢,我已经做到了!但这并不能真正帮助我的问题? –

+0

@JoshLuke请检查ediut –

3

当你穿越最多你只能得到以.formRight.MCQuestion父元素。使用closest去到.formRow然后回落到每一个.MCAnswer

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