Jquery检索动态创建的元素的值

时间:2010-03-17 10:12:33

标签: forms jquery unobtrusive-javascript

我有一个带有表单的html页面 表单包含Div,可以使用文本框,广播,复选框等输入元素动态填充。

现在我想 在Html页面中检索这些动态创建的元素的值 ,以便我可以将其提交到页面。

// HTML PAGE

<script type="text/javascript">
         $(function() {
            populateQuestions();
         });    

         $("#submit_btn").click(function() {
             // validate and process form here
            //HOW TO ??retrieve values???
             var optionSelected = $("input#OptionSelected_1").val();// doesn't work?

            // alert(optionSelected); 
             postAnswer(qid,values);//submit values 
             showNextQuestion() ;// populate Div Questions again new values
         });  


     </script>

    <form action="" name="frmQuestion">
    <div id="Questions" style="color: #FF0000">

    </div>

//问题DIV生成脚本示例单选按钮

//questionText text of question
//option for question questionOptions
// **sample call**
 var question = createQuestionElement("1","MCQ", "WHAT IS ABCD??", "Opt1$Opt2$Opt3");
 question.appendTo($('#Questions'));


function createQuestionElement(id, type, questionText, questionOptions) {
    var questionDiv = $('<div>').attr('id', 'Question');
    var divTitle = $('<div>').attr('id', 'Question Title').html(questionText);
    divTitle.appendTo(questionDiv);    
    var divOptions = $('<div>').attr('id', 'Question Options');     
    createOptions(id, "radio", questionOptions, divOptions);
    divOptions.appendTo(questionDiv);
    return questionDiv;
}

function createOptions(id, type, options, div) {
    var optionArray = options.split("$");
    // Loop over each value in the array.
    $.each(
 optionArray, function(intIndex, objValue) {
     if (intIndex == 0) {
         div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' checked='checked'  value='" + objValue + "'>"));
     } else {
         div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' value='" + objValue + "'>"));
     }
     div.append(objValue);
     div.append("<br/>");
 }

1 个答案:

答案 0 :(得分:1)

您正在多次创建相同的输入,因为您正在拆分选项数组,您正在这样做:

<input type='radio' name='OptionSelected_1' checked='checked'  value='Opt1'>
<input type='radio' name='OptionSelected_1' value='Opt2'>
<input type='radio' name='OptionSelected_1' value='Opt3'>

您目前正在使用#通过ID获取,而不想通过name获取并获取:checked项,如下所示:

var optionSelected = $("input[name=OptionSelected_1]:checked").val();