How to invoke a p:commandButton by JavaScript on enter keypress? - javascript

I have write a and a in my page.
When enter key was pressed ,I want to do any js check, if success post an action.
Javascript:
function text_onkeypress() {
if(event.keyCode==13){
formSubmit();
}
}
HTML:
<p:inputText id="context" value="#{bean.fileName}"
onkeydown="text_onkeypress();"></p:inputText>
<p:commandButton id="search" value="submit" onclick="return formSubmit();"
action="#{action.getResult}" ></p:commandButton>
when I write query("#search")[0].click() in the javascript.It can do the check, but can't do action="#{action.getResult}".
I don't know how to do the losted action.

The easiest way for you to submit your form from Javascript is to just invoke the click() event for the jQuery object of the <p:commandButton>.
Most of the Primefaces components can be accessed from Javascript by declaring the widgetVar attribute. This attribute creates a Javascript variable. Eg.
<p:commandButton id="search" value="submit" onclick="return formSubmit();" action="#{action.getResult}" widgetVar="searchClientVar" />
I can now access the variable in the formSubmit function. This Javascript variable has an attribute called jq which references the underlying jQuery object and what you can use to invoke the click event.
function text_onkeypress() {
if(event.keyCode==13) {
searchClientVar.jq.click();
}
}
This will invoke the server side action of the commandButton and submit the form values if they pass validation.

What kind of checks do you need?
You don't need to manually submit on enter(especially when you have just one form).
If you want to submit the form only if the user enters something you could take advantage of validateLength tag.
<h:outputLabel for="firstname" value="Firstname: *" />
<p:inputText id="firstname"
value="#{personBean.firstname}"
required="true" requiredMessage="You have to enter your name" label="Firstname">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="firstname" />
See here a demo: http://www.primefaces.org/showcase-labs/ui/pprAjaxStatusScript.jsf
PS:What PF version do you use?

Related

Set Primefaces inputText value from Javascript and have ajax fire

I have a primefaces(v10) input text which I need to set from a javascript function and also have an ajax event fire on blur. In my code I have this, but have been unsuccessful in getting the ajax function to fire.
<h:form id="myForm">
<p:inputText id="myText" widgetVar="myTextVar" value="#{myBean.myText}">
<p:ajax event="blur" listener="#{myBean.updateMyText}" update="myForm"/>
</p:inputText>
</h:form>
I can set the inputText using:
document.getElementById("myForm:myText").value="The Value"
But I'm wondering if I need to use something from the PF() Widget API?
Its easy. Just use the widget...
PF('myTextVar').jq.val('The Value').trigger('change');

validate and submit html form required inputs using javascript

I have a form which contains inputs with required tag. It normally validates when I click on an input of type submit.
But I wanted to be able to initiate that process programmatically using javascript. or when an element outside of the form is clicked.
Is this possible? how can I do this?
function validateAndSubmit(){
//what can I do here to initiate same process?
//tried
document.querySelector("form").submit() //this one submits without validating
document.querySelector("#submitter").click() //no such function as this
}
<form>
<input required placeholder="name"/>
<input id="submitter" type="submit"/>
</form>
<button onClick=validateAndSubmit()>Send</button>
I want to do this from other event handler functions too. Is there a way to do this?
Thanks
You have to first focus on the form with the focus() method:
function validateAndSubmit(){
document.querySelector("form").focus()
document.querySelector("#submitter").click()
}
<form>
<input required placeholder="name"/>
<input id="submitter" type="submit"/>
</form>
<button onClick=validateAndSubmit()>Send</button>

How to execute a set of JavaScript code only if HTML form validation is succesfull

