MarkP
MarkP

Reputation: 2566

Value returning undefined if used in function

I have a slight problem with code here. I'm fairly new to it so if its simple I apologise. But would love an explanation.

So here is the html I have:

<div class="one" data-selection="1"></div>
<p class="selections"></p>
<p class="cost">£ <span class="price">0</span></p>

and here is the JavaScript:

<script>
// Empty array to capture selections
    var a = [];
    var originalValue = "You have Selected section(s): ";  
    $(".one").click(function () {
        if ($(this).attr('class') == "selected one") {  
            //alert
            alert("Are you sure you wish to de-select?");       
            //remove from the total
            $(".price").html(parseInt($(".price").html(),10) - 30)  
            $(this).removeClass("selected ");   
            // need to get remove from array
            var removeItem = $(this).attr("data-selection");  
            a = jQuery.grep(a, function(value) {
                return value != removeItem;
            });      
            $('.selections').text(originalValue + a);   
        }
        else {
            var selection = $(this).attr("data-selection");
            alert(selection);
            var originalSrc = $(this).attr('class');
            $(this).attr('class', 'selected ' + originalSrc);     
            a.push(1);
            a.sort();           
            $('.selections').text(originalValue + a);   
            $('.price').text(function(i, txt) {
                return +txt + 30;
            });
        }
    });
</script>

This works fine. However when I add the contents of the if statement into a function called:

undoSelection()

and change the code to:

$(".one").click(function () {
    if ($(this).attr('class') == "selected one") {
        undoSelection();
    }
    else {

Nothing after the alert asking if they are sure to deselect works. If I add an alert in there and get

  $(this).attr("data-selection"); 

it alerts undefined.

I would like it in a function as I dont want lines upon lines of duplicated code :(

Can someone please shed some light on this?

Upvotes: 1

Views: 575

Answers (1)

OnResolve
OnResolve

Reputation: 4032

That's because you have $(this) being called still I bet. The keyword this means $(".one") initially, however the context of this then changes when you call the function. If you want it to work in another function you need to set a variable to the value of $(".one") and use that instead of $(this) inside the function.

It's hard to get but the this keyword in javascript is always refers to the object that a function is a method of. So in the first case this refers to $(".one") whereas if you move the the other logic inside another function the definition changes (to the global object, usually the window).

I've created a jsFiddle for you that shows a working example of what you're looking for: http://jsfiddle.net/CKCjz/1/

Upvotes: 1

Related Questions