Nacho Sarmiento
Nacho Sarmiento

Reputation: 473

Send different tittle attribute of the same input ID

I have a HTML form with 3 inputs. If I change some value in theese input I use it to check something in my DB.

So every time if I change the value of my input, I need to send different "title" attribute to my Ajax function.

The problem is when I change any value, my Ajax function get the title of the fist input ("BEER").

This is my HTML code:

<input id='quantity' type='text' title='BEER' value='0' onchange='search();'>
<input id='quantity' type='text' title='VODKA' value='0' onchange='search();'>
<input id='quantity' type='text' title='GIN' value='0' onchange='search();'>

This is my function:

function search(){

$.ajax({
    url: 'search.php',
    type: 'POST',
    data: 'code='+$("#quantity").attr("title"),
    success: function(x){

     alert(x);

     },
    error: function(jqXHR,estado,error){

        alert("ERROR");
    }
   });
}

May you help me, please?

I was trying to do it with an array but it didn't work.

Thanks you!!

Upvotes: 0

Views: 50

Answers (1)

D.B.
D.B.

Reputation: 1782

Perhaps you meant to send the object in use as a parameter to your function. You can send this.

Like:

<input id='quantity' type='text' title='BEER' value='0' onchange='search(this);'>

NB: I modified your code a bit to help with debug messages.

function search(obj){

  var code = $(obj).attr("title");
  console.log(code);

  $.ajax({
      url: 'search.php',
      type: 'POST',
      data: 'code='+code,
      success: function(x){

       alert(x);

      },
      error: function(jqXHR,estado,error){

          alert("ERROR");

      }
   });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type='text' title='BEER' value='0' onchange='search(this);'>
<input type='text' title='VODKA' value='0' onchange='search(this);'>
<input type='text' title='GIN' value='0' onchange='search(this);'>

** BTW: It is recommended to not have the same ID for more than one element on a page. However, by calling the event the way you did, the IDs are not even needed. You can delete them or change accordingly.

Upvotes: 1

Related Questions