Issue
I'm struggling with jQuery. Please help me...
When loading a page, the jQuery function is automatically executed, and at the same time, I'd like to implement this function in button click.
[Previously]
After loading the page, the jQuery function is automatically executed immediately.
And, there is no response when clicking the button.
html
<button type="button" class="btn btn-primary btn-sm" id="btn_add">LookUp</button>
jQuery
<script type="text/javascript">
$(function() {
..skip..
});
</script>
[Current situation]
After loading the page, the jQuery function is not automatically executed.
But It works well when clicking the button.
html
<button type="button" class="btn btn-primary btn-sm" id="btn_add" onclick="$(this).Lookup();">Lookup</button>
jQuery
<script type="text/javascript">
$.fn.Lookup = function() {
..skip..
};
</script>
[Goal]
Keep the jQuery function running automatically after loading the page.
Implement so that the jQuery function works even when clicking the LookUp button.
How should I fix this?
Solution
What you should do is create a function for Lookup
and then call this function during document ready
and button click. Refer the code snippet. I would be happy to explain further if you don't understand the code.
Edit: Also $.fn.<xyz>
should ideally be used for extending/creating generic functionality and not for specific/page specific ones.
$(function(){
//This will bind Lookup function to the button click event
$("#btn_add").on("click", Lookup);
//This will immediately call the Lookup function on document ready event (startup)
Lookup();
});
function Lookup() {
//do something
alert("Looking up");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-primary btn-sm" id="btn_add">LookUp</button>
Answered By - Sang Suantak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.