0

I have a input for entering money, also there is a switcher for dollar($) and euro(€) sign. I want to make it, after the user enters a number automatically add dollar and euro sign in order to switcher.

 $(document).ready(function(){
        $('#myonoffswitch').click(function(){
            if($(this).is(":checked")){
              $("#1").change(function() {
                  if (this.value.indexOf("$") === -1) {
                      this.value = this.value + ",00 $" ;
                  }
              });
            }
            else{
              $("#1").change(function() {
                  if (this.value.indexOf("€") === -1) {
                      this.value = this.value + ",00 €" ;
                  }
              });
            }
        });
    });

but the problem is, after checked the switcher two times, output looks like the example below: 1st check: "2,00$" 2nd check: "2,00 $ ,00 €"

how can i remove the dollar sign when 2nd check.

EDIT: my html is looks like this;

  <div class="onoffswitch">
            <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" >
            <label class="onoffswitch-label" for="myonoffswitch">
              <span class="onoffswitch-inner"></span>
              <span class="onoffswitch-switch"></span>
            </label>
  </div>

<div class="inputs">
            <input type="text" placeholder="Enter Here" name="1" id="1" autocomplete="off" class="inputName" />
</div>
umuur
  • 91
  • 1
  • 11

3 Answers3

1
this.value = this.value.split(',')[0] + ",00 $" ;

Will keep everything before the comma, and appendaing what you need.

phenxd
  • 689
  • 4
  • 17
0

Here is what I would think to do.

$('#myonoffswitch').click(function() {
  if ($(this).is(":checked")) {
      $("#1").val(addMoneySymbol($("#1").val(), "$"));
  } else {
      $("#1").val(addMoneySymbol($("#1").val(), "€"));
  }
});

$("#1").on('input', function() { 
    $(this).val(addMoneySymbol($(this).val() , $('#myonoffswitch').is(":checked") ? "$": "€"));
});

function addMoneySymbol(value, symbol) {
  var commaLoc = value.indexOf(",00");

  if (commaLoc > -1 && value.length > 0) {
    value = value.split(",00")[0];
  }

  if (value.indexOf(symbol) ===  -1 && value.length > 0) {
    return value + ",00 " + symbol;
  } else {
    return value;
  }
}
Jake Holland
  • 152
  • 1
  • 8
  • Thank you for answer, in line 10, function name should be "addMoneySymbol" but still it isn't working. – umuur Feb 16 '16 at 15:30
0

You should think about using toLocaleString() instead of your own function to format a number/currency properly.

You can format a money-string as following:

number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })

This will print out: 123.456,79 €

Read more about it: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Roman
  • 2,530
  • 2
  • 27
  • 50