当我用javascript选择默认下拉值时,它不会触发更改

问题描述:

我有一个文本框和一个日期文本框。我试图用Javascript连接它们,但是我遇到了一个问题。我的脚本是:当我用javascript选择默认下拉值时,它不会触发更改

  <script> 
      $("#solDate").change(function() { 
       if ($(this).val().trim() == '') { 
        $("#caseStatus").val('In Progress'); 
        $("#solvedBy").val('Pick an option'); 
        $("#solvedBy").change(); 
       } 
       else if ($(this).val().trim() != '' && $("#solvedBy").val().trim() == '') { 
        $("#caseStatus").val('Solved'); 
        $("#solvedBy").val('Please, pick the issue solver'); 
        $("#solvedBy").change(); 
       } 
      }); 
     </script> 

当从日历中挑选日期时,应该设置一个值'请选择问题解决者'。它完美的作品。

然后,如果您偶然输入日期,它应该返回以前的默认值 - “选择一个选项”。

在这两种情况下,都会触发更改。

然后,另一个触发器正在侦听这些更改。

<script> 
     $("#solvedBy").change(function() { 
      if ($(this).val() == 'Please, pick the issue solver') { 
       $("#saveBtn").attr('disabled', true); 
       $("#slvByValMsg").text('You have solution date and no solver'); 
      } 
      else if ($(this).val().trim() == '' && $("#solDate").val().trim() != '') { 
       $("#saveBtn").attr('disabled', true); 
       $("#slvByValMsg").text('You have solution date and no solver'); 
      } 
      else { 
       $("#saveBtn").attr('disabled', false); 
       $("#slvByValMsg").text('');; 
      } 
     }); 
    </script> 

我的故障排除后,事实证明,第一个脚本的第一个if语句不会触发更改。这可能是因为它无法识别值为''的默认选择选项。我不确定。无论如何,当我从文本字段中删除日期时,其他文本字段的值不会更改为“选择一个选项”,而是更改为“”。

HTML代码:

@Html.LabelFor(model => model.Solution_Date, htmlAttributes: new { @class = "control-label col-md-2" })<sup> 1 </sup> 
<div class="col-md-10"> 
     @Html.TextBoxFor(model => model.Solution_Date, new { @id = "solDate", @class = "one", @type = "datetime" }) 
     <br /> 
     @Html.ValidationMessageFor(model => model.Solution_Date, "", new { @class = "text-danger" }) 
</div> 

@Html.LabelFor(model => model.Solved_by, htmlAttributes: new { @class = "control-label col-md-2" }) 
<div class="dropdown"> 
    @Html.DropDownListFor(model => model.Solved_by, (IEnumerable<SelectListItem>)ViewBag.SlvBy, "Pick an option", new { @id = "solvedBy" }) 
<br /> 
@Html.ValidationMessage("Solved_by", "", new { @id = "slvByValMsg", @class = "text-danger" }) 
</div> 

我知道有可能是更好的方法来做到这一点,但我正在寻找一个解决,主要是因为我不知道为什么这种变化不会引发触发器。

在此先感谢!

+1

你能发布html吗? – user2399432

+0

好吧,我已经添加了它。奇怪的是,当我评论第二个脚本的第二个if语句时,这个事情就起作用了。但由于其他原因,我需要第二条if语句。 – GeorgiG

我找到了导致问题的原因。事实证明,

$("#solvedBy").val('Pick an option'); 

无法执行,因为这是默认选项,它后面的值是''。这必须与.change()触发器混淆,并在其他脚本中造成严重破坏。

我改成了

$("#solvedBy").val(''); 

...,一切工作现在。