Anthony
Anthony

Reputation: 4050

jQuery only works on first CodeIgniter view, not the second, why?

I have two CodeIgniter views in my application, both of which have a text field. My problem is, my jQuery code only works on the first CodeIgniter view when my application loads. When my app displays the second view, my jQuery code does not work.

$(document).ready(function() {
    $(".input-field").attr("value","I'm looking for...");
    var text = "I'm looking for...";
    $(".input-field").focus(function() {
        $(this).addClass("active");
        if($(this).attr("value") == text) $(this).attr("value", "");
    });
    $(".input-field").blur(function() {
        $(this).removeClass("active");
        if($(this).attr("value") == "") $(this).attr("value", text);
    });
});

Here are my script tags located in the head section of both CodeIgniter Views. Also, both views have the same class name input-field. Why does my jQuery not work on the second view?

<script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="scripts/script.js"></script>

Upvotes: 0

Views: 80

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use event delegation as it seems you are dealing with dynamic elements

The events are changed to focusin and focusout because by definition focus and blur does not bubble

$(document).ready(function () {
    $(".input-field").attr("value", "I'm looking for...");

    var text = "I'm looking for...";

    $(document).on('focusin', ".input-field", function () {
        $(this).addClass("active");
        if ($(this).attr("value") == text) $(this).attr("value", "");
    });
    $(document).on('focusout', ".input-field", function () {
        $(this).removeClass("active");
        if ($(this).attr("value") == "") $(this).attr("value", text);
    });
});

Upvotes: 1

Related Questions