Shiro Shiro - 28 days ago 11
Ajax Question

How can I get a radio attribute name by unqie ID with jQuery using regex?

I have the following input elements:

<input name="option[100]" value="first" type="radio" checked="checked"/>
<input name="option[100]" value="second" type="radio" />
<input name="option[100]" value="third" type="radio"/>


I able to use

myOption = $('input[name^=\'option\']:checked').val();


to get the value of the radio button.

However, I want to know the name id which 100, how am I able to get it?

I would want to submit an ajax as an array as it like post a form

$.ajax({
url: 'product/product/add',
type: 'post',
data: { product_id: product_id, option: myOption },
dataType: 'text',


The PHP get the POST need to like
$myOption[100]=first;

Answer

You may get the element name using attr('name') and use a very simple regex - /\d+/:

var myOption_name = $('input[name^=\'option\']:checked').attr('name');
console.log(myOption_name.match(/\d+/)[0]);
// or
// console.log(myOption_name.replace(/^option\[(\d+)]$/, "$1"));
// or
// console.log(myOption_name.match(/^option\[(\d+)]$/)[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="option[100]" value="first" type="radio" checked="checked"/>
<input name="option[100]" value="second" type="radio" />
<input name="option[100]" value="third" type="radio"/>

If you want to make sure the name follows your specific pattern you may use

/^option\[(\d+)]$/

And either use match or replace (see commented code in the snippet above).

Details:

  • ^ - start of string
  • option\[ - a option[ substring
  • (\d+) - Group 1 capturing 1 or more digits
  • ] - a closing ]
  • $ - end of string.