开发者

How to add a very dynamic inputs in the dynamic divs by jQuery

I have php code similar to this below:

foreach ($questions as $q){
    foreach ($answers as $a)
    {
        echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$a['answer'].'" />';

        echo '<div id="newAnswerTextBox'.$a['question_id'].'">';
    }
    echo '<button id="addNewAnswer'.$q['id_question'].'">Add new answer</button>';
}

exemplary output:

<input type="text" id="1_1" value="question1 answer1">
<input type="text" id="1_2" value="question1 answer2">
<input type="text" id="1_3" value="question1 answer3">
<div id="newAnswerTextBox1">
<button id="addNewAnswer1">Add new answer</button>

<input type="text" id="2_4" value="question2 answer4">
<input type="text" i开发者_如何学Pythond="2_5" value="question2 answer5">
<input type="text" id="2_6" value="question2 answer6">
<div id="newAnswerTextBox2">
<button id="addNewAnswer2">Add new answer</button>

desired extra input after clicking first button "Add new answer":

<input type="text" id="1_4" value=" ">

The main question is how to add by jquery new inputbox. I can't find similar solution I'm learning yet jquery.

I found this below but I need to add dynamic input in right div.

var num = 0;
$("#addNewAnswer").click(function() {
    num++;
    $("#newAnswerTextBox").html("<input type=\"text\" id=\"" + num + "\" />");
});


First give all button a common class say add_answer

Second on click of the button add textbox to its parent div like this

var num = 0;
$(".add_answer").click(function() {
    num++;
    $(this).parent().append("<input type=\"text\" id=\"" + num + "\" />");
});


$("button[id^='addNewAnswer']").click(function(){
  var p = new RegExp(".*?(\\d+)",["i"]);
  var questionID = parseInt(p.exec(this.id)[1]);
  var answerID = parseInt($("input[id^='"+questionID+"_']:last").attr("id").split("_")[1]);
  answerID++;
  var newTextBoxID = questionID +"_"+answerID;   
$("<input/>").attr({"type":"text","id":newTextBoxID}).insertBefore("#newAnswerTextBox"+questionID);
});

DEMO


Simply add tell javascript what was the last number that entered, using PHP:

foreach ($questions as $q){
    foreach ($answers as $a)
    {
        echo '<input type="text" id="'.$a['question_id'].'_'.$a['id_answer'].'" value="'.$a['answer'].'" />';

        echo '<div id="newAnswerTextBox'.$a['question_id'].'">';
    }
    echo '<script type="text/javascript">var num'.$q['id_question'].' = '.count($answers).';';
    echo '<button id="addNewAnswer'.$q['id_question'].'">Add new answer</button>';
}

Or something similar...

Good luck :)


First of all you have to close the "newAnswerTextBox" divs. Replace the following line:

echo '<div id="newAnswerTextBox'.$a['question_id'].'" />';

And the solution of jimy is just fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