$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode === 13){
SearchThis.submit();
return false;
}
});
});
So now my form (SearchThis) is submitted whenever the enter key is pressed which is great however how do I modify it to check if mysearchfied has been completed before it submits?
IE. If mysearchfied is empty and the enter key is pressed don't submit the form. If mysearchfied contains text and the enter key is pressed then submit the form.
Hope you can help! Thanks...
If you just want to validate the textbox for required use HTML5 required attribute like:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>
There are two ways to validate the form.
-> Check is the form valid usind the form valid function
SearchThis.validate().valid()
-> validate each field for value as told by #n01ze
if the id of your input field is mysearchfield, then you could do it like this:
var msf = document.getElementById("mysearchfield").value;
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode == 13){
if (msf != "") {
SearchThis.submit();
return false;
}
else
{
// some code here....
}
}
});
});
if (event.keyCode === 13) {
if ($('mysearchfied_ID_or_Class').val()!=='') {
//mysearchfied is not empty
SearchThis.submit();
}
else {
//dont submit, do your checks
}
return false;
}
Related
I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
I want to validate my jsp fields while pressing the tab button.How to implement it using jquery.
Below is my jsp page
<form:form method="POST" commandName=" test" name="testname" onclick="submitForm();" >
<div>
<form:input path="testpath" type="text" class="values " name="tpath" id="code"/>
</div>
<div>
<form:input path="testname" type="text" class="values " name="tname" id="name"/>
</div>
<div>
<input type="submit" value="Register">
</div>
</form:form>
jQuery
function submitForm(){
$('form').on('submit', function (e) {
alert("test");
var focusSet = false;
if (!$('#tpath').val()) {
if ($("#tpath").parent().next(".validation").length == 0) // only add if not added
{
$("#tpath").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter the code</div>");
}
e.preventDefault();
$('#tpath').focus();
focusSet = true;
} else {
$("#tpath").parent().next(".validation").remove(); // remove it
}
if (!$('#name').val()) {
if ($("#name").parent().next(".validation").length == 0) // only add if not added
{
$("#name").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter seasoname</div>");
}
e.preventDefault(); // prevent form from POST to server
if (!focusSet) {
$("#name").focus();
}
} else {
$("#name").parent().next(".validation").remove();
}
});
}
on button click only my form validates.How to validate by clicking inside form.
Capture keycode and write an event for keypress on the elements as below:
//Combine keypress for both the elements as below
$("#tpath,#name").on('keypress',function(e){
if(e.which==9 && !$(this).val())
if ($(this).parent().next(".validation").length == 0)
{
$(this).parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter the code</div>");
}
else {
$(this).parent().next(".validation").remove(); // remove it
}
$(this).focus();
});
$('#tpath').keyup(function(e) {
e.keyCode; // this value
if(e.keyCode == 9){
//e.keyCode is 9 mean tab is pressed
// write your validation code over here.
}
});
I think this code can work for you
Use this
$('#tpath').keyup();
This triggers on release key event.
I need the if bottom if statement to run if #nextQ is clicked (like it is currently) or if enter is pressed.
$('input[type=text]').on('keyup', function(e) {
if (e.which == 13) {
alert("enter is pressed");
return true;
}
});
$('#nextQ').click(function() {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
});
If your input is wrapped in a form and that form has a submit button, it is submitted when you press enter inside the input.
Knowing this you should listen to the submit event:
The form:
<form class="myForm">
<input name="answer" type="text">
<button id="nextQ" type="submit">next Question</button>
</form>
JS:
jQuery( '.myForm' ).on( 'submit', function( event ) {
//me.html validations
if (actual == 0 && document.URL.indexOf("me.html") >= 0){
loadNew();
}
} );
every time time when i pressed the enter key in input field then it should alert some thing but facing problem in doing that here is the code.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(this.value)">
Here is the js code
<script>
function ajxsrch(str)
{
var keycod;
if(window.event)
{
keycod = str.getAscii();
}
if(keycod==13){alert("You pressed Enter");}
}
</script>
I think it is because you aren't passing e to the function and only using window.event which does not work in all browsers. Try this code instead.
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)">
<script>
function ajxsrch(e)
{
e = e||event;
var keycod;
if(e)
{
keycod = e.keyCode||e.which;
}
if(keycod==13){alert("You pressed Enter");}
}
document.getElementById("input").onkeyup=ajxsrch;
</script>
Try this..
<input type="text" class="searchfld" id='input' onchange="gotothatpost(this.value)" onkeyup="ajxsrch(event)">
<script>
function ajxsrch(e)
{
if (e.which === 13) {
alert("You pressed Enter");
}
return false;
}
</script>
Pass the event object to the function call
<input type="text" class="searchfld" id='input' onkeyup="ajxsrch(event)">
Use the event object in the JS and get the key value.
function ajxsrch(ev) {
var ch = ev.keyCode || ev.which || ev.charCode; // Proper way of getting the key value
if(ch == 13) {
alert("You pressed enter");
}
}
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}