I have two forms (consist with input,textarea,checkbox) in a page. I want check emptiness of these forms separately on click seperate button.
I use the following script. But it shows empty message if any of these form input is empty.
$('#submit').click(function(e) {
var empty = false;
$('input, textarea').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (empty) {
alert("empty");
e.preventDefault();
}
else {
document.getElementById("contact").submit();
}
})()
Never assign stuff to submit buttons
Do not submit a form from a submit button if you have chosen to use preventDefault if something wrong. It could submit the form twice
$(function() {
// on the submit event NOT the button click
$('form').on("submit", function(e) { // any form - use .formClass if necessary to specific forms
var empty = false;
$("input, textarea", this).each(function() { // this form's inputs incl submit
if ($.trim($(this).val()) == "") { // trim it too
console.log(this.name,"empty")
empty = true;
return false; // no need to continue
}
});
if (empty) {
alert(this.id + " is empty"); // or set a class on the div
e.preventDefault(); // cancel submission
}
});
});
div {
border: 1px solid black;
width:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input type="text" value="" name="field1" /><br/>
<textarea name="field2"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
<hr/>
<form id="form2">
<div>
<input type="text" value="" name="field3" /><br/>
<textarea name="field4"></textarea><br/>
<input type="submit" value="Submit" />
</div>
</form>
You could also add required to the fields
You need to restrain the handler to the form containing the clicked button:
$('#submit').click(function(e) {
var form = $(this).parents('form:first');
var empty = false;
$('input, textarea', form).each(function() {
// the rest is the same
I'd also like to point out that you cannot have the same ID on multiple controls, so
$('#submit')
should always return exactly one button. You should do something like this, where you distinguish the buttons by class instead:
<input type="submit" id="submitA" class="submitButton">
<input type="submit" id="submitB" class="submitButton">
and select with
$('.submitButton')
you know you can also use jquery to reset the form like so
form.resetForm();
Related
I have a form which gets submitted normally, now I have 2 requirement that needs to be completed on click of submit button, if these requirements are completed then the data needs to get saved in database
1) Border of the input boxes get highlighted if input boxes are left empty
2) If the image upload is left empty, a written message below the upload button should appear saying that the image is missing
3) The form should not get submitted till all input boxes and image upload are filled
4) Would also appreciate if someone could tell how I can use this code for all input boxes together instead of using separately for each one
Currently when I click on submit button, if the box is empty it highlights the input but after that submits the form also and the image message is also not appearing
Form Code
<form action="<?php echo base_url(); ?>profile/add_profile" method="post" >
<input id="user" type="text" />
<input id="pwd" type="text" />
<input type="file" class="form-control modalcontrol" name="profile_img" id="profile_img" required>
<span class="fileuploadlabl">Upload</span>
<div class="login-btn">
<button type="submit" class="btn btn-primary" name="submit" >SUBMIT</button>
</div>
</form>
Script Code
<script>
$( document ).ready(function() {
$(".login-btn").click(function(){
var user = $("#user").val();
var pwd = $("#pwd").val();
if(!user){
$("#user").addClass("makeRed");
}
else
{
$("#user").removeClass("makeRed");
}
if(!pwd){
$("#pwd").addClass("makeRed");
}
else
{
$("#pwd").removeClass("makeRed");
}
});
$("#user").click(function(){
$("#user").removeClass("makeRed");
});
$("#pwd").click(function(){
$("#pwd").removeClass("makeRed");
});
});
</script>
CSS Code
.makeRed{
border: 2px solid red !important;
}
You need to simply iterate all the inputs to validate them (comments inline)
$( document ).ready(function() {
$(".login-btn").click(function(){
$( "input, select" ).each( function(){ //iterate all inputs
var $this = $( this );
var value = $this.val();
$this.removeClass( "makeRed" ); //reset the class first
if ( value.length == 0 )
{
$this.addClass( "makeRed" ); //add if input is empty
}
});
});
$( "input,select" ).focus( function(){
$( this ).removeClass( "makeRed" ); //on focus of the input remove the markRed class
})
});
$(document).ready(function() {
$(".login-btn").click(function() {
$("input, select").each(function() { //iterate all inputs
var $this = $(this);
var value = $this.val();
$this.removeClass("makeRed"); //reset the class first
if (value.length == 0) {
$this.addClass("makeRed"); //add if input is empty
}
});
if ( $(".makeRed").length > 0 )
{
alert( "Some validation errors" );
}
});
$("input,select").focus(function() {
$(this).removeClass("makeRed"); //on focus of the input remove the markRed class
})
});
.makeRed
{
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="user" type="text" />
<input id="pwd" type="text" />
<input type="file" class="form-control modalcontrol" name="profile_img" id="profile_img" required>
<span class="fileuploadlabl">Upload</span>
<div class="login-btn">
<button type="submit" class="btn btn-primary" name="submit">SUBMIT</button>
</div>
</form>
$(document).ready(function(){
/**** When you click on input text element - remove class 'makered' -- Start *****/
$("form input").focus(function(){
$(this).removeClass('makeRed');
});
/**** When you click on input text element - remove class 'makered' -- Ends *****/
/**** While submit, if form is not valid, add error line and do not allow to submit, else allow submit -- Starts *****/
$("form").submit(function() { //validate on submit
var isError = false;
$(this).find('input').each(function(){
if(!($(this).val()))
{
$(this).addClass('makeRed');
isError = true;
}
else
$(this).removeClass('makeRed');
});
if(isError)
return false; // do not submit the form
});
/**** While submit, if form is not valid, add error line and do not allow to submit, else allow submit -- Ends *****/
And remove required attribute from input type file tag.
This will validate your form while submit, not while click, so the better solution instead of validating on click.
Here the code below disables search button when search box is empty. When input type for search button is set to submit then neither submit nor the enter key from keyboard submits empty form but when I change input type to button and put the cursor inside input field and press enter button even empty form is posted causing reloading of page. How to prevent submitting search form on pressing enter when search field is empty?
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
<script>
$(document).ready(function(){
$('.Button').attr('disabled',true);
$('.search').keyup(function(){
if($(this).val().length !=0)
$('.Button').attr('disabled', false);
else
$('.Button').attr('disabled',true);
})
});
</script>
Add a event listener for the form submission
$('form').submit(function(e){
// check logic here
if ($('.search').val().length < 1)
e.preventDefault()
});
where e.preventDefault will avoid the form being submitted if no value
otherwise the form will submitted normally
here is your code with some modification:
JsFiddle Demo
$(document).ready(function(){
// By default submit is disabled
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
if($(this).val().length !=0 ) {
$('.Button').prop('disabled', false);
} else {
$( ".search").focus();
$('.Button').prop('disabled', true);
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="search.php" method="post">
<input type="text" class="search" placeholder="search here"/>
<input type="submit" class="Button" value="search"/>
</form>
JsFiddle Demo
You can try like this
$('form').submit(function(e){
if ($('.search').val().length<=0)
return false;
});
you should use prop instead of attr if you want to change disabled
$(function() {
$('.Button').prop('disabled', true);
$('.search').keyup(function() {
$('.Button').prop('disabled', !$(this).val());
});
});
I'm new to javascript / jquery so I may be missing something obvious, but I've found solutions that disable the submit button until all text fields are filled, and I've found solutions that disable it until a file is chosen. However, my form consists of a file input and 3 text fields and I cannot find a way of it being disabled until all text fields AND a file is chosen.
The distilled version of the code I'm working with is here:
HTML
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
JS
$('.submit').click(function() {
var empty = $(this).parent().find("input").filter(function() {
return this.value === "";
});
if(empty.length) {
$('.submit').prop('disabled', false);
}
});
})()
Thanks for your help
https://jsfiddle.net/xG2KS/482/
Try capture the event on those field and checking the empty values by using another function, see below code :
$(':input').on('change keyup', function () {
// call the function after
// both change and keyup event trigger
var k = checking();
// if value inc not 0
if (k) $('.submit').prop('disabled', true);
// if value inc is 0
else $('.submit').prop('disabled', false);
});
// this function check for empty values
function checking() {
var inc = 0;
// capture all input except submit button
$(':input:not(:submit)').each(function () {
if ($(this).val() == "") inc++;
});
return inc;
}
This is just an example, but the logic somehow like that.
Update :
Event Delegation. You might need read this
// document -> can be replaced with nearest parent/container
// which is already exist on the page,
// something that hold dynamic data(in your case form input)
$(document).on('change keyup',':input', function (){..});
DEMO
Please see this fiddle https://jsfiddle.net/xG2KS/482/
$('input').on('change',function(){
var empty = $('div').find("input").filter(function() {
return this.value === "";
});
if(empty.length>0) {
$('.submit').prop('disabled', true);
}
else{
$('.submit').prop('disabled', false);
}
});
[1]:
The trick is
don’t disable the submit button; otherwise the user can’t click on it and testing won’t work
only when processing, only return true if all tests are satisfied
Here is a modified version of the HTML:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file"><br>
<input type="text" name="name"><br>
<input type="text" name="email"><br>
<button name="submit" type="submit">Upload</button>
</form>
and some pure JavaScript:
window.onload=init;
function init() {
var form=document.getElementById('test');
form.onsubmit=testSubmit;
function testSubmit() {
if(!form['file'].value) return false;
if(!form['name'].value) return false;
if(!form['email'].value) return false;
}
}
Note that I have removed all traces of XHTML in the HTML. That’s not necessary, of course, but HTML5 does allow a simpler version of the above, without JavaScript. Simply use the required attribute:
<form id="test" method="post" enctype="multipart/form-data" action="">
<input type="file" name="file" required><br>
<input type="text" name="name" required><br>
<input type="text" name="email" required><br>
<button name="submit" type="submit">Upload</button>
</form>
This prevents form submission if a required field is empty and works for all modern (not IE8) browsers.
Listen for the input event on file and text input elements, count number of unfilled inputs and, set the submit button's disabled property based on that number. Check out the demo below.
$(':text,:file').on('input', function() {
//find number of unfilled inputs
var n = $(':text,:file').filter(function() {
return this.value.trim().length == 0;
}).length;
//set disabled property of submit based on number
$('#submit').prop('disabled', n != 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="file" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="submit" value="Upload" class="submit" id="submit" disabled="disabled" />
</div>
For my approach, I'd rather use array to store if all the conditions are true. Then use every to make sure that all is true
$(function(){
function validateSubmit()
{
var result = [];
$('input[type=file], input[type=text]').each(function(){
if ($(this).val() == "")
result.push(false);
else
result.push(true);
});
return result;
}
$('input[type=file], input[type=text]').bind('change keyup', function(){
var res = validateSubmit().every(function(elem){
return elem == true;
});
if (res)
$('input[type=submit]').attr('disabled', false);
else
$('input[type=submit]').attr('disabled', true);
});
});
Fiddle
I have implemented a simple javascript validation but the validation and the form submission never happen together ...
When i use "onsubmit" (like below) it will goto the next page without validation
if i use "onclick" on the end of the form
<input type="button" name="submit" id="send" value="Search Flights" onclick="return validate_booking_form();" />
</form>
it will validate the input .. but the form wont be submitted even the correct input
This is the code i have used
//Javascript Validation
function validate_booking_form()
{
chk_fromcity();
chk_tocity();
chk_depature_date();
}
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
})
}
else
{
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
}
}
and the form
<form method="POST" action="../controller/booking.php" name="search_flights_names" onsubmit="return validate_booking_form();" >
/// Form content
<div class="form_input_container">
<div class="form_input">
<input type="text" id="from_cities" name="from_city" class="fieldInput" onblur="return chk_fromcity()" />
</div>
</div>
<input type="submit" name="submit" id="send" value="Search Flights" />
</form>
Submit is the proper button to use.
Try putton onsubmit in your form element and have the validation occur there instead of on the click event. That way pressing enter won't bypass all of your validation.
Try using Jquery validate. I think it should pretty much solve your problem
return false from chk_fromcity() to stop the form posting to action.
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
});
return false;
}
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
// return true; // default is true which is why you were passing the validation
}
I have 2 submit buttons in an HTML form.
How can I know which submit button has triggered the JavaScript function?
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
// I can't use onclick handler
// I can't use JQuery.. I want to do only with javascript
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1">
<input type="submit" value="submit2">
</form>
<button value="delete row" id="but1" onclick="disps()">delete row</button>
I want to do different actions based on the different submit buttons clicked.
It is not possible to check the button clicked through the onsubmit event. Instead move the call to verifyData() to the onclick handler of each button. Use return in the onclick call to cancel submission if false is returned by verifyData()
<script language="javascript" type="text/javascript">
function verifyData(button) {
// validate
switch (button.value) {
case "submit1":
// do somehting
break;
case "submit2":
// do somehting
break;
// ...
};
// submit the form
return true;
}
</script>
<form method="post">
<input type="submit" value="submit1" onclick="return verifyData(this);">
<input type="submit" value="submit2" onclick="return verifyData(this);">
</form>
How about putting an onclick event handler on both buttons which will set a variable to say which button was clicked?
like so:
<script language="javascript" type="text/javascript">
function verifyData(formdata) {
alert(btnClicked);
// Here I want to know from which submit button this function is triggered
// I can't use type button instead of submit
}
var btnClicked = 0;
function setSubmit(which) {
btnClicked = which; return true;
}
</script>
<form onsubmit="verifyData(this);" method="post">
<input type="submit" value="submit1" onclick="return setSubmit(1);">
<input type="submit" value="submit2" onclick="return setSubmit(2);">
</form>
Are you allowed to use the jQuery library?
If you can using this you can easily bind to each submit button based on an id.
For example:
<form id="form1" method="post">
<input type="submit" value="submit1" id="submit1">
<input type="submit" value="submit2" id="submit2" >
</form>
<script type="text/javascript">
$("#submit1").click(function(e)
{
// Do stuff when 1 is clicked.
$("#form1").submit();
});
$("#submit2").click(function(e)
{
// Do stuff when 2 is clicked.
$("#form1").submit();
});
</script>
you could also have the buttons as a type of button to avoid any issues, but you should be able to simply return false; to stop the button of type submit from... submitting
Here is how I would do it... Firstly I would use jQuery so you must include that in your document like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
It would also mean your HTML can be simplified to:
<form method="post">
<input type="submit" value="submit1"/>
<input type="submit" value="submit2"/>
</form>
Then you can use jQuery:
<script>
// When the document is ready
$(function(){
// Action performed when a submit button in the form is clicked
$("form[type='submit']").click(function(e){
// Get the value attribute
var val = $(this).val(),
validation_has_passed = false;
// If it is submit1
if(val == "submit1") {
// Validate submit 1
validation_has_passed = true;
// If it is submit2
} else if(val == "submit2") {
// Validate submit 2
validation_has_passed = true;
}
// If all validation is OK submit the form
if(validation_has_passed === true) {
$("form").submit();
}
// Ensure pressing these buttons doesn't submit the form
e.preventDefault();
});
});
</script>