I have a HTML form with some fields and a submit button. couple of fields are mandatory. I have a set of JavaScript code which i need to execute only if the form validation is successful. If there is some validation error on the form, the JavaScript code shall not execute. Below is the sample code:
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
/*JavaScript*/
$("#sampleForm").submit(function(){
//Set of JavaScript code to execute if validation is success.
});
For me above JavaScript code does not work.
Please help!
In a comment you've said:
But if i use $("#sampleForm").submit() to submit the form, the form gets submitted but if i write function inside submit() ($("#sampleForm").submit(function(){ //Set of JavaScript code to execute if validation is success. });) then nothing happens !
That function is called when the submit event is fired, but the event isn't fire when the controls are invalid because the form won't be submitted.
The individual form controls get an invalid event when the user tries to submit the form when they're invalid. You can use that to provide feedback beyond what the browser supplies if you like:
$("#sampleform")
.on("submit", function() {
alert("Got the 'submit' event; form is being submitted");
})
.find("input, select")
.on("invalid", function() {
// Will fire for *EACH* invalid control
alert("Validation failed");;
});
Fiddle (Stack Snippets don't allow form submission even when it's cancelled.)
In case you need to submit the form programmatically (by calling submit), you can use checkValidity first to see if the form is valid:
// When submitting programmatically
var form = $("#sampleForm");
if (form[0].checkValidity()) {
form.submit();
}
Side note: When you use jQuery to submit the form (above), submit event handlers will be called. But if you use the DOM to submit the form ($("#sampleForm)[0].submit()), they won't be.
Just write a submit handler and execute your codes.
$("#sampleForm").submit(function(){
// Your code.
})
Submit handler triggers only when you complete the validation by HTML5 custom validator.
Here is a demo : http://jsfiddle.net/sureshatta/9ky8Z/118/
Html5 form have checkValidity method.Also since it is a form and button type is submit it will default throw an error pop up if it is not valid. checkValidity method return a boolean value true if it is valid. You can take a look in this method for further your job
$("#sampleForm").submit(function(e) {
var result = document.getElementById('firstname').checkValidity()
console.log(result) // will log true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
Thanks everyone for the answers!
I tried each one of your's solution which helped me to reach to my solution. Below worked for me:
if($("#sampleForm").valid()){
$("#sampleForm").submit();
//Set of JavaScript code to execute.
}

Pressing enter does not hit the expected search button via p:defaultCommand [duplicate]

This question already has answers here:
Submit form with primefaces widgets on enter
(2 answers)
Closed 6 years ago.
I am trying to use primefaces but its not producing expected result. My code snippet is below
<h:form id="searchForm" styleClass="searchForm">
<p:panelGrid columns="3">
<p:commandButton id="left-overlay-btn" value="" styleClass="xschnapp-search-filter-menu" />
<p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" />
<p:commandButton value=" " id="searchButton" action="#{cc.attrs.searchAction}" styleClass="xschnapp-search-action" />
</p:panelGrid>
<p:defaultCommand target="searchButton">
</h:form>
In Above code, when I press enter then it hits the first column button and not the expected search even after using primefaces p:defaultCommand.
http://blog.primefaces.org/?p=1787
Someone adviced me to use javascript to manually click search button, thats also failing. Perhaps due to my weak javascript knowledge. Below is code snippet with javascript and that also hit first column button instead of desired search button
<h:form id="searchForm" styleClass="searchForm" onkeypress="if (event.keyCode == 13) {document.getElementById('searchButton').click(); return false}">
<p:panelGrid columns="3">
<p:commandButton id="left-overlay-btn" value="" styleClass="xschnapp-search-filter-menu" />
<p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" />
<p:commandButton value=" " id="searchButton" action="#{cc.attrs.searchAction}" styleClass="xschnapp-search-action" />
</p:panelGrid>
</h:form>
Can somebody please help me.
I have had the same problem defining global hotkey for my enterprise site. The aproach which worked for me is:
<h:form id="form">
<p:hotkey bind="Enter" update="msg" actionListener="#{yourBean.yourSearchfunction}"/>
<p:remoteCommand name="search" actionListener="#{yourBean.yourSearchfunction}" update="msg"/>
//Your code
</h:form>
<h:outputScript>
$(':input').bind('keydown', 'Enter', function () {
search();
return false;
});
</h:outputScript>
With this code regardless where your cursor stays it will start your search function on pressing enter. Maybe you want it a bit more finegrained then you can remove the p:hotkey component to only use to start your search function if the cursor is inside a input field.
The javascript is needed because the p:hotkey component works everywhere except if the cursor stays inside an input field. So you bind your remote comand to the enter event inside every inputfield in the view.

How do I detect how a form was submitted via JavaScript?

I have a form with multiple submit buttons and I'm listening for the 'submit' event via JavaScript. I want to know which submit button or form field (if the user pressed 'Enter/Return') triggered the submit event. Is there a way to get the HTML element that the user clicked on or pressed 'Enter/Return' in?
Update since people aren't understanding me:
This is via JavaScript before the form is submitted. No server-side detection allowed. I also need to handle the form being submitted via the user pressing Enter or Return.
Code
<form action="" method="POST">
<input type="text" name="first_name">
<input type="text" name="item">
<input type="submit" value="Add item">
<input type="submit" value="Submit">
</form>
Clicking 'Add Item' or pressing Return/Enter inside name="item" will add another form field.
Final Note
As far as I can tell, there isn't a way to detect which form field triggered a form submission. If you need to prevent submitting a form that has multiple buttons and/or from Enter/Return, you'll need to use <input type="button"> and bind event handlers to the form fields you want to stop form submission from.
If you have multiple submit buttons, the way you can tell is by giving each of them a unique name attribute, like this:
<input type="submit" name="submit1" value="Submit 1"/>
<input type="submit" name="submit2" value="Submit 2"/>
<input type="submit" name="submit3" value="Submit 3"/>
The one that is focused is sent along with the form submit, so if you clicked the one with a name of "submit2", that would come through in the form POST (or GET). If enter is hit, the first button in the source (in this case submit1) is considered the default and is sent along. You could set it to display:none to use as a dummy for detecting whether enter was pressed vs actually clicking a submit button.
EDIT:
In response to your comments, to capture the enter key getting pressed in certain elements you can do this with jQuery.
Note, you'll need to give first_name and add_item id attributes, and turn add_item into a type="button" instead of type="submit".
HTML:
<form action="" method="POST">
<input type="text" name="first_name"/>
<input type="text" id="item" name="item"/>
<input type="button" id="add_item" value="Add item"/>
<input type="submit" value="Submit"/>
</form>
JS:
$("#item").keydown(function(event){
if(event.keyCode == 13) {
addFields();
event.preventDefault();
event.stopPropagation();
}
});
$("#add_item").click(function(event) {
addFields();
});
You could set the onclick event on each element you are interested and call a javascript function with a different parameter for each element clicked.
From that function you send the idendifier of the button to the server side as a parameter
Just put a different name on each submit button, whichever one was clicked will be submitted (i.e. its name/value pair) with the form. Forms have worked like this since the begining of (WWW) time.
If the form is sumitted by enter or other keypress, no the first submit button name/value pair will be submitted.
Edit
Re-reading your question, you may want to determine how the form was submitted before it is sent. A click listener on the form can remember the last submit button clicked, but in Firefox, pressing enter in an input dispatches a fake click on the first submit button so you can't detect it.
I think you can't do it reliably other than using the basic method suggested above or Jordan's hidden submit button. If you say why you need to do this, perhaps more help can be provided.
here's an option if you don't mind using jQuery:
example: http://jsfiddle.net/U4Tpw/
use something like
$('form').submit(function() {
// identify the form by getting the id attribute
handleWhichForm($(this).attr('id'));
});

Categories