jQuery的检索动态创建的元素的值(Jquery retrieve values of Dynam

2019-10-30 04:19发布

我有一个形式的HTML页面。
形式具有获取与输入元素,如文本框,单选,复选框等动态填充股利

现在我想找回在HTML页面,这些动态创建的元素的值 ,这样我可以把它提交到页面。

// HTML页面

<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/>");
 }

Answer 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();


文章来源: Jquery retrieve values of Dynamically created elements