Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access custom attribute using serializeArray()

I am using serializeArray() function to fetch name and value attrubute of input tags resides in the form tag.

<form>
   <input type='text' data-val="Employee Name" value='john' name ='empName'/>
   <input type='text' data-val="Employee id" value='4333' name ='empId'/>
</form>

i am able to access name and value attributes , but how can i access custom attribute data-val using serializeArray()

like image 303
Hunt Avatar asked Dec 05 '25 17:12

Hunt


1 Answers

In this case you can't use serializeArray, you can try something like this with the help of map()

var arr=$('input').map(function(){ return $(this).data('val');}).get();
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <input type='text' data-val="Employee Name" value='john' name ='empName'/>
   <input type='text' data-val="Employee id" value='4333' name ='empId'/>
</form>

If you want the result as name value pair then use

var arr = $('input').map(function() {
  return {
    [$(this).attr('name')] : $(this).data('val')
  }
}).get();
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type='text' data-val="Employee Name" value='john' name='empName' />
  <input type='text' data-val="Employee id" value='4333' name='empId' />
</form>

Same output as serializeArray

var arr = $('input').map(function() {
  return {
    name: $(this).attr('name'),
    value: $(this).data('val')
  }
}).get();
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type='text' data-val="Employee Name" value='john' name='empName' />
  <input type='text' data-val="Employee id" value='4333' name='empId' />
</form>
like image 95
Pranav C Balan Avatar answered Dec 08 '25 07:12

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!