Reputation: 4187
<div class="heading">
<ul>
<li id="one">One</li>
<li id="two">Two</li>
</ul>
</div>
I using this jquery
<script>
$(document).ready(function(){
$('.heading ul li').click(function(){
var type1 = $('#one').val();
var type2 = $('#two').val();
if(type1) {
alert("1");
} else {
alert("2");
}
});
});
</script>
=> Error when click on One or Two, result is 2, too , how to fix it ?
Upvotes: 0
Views: 188
Reputation: 2794
What do you mean by if(type1)? I think you want to check if the value of the li is one then enter the if statement? Then you should:
$('.heading ul li').click(function(){
var type1 = $('#one').html();
var type2 = $('#two').html();
if($(this).val() == type1) {
alert("1");
} else {
alert("2");
}
});
Hope this help :)
(Edited from val to html)
Upvotes: 2
Reputation: 7218
As of jQuery 1.4, the .text() method returns the value of text and CDATA nodes as well as element nodes.
here is the link for jquery text() http://api.jquery.com/text/
Try
<script> $(document).ready(function(){
$('.heading ul li').click(function(){
var type1 = $('#one').text();
var type2 = $('#two').text();
if(type1 =="One") {
alert("1");
} else {
alert("2");
}
});
});
</script>
Upvotes: 0
Reputation: 39872
When you call .val()
it returns a string. Any string other than 0
will return as true
in your if statement. But you have more problems. val
gives you the value of an input. List items do not have a value property so this won't work. You probably want to retrieve the html instead.
$('li').click( function() {
var type1 = $('#one').html();
var type2 = $('#two').html();
if (type1 == 'One') { ... }
else { ... }
});
Upvotes: 0