Javascript/Trinidad: autoSubmit on checkbox prevents keyup event from being heard - javascript

When my user presses 'Enter' after clicking a checkbox, my form should act as though the 'Next' button was pressed. But, I am using PPR (partial page rendering) so that when it is clicked, my checkbox triggers a 'Next' button to get repainted. This is done by setting autoSubmit="true" on the checkbox and a partialTrigger on the button.
The problem is that with autoSubmit=”true” on my component, the javascript/jquery does not ‘hear’ the keyup event. I assume that this is because when the button that has the partialTrigger on it is repainted, my checkbox has lost focus. I have tried resetting the focus on the checkbox in an onclick method but it seems to fire too early. I set a timeout on it too, but that didn't work either. I have also tried programatically making a javascript call during the checkbox's valueChangeListener method, but this must be firing too early as well. Does anyone know why this is happening and what I can do?
Here is the code
$(document).ready(function(){
$("input[id='subview:agree']").keyup(function (event) {
if (event.keyCode == 13) {
processEnterKey();
}
});
});
function processEnterKey() {
$("button[id='subview:btnSubmit']").click();
}
Checkbox:
<tr:selectBooleanCheckbox binding="#{bean.termsOfUseChkBox}"
id="agree"
autoSubmit="true"
simple="true"
valueChangeListener="#{bean.agreementChangeListener}"/> /
Button:
<tr:commandButton id="btnSubmit"
disabled="#{!bean.agreementAccepted}"
partialTriggers="agree" text="Next"
action="#{bean.termsOfUse_action}"
partialSubmit="false"
onclick="handleLoadingPleaseWait()"
blocking="true"/>
Here is the onclick method I used to try to set focus back to the checkbox so it could 'hear' the keyup:
$("input[id='subview:agree']").click(function (event) {
if(document.getElementById('subview:agree').checked) {
setTimeout(function(){document.getElementById('subview:agree').focus();},1000)
}
});
Here is the server-side code I put in the changeListener:
FacesContext fctx = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks = null;
//compose JavaScript to be executed on the client
StringBuilder script = new StringBuilder();
script.append("document.getElementById(\"subview:agree\").focus();");
erks = Service.getRenderKitService(
fctx, ExtendedRenderKitService.class);
erks.addScript(fctx, script.toString());

If you want to submit the form from each imput by pressing enter you can simply use the defaultCommand attribute on your tr:form.
Documentation on <tr:form defaultCommand="..."/>
The id attribute of the command button whose action would be invoked by default for form submit on hitting enter on any of the input fields of the form.
So, setting it to btnSubmit should do the trick.
As this did not help for your scenario, you could try adding a onkeypress attribute to your checkbox:
<tr:selectBooleanCheckbox binding="#{bean.termsOfUseChkBox}"
id="agree"
autoSubmit="true"
simple="true"
valueChangeListener="#{bean.agreementChangeListener}"
onkeypress="if (event.keyCode === 13){ this.click(); }"/>
For me this triggered submitting my form.

Related

javascript: a button element is not working on click()

