Each submit button calls the same function - javascript

I'm calling function for selecting component ID after page refresh:
$(document).ready(
function() {
document.getElementById('form:#{myBDE.componentId}').focus();
document.getElementById('form:#{myBDE.componentId}').select();
}
)
My submit button example:
<h:form id="form">
<h:commandButton id="btnSubmit" action="#{myBDE.save}" type="submit" >
<f:ajax execute="#form" render="#form"/>
</h:commandButton>
...
</form>
How can I create the same function to be called each time I click any submit button (I'm using ajax, so I'm working without page reloading, document.ready is not enough for me). Is it possible?
update (partially functional solution):
var myFunc = function() {
document.getElementById('form:#{myBDE.componentId}').focus();
document.getElementById('form:#{myBDE.componentId}').select();
};
$(document).ready(function() {
myFunc();
$('input[type=submit]').click(myFunc);
});
I can call the function adding onclick="return myFunc();" to h:commandButton, problem is, that <f:ajax> render the form after calling the function, so the select and focus is cleared :(

Give the function a name (currently, its an anonymous function), and then call the function as and when you need.
$(document).ready(
onPageLoad(); // call it when page loads
$('form').submit(onPageLoad); // also call whenever a form is submitted
)
function onPageLoad() {
document.getElementById('form:#{myBDE.componentId}').focus();
document.getElementById('form:#{myBDE.componentId}').select();
return true;
}

This should work
$('input[type="submit"]').click(function(){
document.getElementById('form:#{myBDE.componentId}').focus();
document.getElementById('form:#{myBDE.componentId}').select();
});
In fact you can bind a function to any events. In this case it is the click event for the input tag with the attribute type=submit

You should delegate the handler to a higher-level dom element:
$(document).ready(function() {
$('h:body').on('click', 'input[type=submit]', function() {
document.getElementById('form:#{myBDE.componentId}').focus();
document.getElementById('form:#{myBDE.componentId}').select();
});
});
See jQuery.on().
When a selector is provided, the event handler is referred to as
delegated. The handler is not called when the event occurs directly on
the bound element, but only for descendants (inner elements) that
match the selector. jQuery bubbles the event from the event target up
to the element where the handler is attached (i.e., innermost to
outermost element) and runs the handler for any elements along that
path matching the selector.
And then later:
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
So the event will be handled for all elements of that type, even if they are added later via ajax. Note that I used h:body here as the element to delegate to but you can use any element that exists at document.ready time and is guaranteed to be an ancestor of all submit inputs.

If you have different ID or Name on them it's just to do somthing like
$(document).ready(function(){
$('#btn1, #btn2, #btn3').on('click', function(evt){
evt.preventDefault();
//your code
$(this).submit(); // or not submit, your choice
});
});

Try this thing
$(document).ready( function (){
$('input[type=submit]').click( function (){
// Whatever you want on submit button click option.
}
});
This will grab every submit button on the page and will bind click event to it, and this code will be called on any submit button click.

Related

Jquery repeater, why .keyup and .change does not triggered on the second items and beyond?

The .keyup and .change only triggered in the first input but not after I added a new item. Is there a way the .keyup and .change triggered when adding new field?
http://jsfiddle.net/q8pcoaxf/
$('.field').on('change keyup',function() {
alert('alert');
})
A jQuery selector only selects those elements present in the DOM at the time of its execution. In older versions of jQuery, there was once a function .live() that would also bind to any elements of the given selector added at a later point in time, but it has since been removed.
What you can do is bind to the document via .on() with an additional selector as the second argument. But keep in mind that this will fire on every trigger of the bound events and check against the selector, so for performance reasons, if you can narrow down the elements that will be added to a specific parent (like a form probably in your case), you should definitely do that instead of binding to the document.
On a sidenote: Binding to change and keyup will result in the callback function to be executed twice in this example case, because the alert window popping up will result in the input losing focus and therefore the change event being triggered as well.
// will bind on the document and be executed for all change and keyup events on any element that has the class "field"
$(document).on('change keyup', '.field', function() {
alert('alert');
});
// let's say you had a form with the id #dynamic_inputs where the inputs are added to,
// this would be the preferable way to handle it:
//$('#dynamic_inputs').on('change keyup', '.field', function() {
// alert('alert');
//});
function addNewInput() {
var newInput = document.createElement('input');
newInput.classList.add('field');
document.body.appendChild(newInput);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addNewInput()">add new input</button><br>
<input class="field" />

Click function not working in .each() function

I want to use click() as eventhandler and that event handler is not working you can see code below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live-on' ).removeClass('ajax-live-on');
});
I have used all the code to initialize the jquery no problem , all right. But this piece of code not working
Here is the jsBin link
http://jsbin.com/doxeravizo/1/edit?html,css,js,output
The $('.ajax-close') collection doesn't contain the elements taking that class after the binding.
Change
$('.ajax-close').click(function( event ){
to
$(document.body).on('click', '.ajax-close', function( event ){
You should also move that binding outside of the loop, there's no reason to do it at every iteration.
Note also that in order to have your span clickable, it must have some content.
Demonstration (I added the jQuery library to make the fiddle work)
I'm guessing that because you're using ajax, your .ajax-close is not created when the event listener is being created.
You're going to want to delegate your click function:
$(document).on('click', '.ajax-close', function(event) {
event.preventDefault();
alert('hi');
$('.ajax-live-on').removeClass('ajax-live-on');
});
This article will help, but just for reference, this bit in particular:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
One option is to listen on the click event using a delegate, like so:
$(document).on('click', '.ajax-close', function( event ){
//your code
});
Another option might be to move your click listener inside the original click listener, which creates the "Close" button, while the reason the issue arises is that the click event on "ajax-close" is bound too soon (before the <span> is appended to the DOM even):
ajaxcontent.click(function(event) {
event.preventDefault();
$( '.ajax-live' ).addClass('ajax-live-on');
$( this ).after('<span class="ajax-close animated bounceInRight">Close</span>');
$('.ajaxshow').append().load(ajaxUrl);
$('.ajaxshow').addClass('animated bounceInUp');
// Move this section here, which was previously located below
$('.ajax-close').click(function( event ){
event.preventDefault();
alert('hi');
$( '.ajax-live' ).removeClass('ajax-live-on');
});
});
Make sure to include some content in your "ajax-close" span to be able to click it like the word "Close".
Add JQuery library to your HTML head :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
In your given link you are adding element dynamically, so need to use event delegate for dynamically created elements event binding.
$(document).on('click', '.ajax-close', function( event ){
//your code
});

Trigger jQuery handler if search field contains "pre-populated" value

I have a search field that currently has an .on('input') event handler attached to it. However, in some instances the search field may be pre-populated if a value is passed through the URL (http://127.0.0.1/search/query-is-here). The issue here however is that the event handler will not be fired until the user edits the search field's value, meaning no search is automatically made.
I have tried initiating a .trigger by specifying focus, click, change, ... but none seem to work (and yes, I do change the event handler to .on('input focus') for example). What's the crack?
--
JS File (referenced in the footer BEFORE the trigger)
$('#search').on('input focus', function(e) {
e.preventDefault();
// various if statements and variable assignments
}
Trigger
// codeigniter -> http://ip.com/{segment 1}/{segment 2} -> this does get executed
<?php if($this->uri->segment(1) == "search" && $this->uri->segment(2)):?>
<script>
$('#search').focus();
$('#search').trigger("focus");
</script>
<?php endif; ?>
My understanding of $('#search').trigger("focus"); is that it should fire the event handler attached to #search, and execute the JS within that function.
You're subscribing to the event 'input focus' and triggering the event 'focus'. I think you'll want to subscribe to both events.
$('#search').on('focus', myHandler);
$('#search').on('focus input', myHandler);
Why are placing e.preventDefault() on focus? The event.preventDefault() method stops the default action of an element from happening.
Remove that e.preventDefault() from the code and try it again.
$('#search').on('input focus', function(e) {
//remvoe this line>> e.preventDefault();
// various if statements and variable assignments
}
Below is the jsfiddle link:
https://jsfiddle.net/shrawanlakhe/c8v5v788/1/
I have also place e.preventDefault() on the handler and it is preventing click event handler from firing .So first try it and the click event handler will not fire and then remove the e.preventDefault() and then try it again in the fiddle and this time event handler will fire

Detecting .click() from ajax loaded element

I have a button that is loaded into my page using ajax:
<button id="submit">Submit</button>
I am using this code on the page that the button is being loaded into:
<script type="text/javascript">
$(function() {
$("button#submit").click(function(){
alert('Submit Clicked');
});
});
</script>
Why is it not detecting the click from the ajax content?
When you attach the click event you attach it to the existent elements in the DOM, when the ajax content comes, new DOM elements are created and the event wasn't attached to them.
One option is to use events delegation a way (but not recommended) to do it is using the document to read the event
$(document).on('click', 'button#submit', function(){
//do something
});
A better way is put the delegation to the element which gets the new content, lets assume is a form with an id formElement, It would be something like
$("#formElement").on('click', 'button#submit', function(){
//do something
});
Using that event delegation the new content from ajax will fire the click event.
PD if you have an ID in a element just use the id, like #submit, It makes a faster selector than tag#id because It used getElementById internaly
In your code you have attached the event handler to buttons before the button is created. You need to attach the handler afterwards. Add the handler in the ajax success() function instead, after you have created the button, and everything will work ok.
Its because its dynamically added button.For that you have to use on() method try following
$(document).on('click', 'button#submit', function(){
alert("hi");
});

Use of Binding after Unbinding

I found a code as shown below.
Html code:
<div id="myButton">Click Here</div>
JQuery Code:
$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
What is the need of unbind("click") before binding the element?
It is also working if unbind is not used. like shown below
$("#myButton").bind("click",function(){
alert("Working")
});
Which one is best? what is the difference?
This only makes sure, that there is no other click event listener attached. So your handler will be the only handler acting upon clicking the #myButton
Edit: as #T.J. Crowder noted in the comments, unbind() will not affect handlers attached in different way than by calling bind().
It is also worth noting, that:
as of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements
(excerpt from the jQuery.unbind() doc). In fact, unbind() is implemented internally by the off() method).
Consider:
$("#myButton").bind('click', function () {
console.log('click 1');
});
$("#myButton").unbind('click').bind('click', function () {
console.log('click 2');
});
// When clicked, prints "click 2"
Versus:
$("#myButton").bind('click', function () {
console.log('click 1');
});
// note: no unbind here
$("#myButton").bind('click', function () {
console.log('click 2');
});
// When clicked, prints "clicked 1" followed by "clicked 2"
By unbinding "click" event on an element, you are actually removing all the onclick events associated with that element. i.e. if your html form's input field has an onclick event and it calls a function, it will be unbound. After an unbind, you are binding another click event which will call your function onclick of that element.
$("#myButton").unbind("click").bind("click",function(){
alert("Working")
});
jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements. please see a demo http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-bind-unbind-example.html
Without url of this html code , i'm not sure that #myButtonelement whether has other click handler attached ,but what is certain is unbind method remove all the handler on this element , i think the author only want to trigger one click event.
Also, you can see if there is other event handler on debug inspector of browser.
Hope this will help you.

Categories