简体   繁体   中英

clear a text field depending on which radio button

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/

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM