I use the following code to dynamically generate input fields, which I want to parse in a jQuery UI dialog. First, the user enters systems. After a click on the "Confirm systems" button, new input fields for each system are generated. Now, I want to access the data entered in the dynamically generated input fields. However, these values are always undefined.
$(document).ready(function() {
var systemsArray;
var div = $("<div id="dialog"></div>");
div.append("<p>" +
"<label for="systems">Systems:</label>" +
"<input id="systems" size=40></input>" +
"<button id="systems_btn">Confirm systems</button>" +
"</p>");
$("body").append(div);
$("#dialog").dialog({
autoOpen: true,
modal: true,
width: 800,
height: 500,
buttons: [{
text: "Execute",
click: function() {
$("#items").children(".input").each(function() {
alert(this.val().join(", ") + ". "); // <-- val undefined
});
$(this).dialog("close");
}
}]
});
$("#systems_btn").click(function() {
$("#items").empty();
var fieldSet = $("<fieldset id="items"></fieldset>");
systemsArray = $("#systems").val().split(",");
for (const systemID in systemsArray) {
var label = $("<label for="" + systemID + "">" + "Items for " + systemsArray[systemID] + ":" + "</label>");
var input = $("<input id="" + systemID + "" size=40></input>");
fieldSet.append(label);
fieldSet.append(input);
}
$(this).parent().append(fieldSet);
});
});
<link href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
For clarity, this is what the dialog looks like before pressing the "Execute" button (which crashes, because val() is undefined):
2
Answers
That is because you are using not jQuery object, but JS object that does not have
.val()
Try doing
$(this).val()
There are two things:
1.:
.children(".input")
would select elements with the class input, thats not the case in your code, so i changed to.children("input")
which will select elements of type input2.:
this.val()
will not work as .val() is a jquery method, i changed it to$(this).val()
e.g adding a jquery wrapper to the domelement and voilâ, the alert shows the entered value 😉