简体   繁体   中英

JavaScript selecting radio button

To create a payment order form, how can I check the credit card number entered with the regex of the card and then select the correct radio button of that card number entered?

This is what I have so far:

function selectCardType(){
   var cardNumValue = document.getElementById("ccNum").value;
   var visa = /^4[0-9]{12}(?:[0-9]{3})?$/;
   var mc = /^5[1-5][0-9]{14}$/;
   var discover = /^(?:011|5[0-9]{2})[0-9]{12}$/;
   var amex = /^3[47][0-9]{13}$/;

   if(visa.test(cardNumValue))
   {
       document.getElementById("visa").checked = true;
   }
   else if(mc.test(cardNumValue))
   {
      document.getElementById("mc").checked = true;
   }
   else if(discover.test(cardNumValue))
   {
       document.getElementById("discover").checked = true;
   }
   else if(amex.test(cardNumValue))
   {
       document.getElementById("amex").checked = true;
   }
 }

Your code it is working, have a look:

http://codepen.io/anon/pen/mJPjap

<input type="number" id="ccNum" onchange="selectCardType()" />

Regex for Visa

^4[0-9]{12}(?:[0-9]{3})?$^5[1-5][0-9]{14}$

Regex for Amex

^3[47][0-9]{13}$

Regex for Discover

^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$

Regex for Master Card

^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})$

The radio buttons need to be grouped together. If not it allows selecting multiple radio buttons. The example is below http://codepen.io/anon/pen/jPqpdJ

<input type="radio" name="card" id="mc" /> mc

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