Ive been looking but cant seem to find much clarification...
I am creating a form -
If a user is to select an option for contact "email",
the user must enter a text value for email input type.
Here is a fiddle- https://jsfiddle.net/4s3bLf65/
if ($("input[name='option']").val()=='email') &&($("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
I cant seem to figure out the proper syntax for the js...
Any suggestions?
Try that way:
if ($("input[name='option']:checked").val()=='email' && $("input[name='email1']").val() == '')
{
alert('Enter email');
return false;
}
Add your code to a click handler or submit handler so it executes when the button is pressed.
Your if had too many perentheses
You were not getting the value of the :checked box.
$(document).ready(function() {
$('input[name="btn_submit"]').click(function() {
if ($("input[name='option']:checked").val() == 'email' && $("input[name='email1']").val() == '') {
alert('Enter email');
return false;
}
});
});
Fiddle: https://jsfiddle.net/ojqa46a0/
Related
It seems I'm having issues understanding exactly how form submission works...
Here is my event listener for submitting the from:
function createEventListeners() {
var orderForm = document.getElementsByTagName("form")[0];
if (orderForm.addEventListener) {
orderForm.addEventListener("submit", validateForm, false);
}//end if
else if (orderForm.attachEvent) {
orderForm.attachEvent("onsubmit", validateForm);
}//end else
}//end function createEventListeners()
Here is the code for validating the form:
function validateForm(evt){
var valid = true;
if (testLength(document.expReport.lname) == false){
valid = false;
}
if (testLength(document.expReport.fname) == false){
valid = false;
}
if (testLength(document.expReport.summary) == false){
valid = false;
}
if (testLength(document.expReport.init) == false){
valid = false;
}
//Call the testPattern() function with the department field for the field parameter.
if (testPattern(document.expReport.deptID, /DEPT\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the account field object for the field parameter.
if (testPattern(document.expReport.accID, /ACT\d\d\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function with the project field for the field parameter.
if (testPattern(document.expReport.projID, /PROJ-..-\d\d\d\d/) == false){
valid = false;
}
//Call the testPattern() function for the ssn field
if ((testPattern(document.expReport.ssn, /\d\d\d\d\d\d\d\d\d/) || testPattern(document.expReport.ssn, /\d\d\d-\d\d-\d\d\d\d/)) == false){
valid = false
}
if (testDates() == false){
valid = false;
}
if (valid == false){
window.alert("Please fill out all required fields in the proper format.")
}
return valid;
}//end function validateForm(evt)
My issues is that even though the validate function is returning a false value the form submission still takes place.
I've done research on how to prevent this from being the case but it seems that most people just use the .preventDefaults() method to get around this. My issue is that the form that I'm working with contains text fields that are optional, thus if the user chooses to not fill them out, he will still be presented with a false return.
Is there an issue with how I'm setting up the listener for submission?
I've also tried to look up what can be done with the evt parameter but there is nothing there that is explaining why it refuses to function as intended.
The problem is that you're ultimately not doing anything with the validation result.
Your function validateForm will be getting invoked when the event fires, and it's probably working fine, but its return value goes nowhere.
Without seeing the whole page it's not possible to say what change you should make, but hopefully this is enough to shed light on what's needed so you can fix it.
I have a form, after submitting form when button is clicked using jQuery like this.
function validate(){
if($('#firstname').val() =="")
alert("Please enter your first name");
else if($('#lastname').val() == "")
alert("Please enter your last name");
else if( $('#association').val() == "")
alert("Choose your association");
else if($('#association_no').val() == "")
alert("Please enter your association number");
else
$('#register').submit();
}
$(function(){
$(".enter_submit").keyup(function(event) {
if(event.keyCode === 13)
validate();
})
})
The alert box is displaying fine but my issue that When I press enter after alert box is displayed, it gives another alert box instead of getting rid of the alert(Works fine when I click OK with mouse). In FF, it gives #prevent more alerts from this page. So I believe its still focusing on the form even after alert is displayed.
Specify return False after the alert box is displayed. This might not show other alert box at the same time.
function validate() {
if ($('#firstname').val() == "") {
alert("Please enter your first name");
return false;
}
else if ($('#lastname').val() == "") {
alert("Please enter your last name");
return false;
}
else if ($('#association').val() == "") {
alert("Choose your association");
return false;
}
else if ($('#association_no').val() == "") {
alert("Please enter your association number");
return false;
}
else {
$('#register').submit();
return true;
}
}
$(function () {
$(".enter_submit").keyup(function (event) {
if (event.keyCode === 13)
return validate();
});
});
Hope this help
Thanks
Prashant
I fixed this using blur function
$(".enter_submit").keyup(function(event) {
$(this).blur();
if(event.keyCode === 13)
return validate();
})
I figured that the text field was still on focus even when the alert was being displayed so had to take it out of focus i.e, blur it. Thanks to everyone who replied.
I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.
I have the following code to put helper text in a search input box that is removed when you click in the box and returned if you click anywhere else without changing it:
$('#search-form input[type="text"]').each(function(){
var defaultVal = 'Category Search';
$(this).focus(function(){
if ($(this).val() == defaultVal){
$(this).removeClass('active').val('').css('color', '#000');;
}
})
.blur(function(){
if ($(this).val() == ''){
$(this).addClass('active').val(defaultVal).css('color', '#CCC');
}
})
.blur().addClass('active');
});
But if the user clicks submit without clicking in the input box, the site will search for the helper value (Category Search).
What I need to do is on submit check the value and if it's Category Search then do the following things:
Change helper text to Please enter a category
Don't submit the form.
I tried this but it stopped my default value (Category Search) from working all together:
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search")
//do stuff here
});
jsBin demo
var defaultVal = 'Category Search';
var enterCat = 'Please enter a category';
$('#search-form input[type="text"]').each(function(){
$(this).focus(function(){
if ($(this).val() == defaultVal || $(this).val() == enterCat){
$(this).removeClass('active').val('').css('color', '#000');
}
})
.blur(function(){
if ($.trim($(this).val()) === ''){
$(this).addClass('active').val(defaultVal).css('color', '#CCC');
}
})
.blur().addClass('active');
});
$('#search-form').submit(function(e) {
if ( $(this).find('[type="text"]').val() === defaultVal){
e.preventDefault();
$(this).find('[type="text"]').prop('value', enterCat);
}
});
and use also $.trim() (whitespaces) before searching for blank inputs :)
HTML5 placeholder is what you should use for browsers that support it, there would be no code to write to remove it.
For browsers that do not support it, there are plenty of plugins that make it work.
And why do you not just ignore the default value on the server? Seems like a logical place to filter it out.
The reason why your code fails is this is the submit button, not the form fields!
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search") <-- this is the submit button, not the input
//do stuff here
});
You need to change it to point to the inputs
$('#search-form').on("submit",function() {
$('#search-form input[type="text"]').each( function() {
//do comparison here, you could use defaultValue attribute
} );
});
I agree on using placeholder, but this is the answer to your question:
$('#search-form input[type="submit"]').click(function() {
if ($('#search-form input[type="text"]') == "Category Search")
$('#search-form input[type="text"]').val("Please enter a category");
return false;
});
I, personally, would create an error box near to the search field rather than change the text already in it - otherwise you're going to have problems with people submitting 'please enter a category'...
You are trying to get the .val() of the submit button
$('#search-form input[type="submit"]').click(function() {
if ($('#search-form input[type="text"]').val() == "Category Search")
//do stuff here
});
but you should probably hook it to submit event of the form itself, but that would depend on how your implementation actually works.
$('#search-form').submit(function() {
if ($('#search-form input[type="text"]').val() == "Category Search")
//do stuff here
});
If you can't use the placeholder (and you really should if you can), then you could simply set the field to disabled:
$('#search-form input[type="submit"]').click(function() {
if ($(this).val() == "Category Search") {
$(this).prop('disabled',true);
}
});
The disabled attribute essentially guarantees that the field is 'not successful', and thus won't be submitted to the server.
A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.
However:
Controls that are disabled cannot be successful...
Citation: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2.
Much simpler: Most new browsers will allow this:
<input type="text" placeholder="your prompt here" />
But for older browsers you can do this:
$(function() {
if ($.browser.msie) {
$('#search-form input[type="text"]').each(function(){
$(this).val($(this).attr("placeholder"));
});
}
$("#search-form").on("submit",function() {
var cnt=0,empty++;
$("#search-form input[type='text']").each(function(){
var box = $(this),val = box.val();
if (val == box.attr("placeholder")){
box.val("");
}
else {
box.val($.trim(val));
}
if (box.val()=="") empty++;
cnt++;
});
if (empty==cnt) return false;
});
});
I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!
the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.
$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length