我正在构建一个Web应用程序,该应用程序将利用依赖于三重关系的下拉菜单(请考虑“国家/地区”->“州/州”>“城市”),并允许用户更改其详细信息。
这是下拉结构的代码段(请注意,默认选项的dropAccounts
值为'test'
):
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name="dropAccounts" class="dropAccounts">';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value="test">---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value=' . $account->getId(). '>' . $account->getName() . '</option>';
}
} else {
echo '<option value="0">---No accounts available---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name="dropProperties" class="dropProperties" id="dropProperties">';
echo '<option selected="selected">---Select a webproperty---</option>';
echo '</select>';
//for available profiles
echo '<br> Available Profiles: ';
echo '<select name="dropProfiles" class="dropProfiles" id="dropProfiles">';
echo '<option selected="selected">---Select a profile---</option>';
echo '</select>';
我正在使用onchange
事件和AJAX从第一个下拉菜单dropAccounts
(国家)提取值,并使用该值索引API调用以填充第二个下拉菜单dropProperties
(状态),如下所示:
$(".dropAccounts").change(function()
{
var accountID = $(".dropAccounts").val(); //gets the account ID from drop-down value
populateProperties(accountID);
});
function populateProperties(accountID) {
$.ajax
({
type: "POST",
url: "propertyID.php",
data: {
'accountID' : accountID
},
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
// Populate profiles after properties load
populateProfiles($(".dropProperties").val());
}
});
}
AJAX请求将替换dropProperties
(状态)下拉列表的内容,然后以类似的方式调用该populateProfiles()
函数以填充最终的下拉列表dropProfiles
(城市):
function populateProfiles(propertyID) {
$.ajax
({
type: "POST",
url: "profileID.php",
data: {
'propertyID' : propertyID
},
cache: false,
success: function(html)
{
$(".dropProfiles").html(html);
}
});
}
此方法可以正常工作,以使用正确的dropAccounts
(国家/地区)填充前两个下拉列表dropProperties
,但是在第三个下拉列表dropProfiles
(城市)中检索到的值不是从中获取的值dropProperties
。
在profileID.php脚本中:
<?php
$propertyID = $_POST['propertyID'];
echo '<option> Property ID: ' . $propertyID . '</option>';
?>
的值从默认选项中$propertyID
返回。我仔细检查了所有变量,但感到很困惑。我想知道是否有经验更丰富的人能找出问题所在?'test'
dropAccounts
提前致谢!
看起来问题在于您正在使用类选择器,这意味着您可能会返回多个元素,在这种情况下,我不确定如何.val()
处理一组元素。
您还应该通过获取所选选项的值来获取值。
尝试像这样使用它...
var accountID = $(".dropAccounts").first().find('option:selected').val();
我们需要一种更好的方法来选择要获取其值的元素,因此,我认为最好的选择是使用可以用来选择该元素的元素来修改该元素,并确保没有其他问题。
修改这行 echo '<select name="dropAccounts" class="dropAccounts">';
我建议添加一个在此页面上唯一的ID,以便我们可以准确地使用jQuery来确保仅选择此元素。
echo '<select name="dropAccounts" class="dropAccounts" id='someuniqueid'>';
然后使用jQuery,将更容易获得价值...
var accountID = $("#someuniqueid > option:selected").val()
//修复语法错误
因此,基本上,这就是说要让jQuery获取IDsomeuniqueid
为您选择元素的元素,然后它将获取该selected option
选择元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句