Need help preventing form submission if element is not checked - javascript

I wrote a small script the prevents the form from being submitted if an input field (checkbox or radio) has not been selected. The script only targets the input field with the attribute "required". However since my form varies from page to page (depending on what link the user selects) not all options required.
The form that I am including the jquery script is on one form since it is dynamic.
I have wrote the script below which does the job
$('#item_form').submit(function() {
var ok = $('input[id*=\"required\"]').is(':checked');
$('#error').toggle(!ok);
$('html, body').animate({scrollTop: 0,scrollLeft: 300}, 500);
return ok;
});
});
But the challenge that I am facing having it work only if there is a required attribute. I have wrote the following code below but it doesn't seem to be working for me. Here is what I wrote
$.fn.exists = function () {
return this.length !== 0;
}
$('#item_form').submit(function() {
var req = $('input[id*=\"required\"]');
if(req.exists()){
var ok = req.is(':checked');
$('#error').toggle(!ok);
$('html, body').animate({scrollTop: 0,scrollLeft: 300}, 500);
return ok;
}
});
});
Can anyone please help me figure this one out? Thanks!

You can try to check if the selector input[id*="required"]:not(:checked) returns with length "0", that will be true either if all required are checked, and also if there's no required on the page:
$('#item_form').submit(function() {
var ok = $('input[id*=\"required\"]:not(:checked)').length == 0;
$('#error').toggle(!ok);
$('html, body').animate({scrollTop: 0,scrollLeft: 300}, 500);
return ok;
});

It isn't entirely clear what your validation requirements are but if you are trying to target required attribute you can use an attribute selector'
For example on a single checkbox:
<input type="checkbox" required/>
var ok = $(':checkbox[required]').is(':checked');
Would need to see more html and have better explanation of your needs to improve this
See API Docs for has-attribute selector

Simple solution...
$('#item_form').submit(function () {
if ($(this).find('input.required').length > 0) {
alert('oops, a field is required'); // this is where you'd put your loop to make sure each required field is filled
} else {
alert('form is good to go');
}
});
Note though that you can only have one instance of an ID on a page, so use class="required" instead of id="required".

Related

Validate a SELECT against another SELECT PHP JQuery

