鉴于此标记(MVC5)
@Html.HiddenFor(m =>m.Val1, new {id="answer_val1"})
@Html.HiddenFor(m => m.Val2, new { id = "answer_val2" })
产生以下内容;
<input data-val="true" data-val-number="The field Val1 must be a number." data-val-required="The Val1 field is required." id="answer_val1" name="Val1" type="hidden" value="6" />
<input data-val="true" data-val-number="The field Val2 must be a number." data-val-required="The Val2 field is required." id="answer_val2" name="Val2" type="hidden" value="9" />
我创建了一个字符串,用作文本框的占位符,输入答案。
@{
var answerPlaceholder = @"What is " + @Model.Val1 + "+ " +
@Model.Val2 + "?";
}
文本框标记
<div class="form-group">
@Html.LabelFor(m => m.Answer, new { @class = "col-xs-3 control-label" })
<div class="col-xs-5">
@Html.TextBoxFor(m => m.Answer, new
{
@class = "form-control",
@placeholder = answerPlaceholder,
id = "answer",
maxlength = 2
})
</div>
</div>
<div class="form-group">
<div class="col-xs-3" style="margin-left: 242px;">
<input type="submit" class="btn btn-default disabled" id="Send" name="Send" value="Send">
</div>
</div>
这些是在文档末尾加载的脚本。 显然,至少,一旦用户输入答案文本框,该按钮应该变为绿色(btn-success)但没有任何反应。我正试图在准确回答问题时启用按钮。
<script>
$(document).ready(function () {
$('#answer').focusin(function () {
$('#Send').removeClass('btn-default').addClass('btn-success');
});
$('#answer').focusout(function () {
var sum = parseInt('#answer_val1').val() + parseInt('#answer_val2').val();
if (parseInt('#answer').val() === sum) {
$('#Send').removeClass('disabled');
}
});
});
</script>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
工作脚本 我将脚本放在一个文件中并在脚本部分中呈现它。它现在按照Rahul工作
$(document).ready(function () {
$("#answer").on("focusin", (function () {
$("#Send").removeClass("btn-default").addClass("btn-success");
}));
$("#answer").on("focusout", (function () {
var sum = parseInt($("#answer_val1").val(), 10)
+ parseInt($("#answer_val2").val(), 10);
if (parseInt($("#answer").val(), 10) === sum) {
$("#Send").removeClass("disabled");
}
}));
});
答案 0 :(得分:1)
请将其更改为blur()
:
$('#answer').blur(function () {
var sum = parseInt($('#answer_val1').val()) + parseInt($('#answer_val2').val());
if (parseInt('#answer').val() === sum) {
$('#Send').removeClass('disabled');
}
});
答案 1 :(得分:0)
我认为你错过了jQuery选择器
$('#answer').focusout(function () {
var answer1 = parseInt($('#answer_val1').val(), 10);
var answer2 = parseInt($('#answer_val2').val(), 10);
var sum = answer1 + answer2;
if (answer1 === sum) {
$('#Send').removeClass('disabled');
}
});
<强> 修改 强>
您的脚本在jQuery核心文件之前呈现。请更改订单。
<script src="/Scripts/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#answer').focusin(function () {
$('#Send').removeClass('btn-default').addClass('btn-success');
});
$('#answer').focusout(function () {
var sum = parseInt('#answer_val1').val() + parseInt('#answer_val2').val();
if (parseInt('#answer').val() === sum) {
$('#Send').removeClass('disabled');
}
});
});
</script>