I'm having troubles in getting the submitted option in a html page where I create dynamically a number of forms, the corresponding <select>
and the <option>
values within it.
This is my html
<div class="inputs_container">
</div>
my js :
var data = {
"name": "forest",
"inputs": [
{
"name": "input_1", "formats": ["JPG"]
},
{
"name": "input_2", "formats": ["TXT","ODT"]
}
]
}
var data_files = {
"resources": [
{"name": "file_1.jpg", "format": "JPG"},
{"name": "file_2.jpg", "format": "JPG"},
{"name": "text_1.txt", "format": "TXT"},
{"name": "text_2.txt", "format": "TXT"},
{"name": "odt_1.odt", "format": "ODT"},
{"name": "odt_2.odt", "format": "ODT"}
]
}
document.addEventListener('DOMContentLoaded', function() {
$.each(data.inputs, function(i, input) {
let format_in = input.formats;
var form_id = input.name;
var select_id = form_id + "_id";
var select_name = form_id + "_name";
let $h5 = $(`<h5>Select ${input.formats} file</h5>`).appendTo('.inputs_container');
$('<form>', {
"id": form_id,
"html": '<div class="input_field s12 l6"> <select id="' + select_id + '" name= "' + select_name +'"> </select> </div> <div class="col s12 l6"><button class="btn blue" type="submit"> submit</button> </div>'
}).appendTo(`.inputs_container`);
var select = document.getElementById(select_id);
var file_list_URI = serverURI + "/resources?formats=" + format_in + "";
$.getJSON(file_list_URI, function(file){
$.each(file.resources, function(j, fieldopt){
select.add(new Option(fieldopt.name, fieldopt.name));
}); // each
M.FormSelect.init(document.querySelectorAll('select'));
var input_form = document.getElementById(form_id);
input_form.onsubmit = function(e) {
e.preventDefault();
var input_file = input_form.select_name.value;
console.log(" FORM SUBMIT " + input_file);
}
});
});
});
The code renders two select fields (with the correct options), one for JPG
and one for TXT, ODT
file formats. But when I click any of the two submit buttons I get
Uncaught TypeError: input_form.select_name is undefined
Could anyone help me in fixing this error?
Thank you in advance
The error you have occurs on this line:
var input_file = input_form.select_name.value;
The error message Uncaught TypeError: input_form.select_name is undefined
means select_name
is undefined.
select_name
here, is not the variable you declared a couple lines above. It is a property of input_form
, the element found by document.getElementById(form_id);
.
The select element you wish to target is a child of that form element... So you have to target it and .querySelector() is the right method to do it.
So change it for:
var input_file = input_form.querySelector("[name="+select_name+"]").value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.