[英]How can i get text option from AJAX generated select dropdown using jQuery?
I am trying to populate dropdown using AJAX and trying to get the text field of select dropdown along with the value of that selection. 我试图使用AJAX填充下拉列表,并尝试获取选择下拉列表的文本字段以及该选择的值。 I am getting the text but only the preselected text. 我正在获取文本,但只有预先选择的文本。 If i change the selection in second dropdown the text corresponding to the value doesnt change. 如果我在第二个下拉菜单中更改选择,则对应于该值的文本不会更改。 Here is what i have tried - 这是我尝试过的-
< script type = "text/javascript" > function AjaxFunction() { var httpxml; try { // Firefox, Opera 8.0+, Safari httpxml = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { httpxml = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httpxml = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } function stateck() { if (httpxml.readyState == 4 && httpxml.status == 200) { //alert(httpxml.responseText); var myarray = JSON.parse(httpxml.responseText); // Remove the options from 2nd dropdown list for (j = document.testform.subcat_id.options.length - 1; j >= 0; j--) { document.testform.subcat_id.remove(j); } for (i = 0; i < myarray.data.length; i++) { var optn = document.createElement("OPTION"); optn.text = myarray.data[i].Description; optn.value = myarray.data[i].Component_ID; document.testform.subcat_id.options.add(optn); document.getElementById("des").value = $("#subcat_id option:selected").text(); // here i get the text } } } // end of function stateck var url = "production_add_filter.php"; var cat_id = document.getElementById('cat_id').value; url = url + "?cat_id=" + cat_id; url = url + "&sid=" + Math.random(); httpxml.onreadystatechange = stateck; //alert(url); httpxml.open("GET", url, true); httpxml.send(null); } < /script>
<form name="testform" method='POST' action="production_add_exec.php"> <label>Select Category :</label> <select name=cat_id id="cat_id" onchange=AjaxFunction(); required> <option value=''>Select One</option></select> <label>Select Component :</label> <select name=subcat_id id='subcat_id' required> <option value=''>Select One</option> </select> <input id="des" type=text>//updated text value required here ! <input type=submit value=submit> </form>
Updated code - 更新的代码-
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].Description;
optn.value = myarray.data[i].Component_ID;
document.testform.subcat_id.options.add(optn);
document.getElementById("des").value = $("#subcat_id option:selected").text();
}
document.getElementById("des").value = $('#subcat_id').change(function() {
$('#des').val($('#subcat_id option:selected').text());
});
}
}
try to add change event to second select: 尝试将更改事件添加到第二选择:
$('#subcat_id').change(function() {
$('#des').val($('#subcat_id option:selected').text());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.