Bashir ahmad Bashir ahmad - 3 years ago 66
jQuery Question

php how to get the type of form fields using jquery?

I want get the name , value and type of the fields in the form. I am using the following code which helped me to get the name and value but type = "text" always even for checkboxs and radio button too. i want get the exact types of the fields whether it is checkbox, radio or text.
here is the code

<form action="">
<h1> Try Form</h1>
First name: <input type="text" name="FirstName" value="khan"><br>
Last name: <input type="text" name="LastName" value="wazir"><br>
<input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
<input type="checkbox" name="vehicle" value="Car" checked="checked"> I have a car<br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
<button>Serialize form values</button>
<div id="results"></div>

Here is the script

var x = $("form").serializeArray();
$.each(x, function(i, field){
$("#results").append( + ":" + field.value + " :" + $( "input" ).attr( "type" ) + " ");

Answer Source


$( "input" ).attr( "type" ) 


$( "input[name='" + + "']" ).attr( "type" )

you must pick specify input to get type correct

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download