Reputation: 55
I want to get different value from hidden input id inside same class. Here is some example code of html and jQuery that I'm trying to create.
<li>
<div class="test"><img src="course.png"/><p class="text">Computer</p>
<span class="list">
<p>Course 1 <input type="hidden" id="id1" value="1"></p>
<p>Course 2 <input type="hidden" id="id2" value="2"></p>
<p>Course 3 <input type="hidden" id="id3" value="3"></p>
</span>
</div>
</li>
Code that I'm trying to create
$(".test p").click(function(){
var id= $(this).find('#id1').val();
var id= $(this).find('#id2').val();
var id= $(this).find('#id3').val();
alert(id); // will return value 1 or 2 or 3 if click on any course
});
Upvotes: 0
Views: 548
Reputation: 2740
its better to have class for your p and input tags and instead of id use them
<li>
<div class="test"><img src="course.png"/><p class="text">Computer</p>
<span class="list">
<p class="myCourse">Course 1 <input type="hidden" class="myCourseVal" value="1"></p>
<p class="myCourse">Course 2 <input type="hidden" class="myCourseVal" value="2"></p>
<p class="myCourse">Course 3 <input type="hidden" class="myCourseVal" value="3"></p>
</span>
</div>
</li>
$(".test .myCourse").click(function(){
var myValue = $(this).find('.myCourseVal').val());
alert(myValue);
});
It's better to use class instead of input tag
, so if in the future you add other input, you get your value correctly base on what you want.
If you don't use class for you desire p
s if you click on Computer
your code will start to run.
If you want to have your course values that there is in you course name:
$(".test .text").click(function(){
var x = [];
foreach('.myCourse',function(){
x.push($(this).find('.myCourseVal').val();
})
alert(x);
});
Upvotes: 1
Reputation: 40096
Do not use "id" as a var name.
This should work:
$(".test p").click(function(){
var myID = $(this).find('input').val();
alert(myID); // will return value 1 or 2 or 3 if click on any course
});
Upvotes: 2