Dima Deplov
Dima Deplov

Reputation: 3718

html attribute for additional information and forward usage

The question is must be quite trivial, but i don't know how to formulate it right. Ok, I'm using PHP and jQuery, also i use ajax for user-to-server requests. What I'm looking for is a simple way to get info about some ohhhh I'll better show an example of what i want.

I form the page with some info from DB. For example I have a table with objects that have colors, and when page is load we have this:

 <body>
 <span class="object_span">red</span><button>random color</button> 
 <span class="object_span">white</span><button>random color</button>
 </body>

I simplified this, but you got what's the point, think.

next step, I want to change one of this using ajax:

 $(document).ready(function(){
 $('#object_span').change(function(){

  $.post(
'ajax_handler.php',  
    {object_id: 'how to simply get this parameter???' },  //         <---- problem is here
    function(responseText){  
    console.log(responseText);  
    },  
    "html"  
  );  

  });
 });

may be there is some parameter that i can add to span like: 'my_object_id:1232' ?? or something in this way that i can simply use in the js or jQuery like so:

     $(document).ready(function(){
     $('#object_span').change(function(){
     var current_object_id = $('#object_span').attr('my_object_id');
     ...
     });
 });

Thanks, for your help.

Upvotes: 2

Views: 119

Answers (3)

Adil
Adil

Reputation: 148180

You can assign attributs to span and access them as you access defined attributs.

Live Demo

Html

<span class="object_span" my_object_id="I am added">red</span>

Javascript

 $('#object_span').change(function(){
       var current_object_id = $(this).attr('my_object_id');
 });

You can use data-attributes name as well.

Live Demo

Html

<span class="object_span" data-my_object_id="I am added">red</span>

Javascript

   $('#object_span').change(function(){
        var current_object_id = $(this).data('my_object_id');           
   });

Upvotes: 2

Atif
Atif

Reputation: 10880

I recommend you take a look at HTML5 data attirbutes and jQuery data() methods

Upvotes: 1

Mathew Thompson
Mathew Thompson

Reputation: 56459

Use a data attribute:

<body>
     <span class="object_span" data-my_object_id="1234">red</span><button>random color</button> 
     <span class="object_span" data-my_object_id="1235">white</span><button>random color</button>
</body>

Then you can do:

$(document).ready(function(){
    $('.object_span').change(function(){
     var current_object_id = $(this).data('my_object_id');
     ...
});

Upvotes: 3

Related Questions