0

I have two radio buttons

  • USA
  • Argentina

Depending on what the user selects the phone field needs to clear and a different format needs to be in place

I have the the phone formats working I just don't know how to clear the tel field depending on what radio button they select

Here is my code

<div>
    <legend>Country</legend>

    <input id="usa" name="country" type="radio">
    <label for="usa">United States</label>

    <input id="argentina" name="country" type="radio">
    <label for="argentina">Argentina</label>
</div>

<div>
    <label>Phone Number</label>
    <input id="phone" name="phone" class="phone" type="tel" />
    <input id="phone_arg" name="phone_arg" class="phone_arg" type="tel" />
    <span>Example: 123-456-7890 or 12-34-5678-9000</span>
</div>

I currently have two phone fields so I can change the phone format using the mask plugin. But I would love to be able to use the one field

My JS is

$(".phone").mask("999-999-9999", { placeholder: " " });
$(".phone_arg").mask("99-99-9999-9999", { placeholder: " " });

Maybe if the user selects the argentina radio button it removes one class and adds another class. Please help

Here is a fiddle http://jsfiddle.net/barrycorrigan/L92aph6p/1/

  • Changing the class won't change the mask that was applied to the field. You need to call `.mask()` when the user selects the button. – Barmar Jun 10 '15 at 21:22

2 Answers2

0

Use

if($('#usa').prop('checked'))
   $("#phone").unmask().mask("999-999-9999", { placeholder: " " });
else
   $("#phone").unmask().mask("99-99-9999-9999", { placeholder: " " });

The mask is applied to object with that class when you execute it, if you change the class, the new objects with that class won't be masked.

oscargilfc
  • 339
  • 1
  • 12
  • http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Jun 10 '15 at 21:21
  • @Barmar I know not using curly braces is against standards like JSLint, but this is just an answer with the idea. Also in production usually compressed version are used and them omites curly braces whenever they can. – oscargilfc Jun 10 '15 at 21:25
  • Unfortunately I just tried this and it didnt work for me – Barry Corrigan Jun 10 '15 at 21:27
  • Well, it had a mistake, I've already fixit, I don't know if you notice it, the second line I was using the class instead of the Id – oscargilfc Jun 10 '15 at 21:28
0

Put click handlers on each button that sets the appropriate mask.

$("#usa").click(function() {
  $(".phone").mask("999-999-9999", {
    placeholder: " "
  });
    $("#example").text("123-456-7890");
});
$("#argentina").click(function() {
  $(".phone").mask("99-99-9999-9999", {
    placeholder: " "
  });
    $("#example").text("12-34-5678-9000");
});

$("#usa").click(); // Set default

Fiddle

Barmar
  • 741,623
  • 53
  • 500
  • 612