2017-09-01 35 views
1

我正在工作一个MVC ASP.Net应用程序,用户需要填写表单。有一个文本框,用户必须输入他们在当前工作中工作了多久。如果用户进入不到三年,那么我需要他们以前的工作表格的一部分才能弹出。加载页面时,此部分用jQuery隐藏。文本框中的特定文本是否可以触发jQuery事件?

用户可以输入0到99之间的数字,否则会触发错误。出于这个原因,我不能真正使用下拉菜单来做到这一点;用户输入值更有意义。

输入到文本框中的特定值是否可以触发jQuery事件发生?我一直在试图找到解决我的问题的方法,而且我对jQuery的经验不足也影响了我的工作能力。我真的可以使用一些指导,因为从逻辑上讲,这段代码在我的脑海中是有道理的,我不知道自己出错的地方。

MVC模式

[Required] 
    [Range(0, 99)] 
    [Display(Name = "Number of Years at Current Employer")] 
    public int Buy1YearsAtEmployer { get; set; } 

HTML /剃刀语法:

<div class="form-group required col-md-4"> 
     @Html.LabelFor(model => model.Buy1YearsAtEmployer, new { @class = "control-label" }) 
     @Html.TextBoxFor(model => model.Buy1YearsAtEmployer, new { id = "applicantYearsAtCurrentEmployer", @Value = "", @class = "form-control" }) 
     @Html.ValidationMessageFor(model => model.Buy1YearsAtEmployer, "Please enter a valid number of years", new { @class = "text-danger" }) 
    </div> 


<div class="container" id="applicantPreviousWork"> 
     <h4>Your Previous Employment</h4> 
     <!--More code--!> 
    </div> 

jQuery的

$('#applicantYearsAtCurrentEmployer').focusout(function() { 
    if ($(Buy1YearsAtEmployer).val() <= 3) { 
     $('#applicantPreviousWork').show(); 
    } 
    else { 
     $('#applicantPreviousWork').hide(); 
    } 
}); 
+1

这样的:'$(Buy1YearsAtEmployer)'应该是'$( '#applicantYearsAtCurrentEmployer')'或'$(本)'因为回调具有输入的执行上下文 –

回答

0

这将正常工作。将Buy1YearsAtEmployer更改为thisSee my fiddle

<input id="applicantYearsAtCurrentEmployer"> 

<div id="applicantPreviousWork" style="display:none;"> 
Years worked... 
</div> 

而且JS:

$('#applicantYearsAtCurrentEmployer').focusout(function() { 
    if ($(this).val() <= 3) { 
     $('#applicantPreviousWork').show(); 
    } 
    else { 
     $('#applicantPreviousWork').hide(); 
    } 
}); 
0

使用上的文本框jQuery的变化功能来捕捉价值。然后,根据该值打开弹出窗口。对于输入文本字段,更改事件在值更改且文本字段失去焦点时触发。

https://api.jquery.com/change/

$(document).ready(function(){ 
$('#applicantYearsAtCurrentEmployer').change(function() { 
    var currVal = $(this).val(); 
//Now put your logic here. 
});}); 
相关问题