jQuery validate only get triggered on the second submit - javascript

I have the jquery validation function in the javascript which will get called from react js function.
React JS
function handleFormSubmit(e){
e.preventDefault()
window.validateForm();
}
return (
<form id="contactForm" onSubmit={handleFormSubmit} novalidate="novalidate">
<input name="name" id="name" type="text" placeholder="Name" onChange={handleInputChange} />
<textarea name="address" id="address" cols="4" rows="4" placeholder="Address" onChange={handleInputChange}></textarea>
<button type="submit">Submit</button>
</form>
)
JavaScript
function validateForm(){
$("#contactForm").validate({
rules: {
name: { required: true },
address: { required: true }
},
messages: {
name: { required: "Name field is required" },
address: { required: "Address field is required" }
}
});
}
The first submit is calling the validateForm() function but it won't trigger the jquery validate(). It only get triggered on the second submit click.

The reason is because you are assigning the Validation on the first click. It assigns its own event listener. The second click runs it and you also reassign the validate code again.
You need to just call the code on document ready. So get rid of the on submit
I have the jQuery validation function in the javascript which will get called from react js function.
$(function () {
window.validateForm();
});
And seeing you are using jQuery with React, it is a bit more complicated than that.

Related

VueJS prevent form submission on submit and submit the form on keyup

I have a form that looks like this:
<form id="myForm" action="/searchuser" method="POST" #submit.prevent="onSubmit(inputValue)">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Text input" v-model="inputValue" #keyup="onKeyUp" #blur="inputFocused = false">
<ul v-if="inputFocused">
<li v-for="value in values"><a class="panel-block is-primary" :href="value.link">#{{value.title}}</a></li>
</ul>
</div>
</div>
</form>
And in my JavaScript, I have two methods onSubmit and onKeyPress:
<script>
export default {
data() {
return {
inputValue: "",
inputFocused: false,
values: [
{ title: "facebook", link: "http://facebook.com" },
{ title: "twitter", link: "http://twitter.com" },
{ title: "gplus", link: "http://plus.google.com" },
{ title: "youtube", link: "http://youtube.com" }
]
};
},
methods: {
onKeyUp: function() {
document.forms["myForm"].submit();
this.inputFocused = true;
},
onSubmit: function(inputval) {
console.log(inputval);
}
}
};
</script>
What I am trying to achieve is when the user presses a key, I want the form to be submitted but I don't want the page to be redirected to /searchuser route. But as soon as I press a key, the page gets redirected even though I am using the prevent modifier to prevent the submission. How do I prevent it from being redirected and submit it on keyup/keydown only? My goal is to perform an ajax call through onSubmit by sending the inputval to the server.
Vue is not overriding the DOM default behavior, if you decide to
access the DOM API directly while bypassing vue mechanics (e.g.
document.forms)
If you want to submit a form without the redirection, you have to do
ajax request.
you have to use axios (my personal choice). because you are trying to submit the form directly ...in order to keep up with the default form submission data format, I assume you need to sereialize the data as application/x-www-form-urlencoded format. check the docs.
see the code:
onKeyUp method:
onKeyUp: function() {
axios.post("/searchuser", qs.stringify({ inputValue: inputValue }));
this.inputFocused = true;
},
Remember to add axios and qs to your dependencies using npm, and import them on the file.

How use liferay validator with js submit?

I try to use Liferay validator with javascript on Liferay 6.2.
Have a problem is my button must using submit form with a button onlick, but when submit this way Liferay form validator no trigger prevent submit. It just triggers when I using a button type submit.
Here mycode example:
<portlet:actionURL name="updateURL" var="submitURL"/>
<aui:form name="fm2" id="fm2" action="<%=submitURL %>" method="post">
<aui:input name="userName" value='' label="User Name"></aui:input>
<aui:input name="password" value='' label="Password"></aui:input>
<aui:button type="button" name="logIn" id="logIn" value="Login" />
</aui:form>
<aui:script>
AUI().use('aui-base','liferay-form','aui-form-validator',function(A){
A.one("#<portlet:namespace/>logIn").on("click",function(){
submitForm(document.<portlet:namespace />fm2);
});
Liferay.Form.register(
{
id: '<portlet:namespace/>fm2',
fieldRules: [
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>password',
validatorName: 'required'
},
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>userName',
validatorName: 'required'
}
]
});
});
</aui:script>
What i can do ?
How to liferay can prevent event submit with tag, but does not with js?
Here is AUIFormValidator-portlet to demo.
https://drive.google.com/open?id=0B27gY2oYFX7QTTFFdXc3TnZ4d1k
You can do one thing,
<aui:form name="fm2" id="fm2" action="javascript:void(0)" method="post">
It will prevent your submit event and fire the aui form validation.
Now in onClick function you can assign your submit url to form action like below.
$("#<portlet:namespace/>logIn").on("click",function(){
var url = '${submitURL}';
$('#<portlet:namespace />fm2').attr('action', url);
$('#<portlet:namespace />fm2').trigger("submit");
});

JQuery validation form but not `submit` button

