dhaval
dhaval

Reputation: 2388

how to handle change event in jquery?

What could be wrong with below function? Theres a

tag in error and it gets filled when error occurs, the error is thus shown for a sec and then disappers.

$('#error').hide(); 
$('#error').find('p').change(function(){
    if($(this).contents().length > 0){
        $(this).show();
    }
});

EDIT: adding the error piece too

<div id="error" class="error">
<span style="float:right" >CLICK to remove.</span>
{% block error %}
    {% ifnotequal '' where %}
    <p>where-{{where}}</p>
    {% endifnotequal %}
    {% if error %}
    <p> error-{{error}}</p>
    {% endif %}
{% endblock %}
</div>

Upvotes: 0

Views: 411

Answers (4)

SolutionYogi
SolutionYogi

Reputation: 32233

AFAIK, the change event works only for the input elements, it wouldn't fire for your paragraph element.

EDIT: If your problem is that the paragraphs become invisible again, then there must be some other code which does that. Check for setInternal or setTimeout method calls in your code.

Upvotes: 2

Elzo Valugi
Elzo Valugi

Reputation: 27866

There is no JavaScript error in your code. The issue is that you are hidding the error div. Find is a traversing method that looks to all children of a div. And then you choose to show a div in with a hidden parent. It will not show anything.

Upvotes: 0

Andrew Noyes
Andrew Noyes

Reputation: 5298

It looks like you're setting the <p> to be displayed when it is changed. Why would the <p> be changing? By the way, the #error element is being hidden, so setting the <p> to display isn't going to do anything if its parent is hidden. I think you might need an .end() in there to revert back to the #error element.

I think this is more in line with what you want:

$('#error').hide(); 
$('#error').find('p').change(function(){
        if($(this).contents().length > 0){
                $(this).parent().show();    // .parent() should return #error
        }
});

Upvotes: 1

chaos
chaos

Reputation: 124297

If I understand your question properly, what's wrong with your code is that it's expecting the onchange event on a p to get called. This isn't a thing that normally happens. You should probably read up on onchange and compare/contrast it with whatever behavior you're expecting (which I don't really understand).

Upvotes: 1

Related Questions