隐藏/禁用Ajax表单的提交按钮,直到从下拉列表中做出选择

Hiding/Disabling the submit button for an Ajax form until a selection is made from dropdown list

本文关键字:下拉列表 选择 Ajax 禁用 表单 按钮 提交 隐藏      更新时间:2023-09-26

我想隐藏(或禁用)Ajax表单的提交按钮,直到从下拉列表(@Html.DropDownList)中进行选择

的形式是这样的:

@using (Ajax.BeginForm("RoleAddToUser", "Roles", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "middle_column", HttpMethod = "POST" }, new { id = "RoleAddToUserForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>
    User : @Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.Users, "Select ...")
    Role : @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")
</p>
<input type="button" name="SubmitBtn1" value="Send" onclick="$('#RoleAddToUserForm').submit(); " />
}

我假设有一种方法可以检测除"select…"之外的值。(默认的),然后启用/显示提交按钮,使用Javascript。

我也明白这对于大多数Js粉丝来说可能是微不足道的,但我通常不使用cshtml或javascript,这是非常令人沮丧的lol

如果它有帮助,问题文件是来自mvc程序的cshtml

为按钮添加disabled="disabled"属性。这样它就会被禁用。当你想启用它,使用jQuery启用$('#id').removeAttr('disabled')

使用change event来检测值

$("select").on("change",function(){
if($(this).val()){
$("input[name='SubmitBtn1']").prop("disabled",false);
}
esle{
$("input[name='SubmitBtn1']").prop("disabled",true);
}
});

我相信有更优雅的方式来做到这一点,但这似乎工作:

我将id="SubmitBtn1" style="display:none" 添加到按钮中,然后使用

<script type="text/javascript">
//On change
$('#UserName').change(
function checkValue() {
    //Check if the dropdownlist's value is equal to the default
    if ($('#UserName').val() == "") {
        //if it is, hide it/keep hidden            
        hide_item('SubmitBtn1');
        return
    }
    //otherwise show it
    show_item('SubmitBtn1');
});

function show_item(id) {
    var el = document.getElementById(id);
    el.style.display = 'inline-block';
};
function hide_item(id) {
    var el = document.getElementById(id);
    el.style.display = 'none';
};
</script>

反馈?