我正在使用 html 元素创建动态 div,我需要获取该文本框的值 这是我动态创建的内容,现在我需要获取
<div id="TextBoxContainer">
<div id="newtextbox1"> // this id is dynamic id
<div class="row cells2">
<div class="cell">
<label>Patient Name</label>
<div class="input-control text full-size">
<input type="text" id="PatientName1" placeholder="Patient Name"/> // this id is dynamic id
</div>
</div>
<div class="cell">
<label>Patient ICNo</label>
<div class="input-control text full-size" >
<input type="text" id="PatientICNo" placeholder="Patient ICNo"/>
</div>
</div>
</div>
</div>
</div>
这里我试图在 jquery 中获取值(value)
if ($("#TextBoxContainer") != null && $("#TextBoxContainer").length > 0) {
var count = 1;
$("#TextBoxContainer").each(function () {
debugger;
var Pid = "input#PatientName" + count;
var childdiv = "div#newtextbox" + count;
count++;
var patientname = $(this).closest(childdiv).children(Pid).val();
});
}
最佳答案
这里有一个解决方案 https://jsfiddle.net/p9ywL4pm/1/
if ($("#TextBoxContainer") != null && $("#TextBoxContainer").length > 0) {
var count = 1;
$("#TextBoxContainer").children().each(function () {
var Pid = "input#PatientName" + count;
var patientname = $(this).find(Pid).val();
console.log(Pid, patientname);
count++;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="TextBoxContainer">
<div id="newtextbox1">
<div class="row cells2">
<div class="cell">
<label>Patient Name</label>
<div class="input-control text full-size">
<input type="text" id="PatientName1" placeholder="Patient Name" />
</div>
</div>
<div class="cell">
<label>Patient ICNo</label>
<div class="input-control text full-size" >
<input type="text" id="PatientICNo" placeholder="Patient ICNo"/>
</div>
</div>
</div>
</div>
<div id="newtextbox2">
<div class="row cells2">
<div class="cell">
<label>Patient Name</label>
<div class="input-control text full-size">
<input type="text" id="PatientName2" placeholder="Patient Name"/>
</div>
</div>
<div class="cell">
<label>Patient ICNo</label>
<div class="input-control text full-size" >
<input type="text" id="PatientICNo" placeholder="Patient ICNo"/>
</div>
</div>
</div>
</div>
</div>
我考虑了 #TextBoxContainer
容器内的两个子元素。
将#PatientICNo
输入更改为
<input type="text" class="PatientICNo" placeholder="Patient ICNo"/>
使用class
而不是ID
,因为ID
需要唯一。
希望这对您有帮助。
关于javascript - 如何从动态创建的div中获取文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45853428/