I'm using the JQuery.Validation plugin to validate some fields in a form, but I don't want to use a submit button, I want to use just an <input type="button"> and once clicked using JQuery I want to call my controller, the only thing is that it's not a submit button, so even if the fields are wrong or not validated it will call the controller even if the fields values are wrong, because I'm using the .click() event of JQuery when that button is clicked, I want when I have wrong values on the fields and the validation is showing an error message not to call my action controller even if the button is clicked, how can I reach this?
This is my html code:
<script src="~/js/jquery.validate.js"></script>
<form action="post" class="rightform newsletter" id="formSubscription">
<div class="title">
<img src="http://ligresources.blob.core.windows.net/public/UK/Content/Images/newsletter.png" alt="">NEWSLETTER
</div>
<input type="text" id="txtFullName" name="fullName" placeholder="Full name" required>
<input type="email" id="txtEmail" name="email" placeholder="Email address" required>
<button type="button" id="btnSubscription" data-url="#Url.Action("SubscriptionEmail","Email")" style="background-color:#f66804;">SUBSCRIBE TO NEWSLETTER</button>
</form>
This is the JQuery.Validation plugin code:
$(document).ready(function () {
$("#formSubscription").validate({
rules: {
email: {
required:true,
email:true
},
fullName: {
required:true
}
},
messages: {
email: {
required: "Please enter an email address",
email: "Please enter a valid email address"
}
}
});
});
And this is the JQuery function that I have for the moment to throw when the btnSubscription is clicked:
$(document).ready(function () {
$("#btnSubscription").click(function () {
SendSubscription();
}),
return false;
}),
function SendSubscription() {
$.ajax({
type: "post",
url: $("#btnSubscription").data("url"),
data: { fullName: $("#txtFullName").val(), emailAddress: $("#txtEmail").val() },
success: function () {
alert("email sent")
},
error: function () {
alert("An error occurred..")
}
});
}
Once you set up your .validate() all you need to do is call the .valid() method in your .click() handler. This is what submit does automatically, but you can call it manually with the .valid() method.
you should use type submit, and then you can use the submitHandler in order to manage other things you want to do, like this:
$("#formSubscription").validate({
submitHandler: function(form) {
// do other things for a valid form
form.submit();
}
});
Take a loot at the documentation: https://jqueryvalidation.org/validate/
put an if in the SendSubscription function:
if (yourValidationDidntPass) {
//do whatever you want
}
else {
$.ajax({...});
}

Polymer Iron-Form response

I'm using Polymer's Iron-Form component to submit this form I have created, but the problem is that the response from the php script won't output to the actual html. I'm stuck on how to do this and have tried many different things. What am I doing wrong? Here's my scrpits:
<dom-module id="user-signup">
<template>
<form is="iron-form" id="formGet" method="post" action="/core/register.php">
<paper-input char-counter autoValidate="true" error-message="{{item.error_name}}" label="Username" maxlength="25" required name="username"></paper-input>
<paper-input char-counter error-message="{{error_displayn}}" label="Display Name" maxlength="35" required name="displayname"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Password" maxlength="25" required type="password" name="password"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Confrim Password" maxlength="25" required type="password" name="cfmpassword"></paper-input>
<gold-email-input class="paper-input-input" label="Email" required name="email" auto-validate error-message="{{error_email}}"></gold-email-input>
<br />
<br>
<paper-button raised onclick="clickHandler(event)"><iron-icon icon="check"></iron-icon>Submit</paper-button>
</form>
</template>
<script>
function clickHandler(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
Polymer({
is: 'user-signup',
properties: {
error_name: {
type: String,
value:"Username Is Invalid!"
},
error_displayn: {
type: String,
value:"Display Name Is Invalid!"
},
error_password: {
type: String,
value:"Password Is Invalid!"
},
error_email: {
type: String,
value:"Email Is Invalid!"
}
},
listeners: {
'iron-form-response': 'formResponse',
'iron-form-submit': 'formSubmit',
'iron-form-error': 'formError'
},
formSubmit: function(event) {
var pmn = document.querySelector('#waitForResponse');
pmn.setAttribute("opened", "true");
console.log("Form was submitted");
},
formResponse: function(event) {
setTimeout(function(){
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
console.log('There was a response');
var response = event.detail;
alert(response);
},
formError: function(event) {
console.log('Form Error, no actual response');
setTimeout(function(){document.querySelector('#errorToast').show();
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
}
});
</script>
</dom-module>
Now the listeners work and when there is a response from the php page, the alert pops up but it says: [Object object]. Here is the php script:
<?php
$data[] = array(
"id" => $id,
"error_name" => $error_name,
"success" => true
);
echo 'dd';
?>
I have tried to echo $data as json but what didn't work either. I've tried to search it on Google and Stack but haven't found anything. What am I doing wrong?
according to the docs you have binded your listeners to a host element and not to form itself.
maybe this will help:
listeners: {
'formGet.iron-form-response': 'formResponse',
'formGet.iron-form-submit': 'formSubmit',
'formGet.iron-form-error': 'formError'
}
whats the model object, that your successful login call on php would return?
you could use the following, cosume the json coming back inside JS promise
$myPhpCallLogon.then(function(user) {
user.firstName...
user.id...
user.email...
var polyListUser = document.querySelector('#userView');
set watch vars in polyListUser element....
}
and then user your template to get the name,id, email etc into the dom of your element that displays the user.

form is not refreshing after ajax submit and jquery validate

I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.
The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?
CODE:
$(document).ready(function () {
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#newform").validate({
//validation
debug: false,
rules: {
Name: {
required: true,
minlength: 3,
},
Surname: {
required: true,
},
},
submitHandler: function (form) {
$.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
$('#newform').reset();
});
}
});
});
HTML:
<form name="newform" id="newform" action="" method="POST">
<p>Name:</p>
<input type="text" id="pName" name="sName" /><br />
<p>Surname:</p>
<input type="date" id="pSName" name="pSName" /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
You can use the following code to clear your form:
$('#newform').reset();
To focus on a specific <input> then you can use this after the reset() call:
$('input[name="sName"]').focus();
Try the following:
submitHandler: function (form) {
var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
});
jqxhr.done(function() {
$('#newform')[0].reset();
});
}
$('#newform').reset();
The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php
In the ajax call pass async also in the object parameter-
{url:'xyz.com',async:false}

Categories