We help IT Professionals succeed at work.

jQuery Getting an array of form field names and their values

Cybervanes
Cybervanes asked
on
is it possible to target a form and pull an array of input field names and their corresponding values?

below is as far as I've been able to get.
var values = [];
    $("#"+test+" input").val().each(function(index, value) { 
  values[$(this).attr('name')] =  $(this).val();
  alert(index + ': ' + value); 
});

Open in new window


then I want to be able to use jQuery's ajax function to sent to a php script... haven't gotten that far yet.

one of my concerns is, will the strings being pulled from the form fields need to be encoded in any way? remove special charters and so-forth?

i'm just learning jQuery and spreading my wings with JS so i'd rather not use a plug-in if can can help it.

anybody have any ideas?
Comment
Watch Question

Kiran SonawaneProject Lead
Top Expert 2011

Commented:
You can use jquery "serialize" method to target form elements.
Look at this http://api.jquery.com/serialize/
Commented:
Try this.

var values = [];
$("#"+test+" input").each(function(index, value) { 
    values[$(this).attr('name')] =  $(this).val();
    alert(index + ': ' + value); 
});

Open in new window


Anyway, serialization using serialize method would be a better approach to your problem.
we can do like this.

$("input:text,select,input[type=checkbox],input[type=radio]", ".information").each(function(el) {
				if($(this).attr("type") == "checkbox" || $(this).attr("type") == "radio")
				{
					if($(this).is(':checked'))
					{	
					  values[$(this).attr("name")] = $(this).val();
					}
				}
				else
				{
					values[$(this).attr("name")] = $(this).val();
				}
		});

	 }
	
	$.ajax({
		 type: 'POST',
		 url:  url,
		 data: values,
		 success: function(msg){ 		 
			
		}  
	});

Open in new window