0

i'm fetching all the values of same field name using jquery

$('input[name^="StudentName"]').each(function() {
StudentName+= $(this).val();
alert(StudentName);
});

while alert i'm getting all values as one string such as "Student1Student2Student3" and so on. how can I separate each name of student ?

$.ajax({url:"<?=base_url(); ?>StudentAttendance/SaveAttendance",
data: "StudentName="+StudentName,
success:function(result){
$("#result").html(result);
}});

and when i'm sending it through jquery i'm getting only the last field name value as Student4. kindly help me out.

Note: text fields are dynamic

10
  • Array my friend Commented Apr 16, 2018 at 13:17
  • well look at what you are doing! You are just adding them together with no separator. Commented Apr 16, 2018 at 13:17
  • 1
    First of all in you ajax you want to pass all your StudentName values concatenated? As a literal? You could split them with a comma for example but generally you should use an array for your data as others say. Commented Apr 16, 2018 at 13:19
  • You may also send a complete form via AJAX. Commented Apr 16, 2018 at 13:19
  • "i'm getting only the last field name value" - Where are you "getting" that? If you're building a longer value in StudentName then I would expect that entire value to be sent to the server as a string just like any other value. While it's clear that perhaps something other than string concatenation would likely be ideal here, what's not clear is what the actual problem is. Commented Apr 16, 2018 at 13:20

3 Answers 3

0

you can split these values with \n.

$(this).val().split("\n");
Sign up to request clarification or add additional context in comments.

Comments

0

2 solutions:

  • You can give an object in data

    data: { field1: val1, field2: val2 },

  • You can concat your fields as a data string

    data: "field1=" + val1 + "&field2=" + val2,

Comments

0

Make use of serializeArray() method of jquery will do it for you

 //creates a JavaScript array of objects, ready to be encoded as a JSON string
 var fields = $( 'input[name^="StudentName"]' ).serializeArray();

  $( "#results" ).empty();
  jQuery.each( fields, function( i, field ) {
    $( "#results" ).append( field.value + " " );
  });

   //add div at your html and check 
    <div id="results"> </div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.