我希望在单击单选按钮时显示警报。
我的单选按钮:
<div class="genericFormField">
New:@Html.RadioButtonFor(m => m.Form.InstallType, 1, Model.InstallationHeader.InstallType == 1 ? new { Checked = "checked" } : null )
Pool:@Html.RadioButtonFor(m => m.Form.InstallType, 2, Model.InstallationHeader.InstallType == 2 ? new { Checked = "checked" } : null)
Refurb:@Html.RadioButtonFor(m => m.Form.InstallType, 3, Model.InstallationHeader.InstallType == 3 ? new { Checked = "checked" } : null)
</div>
因此,如果选择了新的单选按钮,我想要一个提示说“NEW”,否则什么也没有。
通常这很容易,因为你有身份证,但在这种情况下没有身份证?
因为这是 RadioButtonFor。
谢谢
新代码
完整代码:
$('input[name="Form.InstallType"]').on('change', function() {
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') {
var validOptions = "@Url.Action("SerialProdNumStockSiteAutoComplete", "Ajax")?stocksitenum=LW&model=" + $("#Form_Prod_Num").val();
previousValue = "";
$('#abc').autocomplete({
autoFocus: true,
source: validOptions,
}).change(function(){
var source = validOptions;
var found = $('.ui-autocomplete li').text().search(source);
console.debug('found:' + found);
var val = $('input[name="Form.InstallType"]:checked').val();
if (found < 0 && val === '1') {
$(this).val('');
alert("Please choose from auto complete");
}
});
}
});
这行得通,但是如果单选按钮在页面加载时不起作用,我必须单击另一个单选按钮,然后单击“新建”,然后它才会起作用。
如果它已经被检查而不是检查时,它有可能工作。
最佳答案
@Html.RadioButtonFor 使用 name
和 id
属性创建一个合适的 input
。
您可以通过这种方式访问值:
$('input[name="Form.InstallType"]:checked').val();
不确定生成的 radio 名称,因为它是一个内部变量。
呈现页面并查看生成的名称。这就是我的情况。
现在,关于您的警报。您需要监听 change
事件。
$('input[name="Form.InstallType"]').on('change', function()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === '1') alert('New');
});
为什么是“1”?因为您已经在 ASP.NET 代码中设置了它。 它应该是这样的。
<div class="genericFormField">
New: @Html.RadioButtonFor(m => m.Form.InstallType, 'new')
Pool: @Html.RadioButtonFor(m => m.Form.InstallType, 'pool')
Refurb: @Html.RadioButtonFor(m => m.Form.InstallType, 'refurb')
</div>
<script>
$(document).ready(function() {
AlertIfNewIsSelected(); // Check if it is selected on page load. According to the question in comments.
$('input[name="Form.InstallType"]').on('change', AlertIfNewIsSelected);
});
function AlertIfNewIsSelected()
{
var val = $('input[name="Form.InstallType"]:checked').val();
if (val === 'new') alert('New');
}
</script>
当然,这一切都可以不使用 jQuery 实现。
关于javascript - 如果选择单选按钮显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30593335/