微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用下拉菜单更改数据输入掩码前缀

如何解决如何使用下拉菜单更改数据输入掩码前缀

我将Robin Herbot inputmask plugin用于货币输入。每当交换下拉更改事件触发时,我都想更改货币符号。但是inputmask前缀可以防止更改货币符号。我有以下代码

HTML:

 @Html.DropDownListFor(model => model.exchange,new SelectList(@ViewBag.rates,"Value","Text",4),null,new
                       {
                           @Style = "height:34px;width:370px !important;font-size: 14px;",@class = "form-control input-lg"
                       }
              )
 <input type="text"
                       class="form-control text-left monerate"
                       id="price1"
                       name="price1"
                       placeholder="₺ 0.00"
                       data-inputmask="'alias': 'numeric','groupSeparator': ',','autoGroup': true,'digits': 2,'digitsOptional': false,'prefix': '₺ ','placeholder': '0'" />
  

jQuery:

  $('input.monerate').inputmask();

  $(document.body).delegate('#exchange','change',function () {  
        exchangeID = $('#exchange :selected').val();
        if (exchangeID == 1) {
            $("#price1").inputmask({ alias: "currency",prefix: '$ ' });           
        }
        else if (exchangeID == 2) {           
            $("#price1").inputmask({ alias: "currency",prefix: '€ ' });
        }
        else if (exchangeID == 3) {            
            $("#price1").inputmask({ alias: "currency",prefix: '£ ' });
        }
        else if (exchangeID == 4) {
            $("#price1").inputmask({ alias: "currency",prefix: '₺ ' });
        }        
    });   

是否可以更改前缀?

我已经阅读了此答案,但对我不起作用:

Change the currency symbol or remove it in the inputmask currency

提琴: https://jsfiddle.net/6kzjLd7u/10/

解决方法

您需要像下面这样使用on-change函数。另外,默认情况下,select的valuestring,但是您正在将value检查为integer,这是代码无法正常工作的原因之一。

添加将选项视为整数,我们可以使用unary operator(+)-在获取值之前添加加号将使其变为整数

var exchangeID = +$(this).val(); //parse as number - by default it is string

第二,要让 Robin Herbot inputMask动态加载并从currency更改dropdown前缀,您需要在initial也是如此。由于您在jQuery静态中进行了定义,因此不能正常工作。

最后,您的代码全部固定并按预期工作,并且货币HTML在选择时发生了变化。

实时工作演示:

prefix
//by default on page load
$("#price1").inputmask({
  alias: "currency",prefix: '₺ '
});

//apply prefix on select option change
$(document).on('change','#exchange',function() {
  var exchangeID = +$(this).val(); //parse as number not - by default is string
  if (exchangeID == 1) {
    $("#price1").inputmask({
      alias: "currency",prefix: '$ '
    });
  } else if (exchangeID == 2) {
    $("#price1").inputmask({
      alias: "currency",prefix: '€ '
    });
  } else if (exchangeID == 3) {
    $("#price1").inputmask({
      alias: "currency",prefix: '£ '
    });
  } else if (exchangeID == 4) {
    $("#price1").inputmask({
      alias: "currency",prefix: '₺ '
    });
  }
});
input.monerate {
  text-align: left !important;
  width: 300px;
}

select {
  width: 300px !important;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。