Saint Robson
Saint Robson

Reputation: 5525

How To Do jQuery Selection For This DIV

I have this div tags :

<div id="target-share">
<a href="#" title="" id="to-chosen" class="default"><span class="to-admin">Admin</span></a>
<ul id="select-shareto">
<li data-val="0-1">
<a href="#" title="" class="selected"><span class="to-Finance">Finance</span></a>
</li>
<li data-val="1-1">
<a href="#" title=""><span class="to-admin-private">Admin Private</span></a>
</li>
<li data-val="1-0">
<a href="#" title=""><span class="to-ceo">CEO</span></a>
</li>
<li data-val="0-0">
<a href="#" title=""><span class="to-ceo-private">CEO Private</span></a>
</li>                                    
</ul>
<input id="shareto" type="text" value="0-1" name="shareto">
</div><!-- #target-share -->

and this JavaScript :

<script type="text/javascript">
$(document).ready(function($) {
        $('ul li').click(function() {
            $('input#shareto').val($(this).data('val'));
        });
    });
</script>

that JavaScript actually works when I'm using it with that div alone. but when I put it on my full code, that JavaScript doesn't work. I think that because there are more than one UL and LI tags on my code.

Now, the question is... how to apply that Javascript so that it can works ONLY for that div, even though there are other UL and LI tags.

Upvotes: 0

Views: 80

Answers (3)

Sammaye
Sammaye

Reputation: 43884

JavaScript (not just Jquery) is all about scoping:

$('ul li').click(function() {

Causes that click to bind to every li in a ul so what you wanna do is scope the click down to a specific area of your page or set of elements across the page.

To scope it down to a specific element the best idea is to use a id like so:

$('#target-share ul li')

But to scope it down to a number of elements it is better to use a class like:

$('.target-share ul li')

Edit:

Also on() could be a good replacement here for click but it depends on where the HTML is being sourced and how it is being used, but thought I would make you aware of that function in case you didn't already know about it.

Upvotes: 0

Michael Robinson
Michael Robinson

Reputation: 29498

Select those ul li that have your data-val attribute:

$(function($) {
    $('ul li[data-val]').click(function() {
        $('input#shareto').val($(this).data('val'));
    });
});

Upvotes: -1

Jon Taylor
Jon Taylor

Reputation: 7905

Just use this instead targeting the div first then its contents

$('#target-share ul li')

Upvotes: 4

Related Questions