I have the following piece of code, that is being executed on submit of a form. Yet the following logic is incorrect as the intent was to develop a universal function that would work for all the forms in my DOM. After failing over and over I ended up creating this function, specific to a this form, that verifies if the values of input fields in my form are the same as their custom defVal attribute, if so the form will stop submitting and an error message will pop up.
My question consists on the following: how can i check if any child elements of my form meet specific parameters, like for example being an input field and have their .val() == .attr('defVal')?
I've already tried using .find(), .children() and .childNode functionalities. Could somebody please suggest me a good solution and if possible explain your code
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<input type="text" name="USERNAME" required value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" required value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
<div class="infoWrapper">
<div class="info">
</div>
</div>
jQuery:
$('div.login').ready(function(){
$('div.login form').submit(function(e){
if( $('div.login form input').val()==$('div.login form input').attr('defVal') ){
var numMsgs=$('div.login form').children();
if( numMsgs.length<=6 ){
var formHtml=$('div.login form').html();
$('div.login form').html('<a class="sysMsg" href="#">error::invalid username/password</a>'+formHtml);
$('div.login form a.sysMsg').addClass('errFatal').fadeIn(300).delay(5000).fadeOut(300);
}
e.preventDefault();
}
});
});
Try (this pattern)
$(function () {
var elems = $(".login input[defval]");
console.log(elems.length);
$.each(elems, function (i, el) {
if ($(el).val() === $(el).attr("defval")) {
// do stuff
console.log(i, $(el).val() === $(el).attr("defval"), $(el));
};
});
});
jsfiddle http://jsfiddle.net/guest271314/9578v/
After sleeping over the subject I ended up managing to do the task. I've changed the html a bit. Anyway thank you for your suggestion as it was quite useful and actualy toaught me something.
HTML:
<div class="login" align="center">
<div class="formWrapper">
<form action="index.php?r=backoffice" method="post">
<p class="jQueryErr">
<?php
if( !empty($_POST['USERNAME']) && !empty($_POST['PASSWORD']) ){
phpClass::USER_login($_POST['USERNAME'],'username',$_POST['PASSWORD'],'password');
}
?>
</p>
<input type="text" name="USERNAME" value="username" defval="username" maxlength="16">
<input type="password" name="PASSWORD" value="password" defval="password" maxlength="16">
<input type="reset" value="reset">
<input type="submit" value="submit">
<hr/>
Can't log in?
</form>
</div>
jQuery:
$('form').submit(function(e){
var elems=$(this).find('input[defval]');
var errWrapper=$(this).find('p.jQueryErr');
for( var i=0; i<elems.length; i++ ){
if( $(elems[i]).val()==$(elems[i]).attr('defVal') ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error:: invalid username/password</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}else if( $(elems[i]).val().length<8 ){
$(errWrapper[0]).html('<a class="sysMsg errWarning" href="#">error::'+ $(elems[i]).attr('defVal') +'::is too short!</a>');
var formSysMsg=$('p.jQueryErr a.sysMsg');
$(formSysMsg[0]).fadeIn(300).delay(5000).fadeOut(300);
e.preventDefault();
break;
}
}
});
Related
I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>
I am using Bootstrap and I have two identical forms. I am trying to add form submission to Google Search results and it works but when I include two of the same form it doesn't work because of the id being the same on both. How can I fix this? The ID needs to be the same because google looks for the "G". The reason I have two forms is because I have it displayed differently on mobile. Using media queries. Below is my code thanks.
<form name="globalSearch" class="navbar-form" role="search" form action="" onsubmit="return validateSearch()">
<div class="input-group add-on">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:11;NB:1" />
<input type="hidden" name="ie" value="UTF-8" />
<input class="form-control" placeholder="Search entire site..." id="q" name="q" type="text">
<div class="input-group-btn">
<button class="btn btn-default btnSubmit" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
function validateSearch() {
if (globalSearch.q.value.length == 0) {
document.getElementById("q").value = "Enter a Value";
document.getElementById("q").style.color = "red";
return false;
}
}
You probably want to change the placeholder, so the user don't have to delete the text than type in a query. Please view updated function.
function validateSearch() {
var q = document.getElementById('q');
if (q.value.length == 0) {
q.setAttribute('placeholder', 'Enter search term')
q.style.borderColor = "red";
return false;
}
}
Two elements can not share same ID.
Either use CSS styling to make different looks in mobile, either hide one of forms from webserver (PHP/etc) side either dont use getElementById - instead, use jQuery:
<form name="globalSearch" ... >
<input name="q" data-input-type="desktop" id="q">
..
</form>
<script>
function validateSearch() {
var field = $("input[data-input-type="desktop"]');
field.val("Enter value here...");
field.css("color","red");
}
</script>
I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>
I have a single form on the page and I have some jQuery to make sure that the inputs have been completed before the submit.
But now I need to have multiple similar forms repeated on the page and I need to change the jQuery to only check the two inputs in the form that the button was clicked and not check any other form on the page.
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
<div class="offerDate">
<form class="form-inline hidden-phone" action="http://www.treacyswestcounty.com/bookings/" method="get">
<fieldset>
<input type="text" name="from_date" placeholder="dd/mm/yy" id="from_date" class="input-small hasDatepicker">
<input type="text" name="to_date" placeholder="dd/mm/yy" id="to_date" class="input-small hasDatepicker">
<button id="submitDates" class="btn btn-main" type="submit">CHECK NOW</button>
</fieldset>
</form>
</div>
The jQuery that I have used previously to check on form using ID
// validate signup form on keyup and submit
jQuery('#submitDates').click(function () {
var found = false;
jQuery("#to_date, #from_date").each(function(i,name){
// Check if field is empty or not
if (!found && jQuery(name).val()=='') {
alert ('Please choose your arrival and departure dates!')
found = true;
} ;
});
return !found;
});
.prev( [selector ] )
Returns: jQuery
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
This is quite short and will target any input displayed just before a button :
$("button").prev("input")
jsFiddled here
you can try like this:
CODE
jQuery('.submitDates').click(function () {
var found = false;
jQuery(this).siblings("input").each(function (i, name) {
// Check if field is empty or not
if (!found && jQuery(name).val() == '') {
alert('Please choose your arrival and departure dates!')
found = true;
};
});
return !found;
});
assuming your inputs are siblings for the button. Note I also changed button's id into class.
FIDDLE http://jsfiddle.net/FY9P9/
Closest and Find do it as well, wherever the input are for the button :
HTML:
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
<form class="form">
<input type="text" class="toDate" />
<input type="text" class="fromDate" />
<div class="button">Click</div>
</form>
JS:
$(".button").each(function () {
$(this).click(function () {
if (($(this).closest(".form").find(".toDate").val() == "") || ($(this).closest(".form").find(".fromDate").val() == "")) {
alert("Please fill in arrival and departure Date");
}
})
})
http://jsfiddle.net/GuqJF/1/
I'm trying to validate a form filed via javascript. The idea is that the form filed has a set list of accepted values and only these values work. So if the field is black it will alert that the ID is incorrect. If the field has input which is not in the list it will display that ID is incorrect. I have gotten close. I just need a little more direction.
Here is my code:
script type="text/javascript">
function validateForm()
{
var x=document.forms["dispatch"]["ID1"].value;
var arr=["CA238", "Pete", "John"];
if x==(.inArray(inputVal, arr) > -1)
{
alert("Correct Dispatcher ID Required");
return false;
}
}
</script>
<form id="form_242533" class="appnitro" name="dispatch" onsubmit="return validateForm()" method="post" action="<?php echo $_SERVER["PHP_SELF"]?>">
<li id="li_9" >
<label class="description" for="element_1">Dispatch ID</label>
<div>
<input id="element_1" name="ID1" class="element text medium" type="text" value=""/> Put your assigned dispatcher ID
</div>
</li>
<li class="buttons">
<input type="hidden" name="Submit" value="Submit" />
<input id="submit" class="button_text" type="submit" name="submit" value="Submit" />
<input type="reset" />
</li>
</ul>
</form>
Change this:
if x==(.inArray(inputVal, arr) > -1)
to this:
if ($.inArray(x, arr) == -1)
if you're using jQuery.
If you don't have jQuery on the page, change it to this instead:
if (arr.indexOf(x) == -1)
Note however, that this method won't work in IE < 9. Use the polyfill provided here to add indexOf support to older versions of IE.