views:

62

answers:

4

i wanted to reload an element whenever there is a click event on any form element. can anyone help me with the jquery syntax? something like

function addClickHandlers() { $.publish('refreshDiv'); }

where the div's reloadTopic is set to refreshDiv

thanks

+1  A: 

Click events bubble up, so you can just set the event on the form element:

$('#myForm').click(function () {
    $.publish('refreshDiv'); 
});

You could also use .delegate() to only catch clicks from certain elements within the form:

$('#myForm').delegate("input, select, textarea", "click", function () {
    $.publish('refreshDiv'); 
});
Andy E
what if there are many forms that contain this specific div and i want it to reload whenever something is clicked in any one of the forms? this of course will mean that i have some file that is included in all these pages and this script goes in that file
abs
@Andy E: I don't see any `publish` method in jQuery, it that a plugin or what?
Sarfraz
@sAc: I assume it is, there's not really enough detail in the question to tell otherwise.
Andy E
@abs: replace `$('#myForm')` with a more suitable selector, e.g. `$('form');`, which will target all forms.
Andy E
i think i will just use a timer to publish it - doesnt seem to be working for elements inside the formthanks Andy E
abs
A: 

Add a handler to every element.

$('*').click(function () {
    $.publish('refreshDiv'); 
    return false; // to stop it from bubbling as we already handled it here.
});
mohang
using the universal selector `*` in is bad karma and the spirit of john resig might come and get you if you do so!
jAndy
It's also very inefficient to apply click handlers to *every* element in the DOM.
Andy E
A: 

Well, I can interpret your text in two ways:

1) execute $.publish on any element which is a children of a form element

$('form').children().click(function(){
   $.publish('refreshDiv');
});

2) execute $.publish on all form elements (like checkboxes, radio buttons, etc.)

$('form').find('input').click(function(){
   $.publish('refreshDiv');
});

Like Andy E. suggested, it has a better performance to delegate the click event, so less event handlers are bound.

3)

$('form').delegate('input', 'click', function(){
   $.publish('refreshDiv');
});
jAndy
You can use *delegate()* for a more efficient `2)`.
Andy E
A: 

I dont have idea about publish and i never seen this kind of code in jquery but if u want to reload whole page then u can do follow thing

<button id="PageRefresh">Refresh a Page in jQuery</button>

<script type="text/javascript">

    $('#PageRefresh').click(function() {

              location.reload();

    });

</script>

and if u want reload particular div then i think u should use ajax in jquery and reload the html in div.

$.post("/page", frm.serialize(), function(data) {
                    $("#ReminderProjectCount").html(data);
            });
Amit