如何获得在while循环中创建的textarea的值?



我有问题,我无法访问在php的while循环中创建的值我的文本区域。我猜它们没有在DOM中注册。对于附加到它的按钮也是如此。我知道,由于这个动态创建,我必须通过带有特殊事件监听器的jquery访问按钮。我得到了我需要的所有ID,但我无法得到textarea的值,即使我能得到它的正确ID,因为它似乎只是空的。由于我不能在这里张贴php提琴,这里有一个例子来说明它是如何工作的。

include"connection.php";
$stuff="here is the query";     
for ($n = 1; $n <= 13; $n++) {
$xy=$con->query($stuff);
while($row=mysqli_fetch_assoc($xy))
{
$value = $row['value'];
echo"<div id='$n' class='antworten'>$value<br>
<div id='notizcontainer$n' class='antwortcontainer'>Notizen:</div>
<div class='antwortcontainer' id='notizerstellen$n'>Notiz erstellen:<br>
<textarea id='notizfeld' class='textarea'></textarea><br>
<button id='absenden' class='notizabsenden'>Notiz absenden</button></div>
</div>";
}
}

jQuery:

$(document).on('click', '.notizabsenden', function(){ //do this bc its not registered and .click() is not working, also I need the click event on the button class to know on which button the event is going on
var parentid = $(this).parent().attr('id'); //get parentid of button
var notizid = $('#'+parentid).find('textarea').attr('id'); //find id of textarea of parent 
var notiz = $('#'+notizid).val(); //this should give me the text of the textarea... but it returns empty/blank
console.log(notizcontainer); //this turns out correct
console.log(parentid); //this turns out correct
console.log(notiz); //this returns empty/blank as if the textarea has nothing in it... which it does

问题是因为PHP循环中的HTML在多个元素必须是唯一的情况下重用相同的id。要解决这个问题,请从所有重复的内容中删除id属性。

要解决访问textarea内容的问题,需要使用DOM遍历来查找与已单击的button相关的textarea。为此,可以使用closest()find()的组合,如下所示:

$(document).on('click', '.notizabsenden', function(e) {
const $btn = $(e.currentTarget);
const notiz = $btn.closest('.notizerstellen').find('.notizfeld').val();

console.log(notiz);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<!-- generated by your PHP loop... -->
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Lorem ipsum</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Dolor sit</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>
<div class="antworten">$value<br>
<div class="antwortcontainer">Notizen:</div>
<div class="notizerstellen">
Notiz erstellen:<br />
<textarea class="notizfeld textarea">Amet consectetur</textarea><br />
<button class="notizabsenden">Notiz absenden</button>
</div>
</div>

最新更新