【问题标题】:Can specific text in a textbox trigger a jQuery event?文本框中的特定文本可以触发 jQuery 事件吗?
【发布时间】:2018-02-10 22:43:47
【问题描述】:

我正在使用用户需要填写表单的 MVC ASP.Net 应用程序。有一个文本框,用户必须在其中输入他们在当前工作中工作了多长时间。如果用户输入的时间少于三年,那么我需要弹出他们以前的工作表格的一部分。当页面加载时,这个部分被 jQuery 隐藏。

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

输入到文本框中的特定值可以触发 jQuery 事件吗?我一直在尝试找到解决问题的方法,而我缺乏 jQuery 经验确实影响了我使其工作的能力。我真的可以使用一些指导,因为从逻辑上讲,这段代码在我的脑海中是有意义的,我不知道我哪里出错了。

MVC 模型

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

HTML/Razor 语法:

  <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();
    }
});

【问题讨论】:

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

标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

这会很好。将 Buy1YearsAtEmployer 更改为 this。 See 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();
    }
});

【讨论】:

    【解决方案2】:

    使用文本框上的 jquery 更改功能来捕获值。然后,根据值打开弹出窗口。对于输入文本字段,当值更改并且文本字段失去焦点时会触发 change 事件。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多