Saqib
Saqib

Reputation: 41

How to Distinguish between ID values of html Element using jquery

Actually I have two divs available on my page with buttons and I am passing the hidden field attached with that button to the jquery function But when I click on the second div it pass the value of the first div. Below is the html code

<div id="polls-42-ans"class="wp-polls-ans">
   <input type="button" name="vote" value="Vote" class="Buttons" id="vote-btn">
   <input type="hidden" value="42" id="poll-id"> 
</div>

<div id="polls-11-ans"class="wp-polls-ans">
   <input type="button" name="vote" value="Vote" class="Buttons" id="vote-btn">
   <input type="hidden" value="11" id="poll-id"> 
</div>

And I am using this jquery :

$(document).on('click','#vote-btn', function() {
  console.log( $("#poll-id").val()); 
});

NOTE: The Div ids are not same all the time

Upvotes: 0

Views: 72

Answers (3)

Soosai
Soosai

Reputation: 1

Here is the working javascript code:

$(document).on('click','#vote-btn', function() {
  console.log( $(this).siblings("#poll-id").val() ); 
});

Upvotes: 0

Oscar Acevedo
Oscar Acevedo

Reputation: 1212

You can select the DIVs with the class "wp-polls-ans" and then the buttons inside

 $(".wp-polls-ans #vote-btn").click(function(){
     var val =  $(this).parent().find( "#poll-id").val();
     alert(val);
   })

This is the fiddle

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

The id attribute should be unique in the same document, it will be better if you're using global classes instead :

<div id="polls-42-ans"class="wp-polls-ans">
  <input type="button" name="vote" value="Vote" class="Buttons vote-btn">
  <input type="hidden" value="42" class="poll-id"> 
</div>

<div id="polls-11-ans"class="wp-polls-ans">
  <input type="button" name="vote" value="Vote" class="Buttons vote-btn">
  <input type="hidden" value="11" class="poll-id"> 
</div>

Then use siblings to target the related field :

$(this).siblings(".poll-id").val();

Hope this helps.

$(document).on('click','.vote-btn', function() {
  console.log( $(this).siblings(".poll-id").val() ); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="polls-42-ans"class="wp-polls-ans">
  <input type="button" name="vote" value="Vote" class="Buttons vote-btn">
  <input type="hidden" value="42" class="poll-id"> 
</div>

<div id="polls-11-ans"class="wp-polls-ans">
  <input type="button" name="vote" value="Vote" class="Buttons vote-btn">
  <input type="hidden" value="11" class="poll-id"> 
</div>

Upvotes: 3

Related Questions