I AM NOT TRYING TO SUBMIT A FORM USING JAVASCRIPT!!" The above remark is misleading, inappropriate and confused
I have a html form that contains several elements (all with unique #id) which when clicked using the mouse correctly submits the form with the action=value pair.
<html><body><form id="frm-table" name="frm-table" method=get>
<!-- the form has an action url to call php script that interprets passed values and serves new dynamic page -->
<!-- #20140820 - #id and #name added to form -->
<button id="cancel-btn" type="submit" name="action" value="cancel"><img src="http://foo.localhost/img/cancel16.png" alt="Cancel" title="Cancel" class="btn" name="btn_c" /></button>
<!-- several other inputs eg type=text and buttons type=submit -->
</form></body>
I have a js script that captures a document ESC keydown and as example: displays an alert to confirm capture.
document.onkeydown = function(evt) {
evt = evt || window.event;
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if (evt.keyCode == 27) {
if (document.getElementById('cancel-btn') != null) {
// alert('Esc key pressed.'); //just to test capturing ESC key - OK
// testing suggestion 201408211700
document.getElementById('frm-table').action = 'http://foo.localhost/index.php?page=bg'
document.getElementById('frm-table').submit(); //suggestion does not work - form not submitted
// document.getElementById('cancel-btn').click(); //original does not work
}
evt.returnValue=false;
}
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
};
When the alert is replaced by a .click() nothing happens.
I do not understand why the native click event is not firing.
I am aware there is no click event on a button element, however it does accept and action a mouseclick on it. Calling a function to submit the form (by adding a listener event to the button does not work - it submits the form but the posted values do not include the button action=value pair.
So is there another js command to trigger the button element''s native functionality? Is important to note that the button is one of several type=submit buttons all of which give a different action-value pair.
[Ed] In an attempt to clarify:
I am not trying to add a handler to the button element just trying to replicate the native type=submit function of the button. (mouse clicking the button submits the form with the important action=value pair without any js)
I only have the option of adding javascript at my disposal not changing the dynamic generation of the page as it is part of a much larger application.
So although I thank those who have responded, the answers, so far, they do not resolve the question.
Tested in Firfox31 and IE9
That is because the <button> does not have an onclick handler on it, so it won't be triggered.
Instead of
document.getElementById('cancel-btn').click();
you can just do
document.forms[0].reset();
which will also reset the form.
Unless the button that is called cancel-btn actually has to submit the form in which case you need:
document.forms[0].submit();

JS/jQuery - blur() not firing when user hits "Enter"?

I have a form field that I'd like to munge a little before the user submits the form.
Specifically, it's a location field, and I need to check whether they've added the state abbreviation. If not, I add it.
I'm watching for blur() so i can see when the user's tabbed or clicked out of the field:
$('#views-exposed-form-libraries-map-page-1 .form-item-field-geofield-distance-origin input').blur(function(){
// do stuff
});
`
This works fine when the user clicks the submit button or tabs out of the input.
However when the user hits "enter" or "return" to submit the form, the function doesn't run - I'm guessing because there's no blur event.
Is there some other way to snag the input's value and edit it when the user hits "enter" or "return"?
You can create a .submit() that trigger .blur() on focused element like that :
$('form').submit(function(){
$(':focus').trigger('blur');
})
set a .submit callback as well/instead, this will be called before the actual form submits and you can cancel the submission if needed
$("#myForm").submit(function(e){
//check/do stuff here before submit
//use e.preventDefault() or return false to stop submission if needed.
});
JQuery .submit Doc
$(window).keydown(function(event){
if(event.keyCode == 13) {
$(':focus').trigger('blur');
event.preventDefault();
return false;
}
});

IE bug triggers click for 2 buttons?

I am trying to trigger the submit button when a user presses enter. Works great for all browsers except Internet Explorer 9. Strange thing is that IE insists on also triggering the click for another button I never told it to. Am I doing something wrong or how to fix this?
Below is my code. Pressing enter in IE triggers the submit click as expected, but for some reason also triggers the "some button" click (even without my keypress listener):
$('input[type=submit]').click(function () {
alert('Submit click');
});
//SIMULATE CLICK IF ENTER PRESSED IN SEARCH
$('input[type=text]').keypress(function (event) {
var keycode = event.keyCode || event.which;
if (keycode == 13) $('input[type=submit]').click();
});
//ROUTE CLEAR HANDLER
$('button').click(function () {
alert('Button click');
});
You can see the bug in action here: http://jsfiddle.net/h64xD/
Here are a couple of things to consider:
IE9 counts the <button/> element as type="submit" by default. So to make it non-submit, you have to be explicit:
<button type="button">Some button</button>
If you do that, you will notice that the emulated click event now doesn't trigger the <button/> but still fires 2 events. The reason is that, because you haven't explicitly defined a <form/> element, IE9 assumes the controls as being in a form, and thus pressing enter in the textbox triggers 2 events:
the one that you are emulating
the default form submit button behaviour
So again to get around this issue, you have to be explicit:
<button type="button">Some button</button>
<form><input type="text" /></form>
<input type="submit" value="Submit" />
Now, these are the reasons that you are seeing the behaviour in IE. #MrSlayer's answer caters to the second issue of stopping the keypress event after you have satisfactorily handled it, using preventDefault()
The Enter key has a default behavior to submit, so you need to prevent the default behavior from executing. Because the button tag is, by default, type="submit" it is executing that button when the Enter key is pressed.
//SIMULATE CLICK IF ENTER PRESSED IN SEARCH
$('input[type=text]').keypress(function (event) {
var keycode = event.keyCode || event.which;
if (keycode == 13)
{
event.preventDefault();
$('input[type=submit]').click();
}
});
How about triggering the form's submit instead of a button click?
$('input[type=text]').keypress(function(e) {
var keycode = event.keyCode || event.which,
frm = $(this).closest('form');
if (keycode == 13) {
e.stopPropagation();
frm.submit();
return false;
}
return true;
});
--EDIT--
Updated Slightly to stop the event propagation.
First off, you don't need to manually attach an event to submit a form when the user presses enter - the browser already handles that.
Oddly enough, this was to do with the order of the elements, implicit form-associations, as well as the fact that IE handles buttons as submit elements.
Try swapping the order of these buttons to see what I mean:
<input type="text" />
<input type="submit" value="Submit" />
<button>Some button</button>
Naturally, the browser is already instructed to listen to respond to the Enter on a text-input. This results in the browser clicking the associated submit button. Further, since you haven't explicitly provided a form, or associated elements with one another via their form attribute, the browser is attempting to make that relationship for you.
In your code, the <button> element was assumed to be the submit button of the text-input (because it was the first submit button in the implicit form). As such, anytime you press Enter on the text-input, the browser naturally raises the click event of the associated button.
If you re-order the elements, as I have above, we see the opposite take place. IE associates the other <input> element with the text-box. And pressing Enter on the text-box implicitly raises the click event on the submit input.
You can confirm this behavior by comparing the .form attributes of various elements. For instance, adding some id values will give us easier access to these:
<button id="fiz">Some Button</button>
<input id="foo" type="text" />
<input id="bar" type="submit" value="Submit" />
Then run some quick comparisons:
var button = document.getElementById("fiz");
var text = document.getElementById("foo");
var submit = document.getElementById("bar");
button.form === text.form; // true
submit.form === text.form; // true
button.form === submit.form; // true
So in the end, it's up to you to remove the ambiguity between the two buttons, by declaring the <button> element to be type='button', or by placing it after the intended submit button.

How can I trigger Button's OnClick event from Javascript in an asp.net application which is using Callback?

I'm using Callback, on a asp.net webforms project. When clicked button, it is working great. However I have a textbox, when user press 'enter' it must trigger button. So I did it,
function search_enter(event) {
if (event.keyCode == 13) {
$("#search_button").click();
}
}
Yes, it triggers first javascript function of callbacks. But it is doing postback not callback :S
How can I fix this?
Update:
I solve the problem, calling callback event at input's keyup event.
function search_enter(event) {
if ($('#search_textbox').val() == '')
return;
WebForm_DoCallback('__Page', Basla(), Istek, null, Hata, true)
}
<input id="search_textbox" onkeyup="search_enter(event)" type="text" />
But if I pressed enter, when cursor in input. It is doing postback. How can I fix this?
I found it. if textbox is in <form runat="server"> tag, It is doing postback, when pressed enter. I've removed form tags and it solved.

enter in asp:TextBox clicks my button (which has a js function bound to it)

basically I have this:
<asp:TextBox runat='server' />
<button id='b2'>hi</button>
<script>
$('#b2').click(function(e){
e.preventDefault();
alert('you clicked the button');
});
</script>
the problem is that when hitting enter inside the textbox the click event on the b2 occurs so I get the js function executed, anybody knows how to stop this?
Pressing the return/enter key while focusing a text box is treated the same way as clicking on the submit button. What you can do is attach a keypress event handler to all text boxes in your form, and simply ignore the return key press.
Code looks like this:
$('input[type="text"]').keypress(function(event) {
if(event.keyCode == 13) {
event.preventDefault();
alert("enter!");
}
});
Note that I don't use ASP, so I tested this with a standard HTML text box and submit button.
adding the attribute type="button" to the button tag stopped this behavior o_O

Categories

Resources