Jquery - не запускать функцию, если значение выбранной опции установлено в значение c - PullRequest
0 голосов
/ 04 февраля 2020

У меня есть функция jquery, которая обнаруживает и форматирует валюту, если для типа данных поля ввода задана валюта. Как сделать так, чтобы эта функция не выполнялась, если для другого значения поля выбора установлено значение BT C, вот коды. JS

$("input[data-type='currency']").on({
    keyup: function() {
      formatCurrency($(this));
    },
    focusout: function() {
      formatCurrency($(this), "blur");
    }
});

и вот мой форматВалютная функция

function formatNumber(n) {
  return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
} // format number 1000000 to 1,234,567

function formatCurrency(input, blur) {
  var input_currency = ""; //the currency symbol that shows beofore the amount

  var input_val = input.val();
  if (input_val === "") { return; }
  var original_len = input_val.length;
  var caret_pos = input.prop("selectionStart");
  if (input_val.indexOf(".") >= 0) {
    var decimal_pos = input_val.indexOf(".");
    var left_side = input_val.substring(0, decimal_pos);
    var right_side = input_val.substring(decimal_pos);
    left_side = formatNumber(left_side);
    right_side = formatNumber(right_side);
    if (blur === "blur") {
    /*  right_side += "00"; */
    }
    right_side = right_side.substring(0, 2);
    input_val = input_currency + left_side + "." + right_side;
  } else {
    input_val = formatNumber(input_val);
    input_val = input_currency + input_val;
    if (blur === "blur") {
      input_val += ".00";
    }
  }

  input.val(input_val);

HTML

<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
 <option value="$" selected>USD</option>
 <option value="₿">Bitcoin</option>
</select>

Ответы [ 2 ]

1 голос
/ 04 февраля 2020

Вам необходимо добавить оператор if внутри функции обратного вызова .on. Например, вы можете изменить свой код следующим образом

  $("input[data-type='currency']").on({
      keyup: function() {
        if($("#currency").val() != "₿"){
          formatCurrency($(this));
        }
      },
      focusout: function() {
        if($("#currency").val() != "₿"){
          formatCurrency($(this), "blur");
        }
      }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
 <option value="$" selected>USD</option>
 <option value="₿">Bitcoin</option>
</select>
0 голосов
/ 04 февраля 2020

Поставьте галочку в начале formatCurrency и верните при необходимости.

const formatCurrency = function(el, action) {
  // option one: checking the requirement could be here in one place
  if (!isShouldBeFormatted()) {
    return;
  }

  console.log(`do formatCurrency`);
}

const isShouldBeFormatted = () => {
  // select select element
  const elCurrency = document.querySelector(`#currency`);
  // value that we will check
  const valueToCheck = `₿`;

  return elCurrency.value !== valueToCheck;
}



$("input[data-type='currency']").on({
    keyup: function() {
      // option two: checking the requirement could be in every place you need it
      if (isShouldBeFormatted()) {
          formatCurrency($(this));
      }
    },
    focusout: function() {
      // option two: checking the requirement could be in every place you need it
      if (isShouldBeFormatted()) {
        formatCurrency($(this), "blur");
      }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input data-type="currency" name="amount">
<select class="" name="currency" id="currency" >
 <option value="$" selected>USD</option>
 <option value="₿">Bitcoin</option>
</select>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...