kasperhj
kasperhj

Reputation: 10482

Sending data via ajax with multiple inputs having the same name

I am attempting to accomplish the following using jQuery.

I have 7 inputs, one for each day in the week. The html for this is generated server side. For each day I have a text input and a link for submitting the text for that day only via ajax to the server.

So far I have

<script type="text/javascript">
    $().ready(function(){
       $('.add_dish').click(function(){
          var mydata = $('form input[name=user_input]').val();
          window.alert(mydata)

          $.ajax({
            type: 'POST',
            url: '/add',
            data: mydata,
            cache: false,
            success: function(result) {
              if(result == "true"){
              }else{
              }
            }
          });
       });
    });
</script>

Server side generated code:

<h1>First day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

<h1>Second day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

<h1>Third day</h1>
<form>
<input type="text" name="user_input">
<a href="#" class="add">Add</a>
</form>

When I click Add the alert box is empty the value of the the input of the first day is always displayed. How can it be changed to reflect the selections of the element in the same <form> as the submitting link is in?

EDIT:
Highlighted the second part of the question.

Upvotes: 0

Views: 5887

Answers (2)

Yaje
Yaje

Reputation: 2831

you are using jQuery selector the wrong way.

it should be like :

 var mydata = $('form input[name=user_input]').attr('value','something');

and if you just want the value of the input box to put in mydata :

var mydata = $('form input[name=user_input]').val();

EDIT :

For iterating on all the inputs with same name you have to use .each():

    $('.add_dish').click(function(){

              $('form input[name=user_input]').each(function(){
              var mydata = $(this).val();
              window.alert(mydata);
              });


              $.ajax({
                type: 'POST',
                url: '/add',
                data: mydata,
                cache: false,
                success: function(result) {
                  if(result == "true"){
                  }else{
                  }
                }
              });
           });

References :

jQuery Input Selector

jQuery Class Selector

jQuery .each()

Upvotes: 1

akmed0zmey
akmed0zmey

Reputation: 573

You are trying to select element using class name but "user_input" is not a class name:) Use http://api.jquery.com/attribute-equals-selector/

Upvotes: 0

Related Questions