Within my form there are 2 SELECT Options. I'm looking to check the values of both, to check that they match.
This below is my jquery, when the code runs, I deliberatly have different values in the SELECT options and the form will just carry onto the next page without flagging up the error that they don't match.
<script type="text/javascript">
$(document).ready(function () {
jquery(function(){
$("leadgenform2").click(function(){
$(".error").hide();
var hasError = false;
var exppagesval = $("#exppages").val();
var pagesseenval = $("#pagesseen").val();
if (exppagesval != pagesseenval) {
$("#pagesseen").after('<div class="alert alert-success display-hide"><button class="close" data-close="alert"></button>Pages Seen & Expected Pages do not match!</div>');
hasError = true;
}
if(hasError == true) {return false;}
});
});
});
</script>
What have I missed?
Not sure why formatting has gone a miss. sorry!
hey $("leadgenform2") is invalid selector either make it a class or id(preferred) and use like
$(".leadgenform2") for class.
$("#leadgenform2") for id.
$("leadgenform2") is not a valid selector. assuming it is an ID, so you should use $("#leadgenform2").
Just from a first glance... you seem to have an error on line1:
jquey(function(){
should be
jquery(function(){
And you are missing $(document).ready(function(){ .... );
Without this, click event will not fire.

Have weird issue with input in ascensor script

Hey I have weird problem with the script ascensor.js
You can watch in my site :
www.emantiss.com
Look down page into the contact form. I can't write anything.
I've tried to delete the script and than it back to work.
Anyone have any idea how to fix that problem? with the script I just cant type inside the inputs and the textarea.
thanks.
This is the script code:
$('#masallery').ascensor({direction:"x",
time: 800,
overflow: 'hidden',
windowsOn: 0
});
This is the input code:
$('input, textarea').attr("data-placeholdertext", function() {
return this.value;
});
$('#form')
.delegate('input, textarea', 'focus', function() {
$(this).removeClass("formde").addClass("formde-click");
if (this.value === $(this).attr("data-placeholdertext")) {
this.value = '';
}
})
.delegate('input, textarea', 'blur', function() {
$(this).removeClass("formde-click").addClass("formde");
if (this.value.length == 0) {
this.value = $(this).attr("data-placeholdertext");
}
});
If I delete the first code, It is works.
When I enable the script, I can't type anything.
I think your problem is that you try to validate fields on every keyup.
You should try to remove it from java.js
line 110
this.uname.on("keyup", this.isVaildName);
this.email.on("keyup", this.isVaildEmail);
this.cmsg.on("keyup",this.isVaildMsg);
Any way form validates on submit
Edit
Yep previos suggest was wrong, sorry was unmindful.
I think I have found now where there is a problem.
Ascensor bind itself to all keydown events.
On line 146 it return "!1" if event comes from input/textarea.
!1 is false so it prevent default browser action (placing symbol to field).
If you change "!1" to "true" it should start work well.
Edit2:
Or you can disable key navigation feature.
$('#masallery').ascensor({direction:"x",
time: 800,
overflow: 'hidden',
windowsOn: 0
keyNavigation: false,
});
It should work too.

Check validation with id's and assign custom errors

(I am not using Jquery Validation)
I'm trying to return custom errors if the field is incorrect or empty. For instance, if the #id_first_name field is null. Append the string, " first name" to p#error to result in :
Please fill in your first name
I've made a fiddle here to show what I mean. So in the list of required fields... How would I be able to grab / check each individual required id and assign the corrosponding error?
Thank you for your help in advance!
You're fiddle should be as basic as possible, removing all other information, but you could try something like this,
$('form').on('submit',function(){
$('input').each(function(){
$this = $(this);
if($this.val() == 'null')
{
$('p#error').append('Please enter your ' + $this.attr('placeholder'));
}
}
});
You could do something like below
$('form input').on('blur', function() {
var id = $(this).attr('id');
var val = $(this).val();
if(id == 'myInput') {
if(!val.length) {
$('#error').append('Please enter a value into the input');
}
}
});
This is a simple way of doing form validation, just tailor the example to your needs.
EDIT
If you want it to work in your example it would be better to have a div with the id of error and append p tags with the corresponding error values.
Happy coding :)

Disable Form submit button if text field filled in

I am trying to implement some Jquery that basically says "If this text field is filled in then disable the submit button so that the form cannot be delivered/submitted"
So far I have come up with this, but it is not working
$(document).ready(function(){
$this = $("#inputValue");
if($this.val().length>0){
$('input[type=submit]').attr('disabled', 'disabled');
}
});
When i fill in the form and include text within the field I am not supposed to the form still gets submitted, what am i doing wrong?
Thanks
Your code only runs once on runtime. After that, it doesn't get checked again.
$(document).ready(function (){
$("#inputValue").on('change', function (){
if($(this).val().length > 0){
$('input[type=submit]').attr('disabled', 'disabled');
} else {
$('input[type=submit]').removeAttr('disabled');
}
});
});
Or, as #thomasfedb suggested:
$(document).ready(function (){
$('#inputValue').on('change', function() {
$("input[type=submit]").prop('disabled', $(this).val().length > 0);
});
});
I'd suggest you to bind a keyup event to do the check every time when user enters something to #inputValue field:
$(document).ready(function() {
$("#inputValue").on("keyup", function() {
$("input[type=submit]").prop("disabled", !!$.trim(this.value).length);
}).trigger("keyup");
});
Since you're using a hidden field it might be better to bind the change event:
$('#inputValue').on('change', function() {
$('input[type="submit"]').prop('disabled', this.value.length > 0);
}).change();
Try using this code.
$('input[type=submit]').attr("disabled", true);

Clearing a text input (if it's empty) when another text box is clicked - jQuery

I have an email text box that contains the text '(Not Required)' until a user clicks on it, at which point it turns blank. I'm trying to make it to where if the user clicks another text box without entering an email address (or entering anything), the text box will revert to containing (Not Required).
Here's what I have:
$(document).ready(function () {
$('#email').val("(Not Required)");
// this part works fine
$('#email').click(function(){
if ($(this).val() == '(Not Required)'){
$(this).val('');
}
});
// this isn't working
$(':text').click(function(){
var em = $('#email').val().length();
if (em<3){
$('#email').val('(Not Required)');
}
});
});
I can't figure out why the second part isn't working correctly. Any help would be rewarded with a lifetime's devotion to yourself from myself in a very big way. Forever.
var em = $('#email').text().length();
Should be
var em = $('#email').val().length;
And I show you a better way do this by chain method:
$(document).ready(function () {
$('#email').val("(Not Required)").foucs(function() {
$(this).val('');
}).blur(function() {
if ($(this).val().length < 3 ){
$(this).val('(Not Required)');
}
});
});
You have to use $('#email').val().length instead of $('#email').text().length()
Change
$('#email').text().length();
to
$('#email').val().length;
And just a suggestion, why not use the blur() event of the email input to return the 'Not Required' text instead of waiting for a click on another input box?
click isn't the event you should catch. focus is the one to go. never forget keyboard navigation.
Don't query the DOM twice, save the DOM element and work with it.
use val() instead of text and length instead od length()
:text isn't a good selector. it implies the global selector $('*')
$(document).ready(function () {
var $email = $('#email');
$email.val("(Not Required)");
// this part works fine
$email.focus(function(){
if (this.value == '(Not Required)'){
this.value ='';
}
});
$('#otherTextBoxId').focus(function(){
if ($email.val().length <3 ){
$email.val('(Not Required)');
}
});
});

Categories