使用Javascript从动态下拉列表中捕获选定的值 [英] Capture Selected Values from Dynamic Drop-down Lists using Javascript
问题描述
我正在尝试从表单中的动态下拉列表中获取值,但是我的代码无法正常工作.
I'm trying to get the value from dynamic drop-down list in my form, but my code isn't working.
View.php
<div class="input_fields_wrap">
<input type="button" class="btn btn-info add_field_button" value="Tambah Cara Pengolahan" /> <br /><br />
</div>
<div class="service-container" data-service=
"<div class='form-group'>
<select class='form-control' style='width:88%; display:inline-block; margin-right:10px;' name='cara_pengolahan[]' required>
<option value=''>No Selected</option>
<?php foreach($pengolahan as $row):?>
<option value='<?php echo $row->id_pengolahan;?>'><?php echo $row->cara_pengolahan;?></option>
<?php endforeach;?>></div>
</select>
<button class='btn btn-danger closebtn remove_field'><b>×</b></button>
</div>"
</div>
Javascript.js
Javascript.js
$('.service-container').each(function() {
var container = $(this);
var service = container.data('service');
// Service variable now contains the value of html + php variable;
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append(service);
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
var cara_pengolahan = document.forms[0].elements["cara_pengolahan[]"];
if(typeof cara_pengolahan !== 'undefined'){
for (var i=0; i<cara_pengolahan.length; i++) {
console.log(cara_pengolahan[i].value);
}
}
当有一个动态下拉列表时,它返回它的所有数组值.但是我想要捕获的是该下拉列表的选定值.
When there is one dynamic drop-down list, it returns all the array values of it. But what I want is to capture the selected value of that drop-down list.
并且当有多个动态下拉列表时,它将返回该下拉列表的正确选择值.
And when there are more than one dynamic drop-down lists, it returns the correct selected values of that drop-down lists.
如何捕获所有动态下拉列表中的选定值? 预先感谢.
How to capture the selected value of all the dynamic drop-down lists? Thanks in advance.
推荐答案
要检查是否存在动态下拉列表,可以简单地检查选择器是否存在 与
To check if there is a dynamic Drop down you can simple check if the selector exists with
$('#elemId').length>0
对于选定的值,您可以使用$(#selectorid").find("option:selected").val();
And for selected value you can use $("#selectorid").find("option:selected").val();
这篇关于使用Javascript从动态下拉列表中捕获选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!