ajax - How can I get a radio attribute name by unqie ID with jQuery using regex? -
i have 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 use
myoption = $('input[name^=\'option\']:checked').val();
to value of radio button.
however, want know name id 100, how able it?
i want submit ajax array post form
$.ajax({ url: 'product/product/add', type: 'post', data: { product_id: product_id, option: myoption }, datatype: 'text',
the php post need $myoption[100]=first;
you may element name using attr('name')
, use 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 want make sure name follows specific pattern may use
/^option\[(\d+)]$/
and either use match
or replace
(see commented code in snippet above).
details:
^
- start of stringoption\[
-option[
substring(\d+)
- group 1 capturing 1 or more digits]
- closing]
$
- end of string.
Comments
Post a Comment