I've made a little demonstration of my problem here: http://jsfiddle.net/nt3Z3/
I'm using Bootstrap v3.1 and jQuery v1.11 and in my contact form I have ~5 inputs and ~1 textarea:
<fieldset>
<div class="form-group"> <!-- Only Posting one for size purposes -->
<label for="nameBox" class="col-lg-2 control-label">Name</label>
<div id="nameGroup" class="col-lg-10">
<input type="text" id="nameBox" class="form-control" placeholder="John Smith" required="" />
</div>
</div>
<div class="form-group">
<label for="messageBox" class="col-lg-2 control-label">Message</label>
<div id="messageGroup" class="col-lg-10">
<textarea id="messageBox" class="form-control" placeholder="Your content here" required="" rows="3"></textarea>
</div>
</div>
<button type="submit" id="submitButton" class="btn btn-primary center-block">Submit</button>
</fieldset>
In my js file I have something along the lines of:
$("#submitButton").click(function () {
var name = $.trim($("#nameBox").val());
if ($("input, textarea").val() == "") {
$(this).parent().addClass("has-error");
}
});
I've imported jquery's latest straight from Google's API.
So, back to the problem. When I click the submit button with nothing in the text boxes the fieldset gets the class has-error when only the div nameGroup (and so on) should have. I've attempted to remove the $.trim to see if that was the problem and that did no success.
What my final output should be when I press the submit button and no text is in any of the inputs should look like
<fieldset>
<div class="form-group">
<label>Name</label>
<div id="nameGroup" class="col-lg-10 has-error">
<input type="text" />
</div>
</fieldset>
But with the current js I have above, I get this
<fieldset class="has-error"> <!-- go away has-error -->
<div class="form-group">
<label>Name</label>
<div id="nameGroup" class="col-lg-10 has-error">
<input type="text" />
</div>
</fieldset>
Am I doing something wrong? Overlooking something? Is there an easy way to have the fieldset not acquire the has-error class without saying $("fieldset").removeClass("has-error"); or without putting $("#nameGroup").addClass("has-error"); for each group?
This code:
if ($("input, textarea").val() == "") {
$(this).parent().addClass("has-error");
}
Puts the class on the parent of #submitButton (since it's in a click handler on #submitButton). It also only checks the value of the first input or textarea on the page (not the others).
If you want it on, say, the parent of each individual input or text box, then:
$("input, textarea").each(function() {
if (!$.trim(this.value)) {
$(this).parent().addClass("has-error");
}
});
or if you like
$("input, textarea").each(function() {
var $this = $(this);
if (!$.trim($this.val())) {
$this.parent().addClass("has-error");
}
});
The buttons' parent is the fieldset. Not the form-group.
If you want to target the form-group you can do this:
.parent().find('.form-group');
Related
I have a form to submit several fields. Two of them are for changing a password.
These password fields aren't required to be filled out before submitting. However, if one of them isn't blank I add the required attribute to both fields when it's changed through jQuery. I remove the attributes when I empty one and the other is already empty too.
The thing it seems to work the most of the times with an exception:
I fill out password
password2 is blank
I submit the form
In this case the validation for password2 shows up, but if I want to remove everything and submit, I can't:
I remove password
I submit the form again
The validation for password2 shows up again. Even if the 'required' attributed is removed in the HTML source
This is the HTML code:
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
And the jQuery code:
$('#password').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$( '#password2' ).attr('required', true);
}else{
if($('#password2').val() == ''){
$(this).removeAttr('required');
$( '#password2' ).removeAttr('required');
}
}
});
$('#password2').change(function() {
if($(this).val() != ''){
$(this).attr('required', true);
$('#password').attr('required', true);
}else{
if($('#password').val() == ''){
$(this).removeAttr('required');
$('#password').removeAttr('required');
}
}
});
And it's an example in JSFiddle:
https://jsfiddle.net/jke3pgh0/
I will suggest you a different approach here...
First, you only need one handler for this, since the logic is the same for both inputs. You can use more than one selector... Ex: $('#password, #password2'). But I would use a class instead... Like $(".password"). It's up to you.
Second, I said the «logic is the same»... That is:
If one of the two inputs is not empty, both are required.
So having the same change event handler on both inputs mean you don't really know which one triggered the event. So I suggest to use an .each() loop here (to make sure you check all values)... and a boolean "flag" (true/false).
After that loop, use that "flag" to set the required attribute.
I used a CSS rule to make the result obvious in the snippet below.
$('#password, #password2').change(function(){
// Look up for the password inputs in that "row".
var pass_inputs = $(this).closest(".row").find("[type='password']");
// Flag to determine if at least one is not empty.
var not_empty = false;
// Loop throug the password inputs and change the flag.
pass_inputs.each(function(){
if($(this).val() != ''){
not_empty = true
}
});
// Use the flag as the boolean argument for the required attribute.
pass_inputs.attr('required', not_empty);
});
[required]{
border: 3px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="edicionPerfilForm" action="actor/edit.do" method="post">
<div class="row">
<div class="form-group col-md-4">
<div>
<label for="password">Password</label>
<input id="password" name="password" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
<br>
</div>
</div>
<div class="form-group col-md-4">
<div>
<label for="password2">Repeat password</label>
<input id="password2" name="password2" class="form-control" type="password" value="" oninvalid="this.setCustomValidity('Fill out this field')" oninput="this.setCustomValidity('')">
</div>
</div>
</div>
<button name="save" type="submit" class="btn btn-dark">Send</button>
</form>
I want to do a validation registration form. How to display the error of the input empty in a span at the bottom of the input?
I want this span to not already exist and be created to display the message.
enter code here
<form action="" name="reg-form" method="post">
<div id="name-box" onblur="validateFullname()" class="form-holder">
<input type="text" name="name" placeholder="enter name" id="name" class="form-control">
</div>
i want create a span element and display message after input or append to div.
The solution will look something like this:
Identify where the "Error Message" span will appear. It needs to be inside another element, even if that element is the body. My example contains: <div id="ErrMsg"></div>
You need an event that triggers both the validation, and the creation of the error span. Usually, that event is a button press. So let's go with that in this example:
$('#mybutt').click(function(){
var tmpL = $('#login').val();
var tmpP = $('#pword').val();
if( tmpL=='' || tmpP=='' ){
$('#ErrMsg').html('<span>Please fill-out all fields</span>');
}else{
alert('Logging in now');
}
});
$('input').on('keyup', function(){
if ( $('#ErrMsg span').length ) $('#ErrMsg span').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="LoginDIV">
<div id="LName">
Login: <input id="login" type="text" />
</div>
<div id="LPass">
Pword: <input id="pword" type="password" />
</div>
<div id="ErrMsg"></div>
<div id="btnDIV"><button id="mybutt">Login</button></div>
</div>
Note: the <script> tag that references the jQuery library is all that you need in order to use jQuery. jQuery just makes javascript easier, more consistent, and less-typing-required.
Your best bet is probably to use JQuery Validation. It's built-in methods don't technically use a span, as you specified, but you could easily tack on your own function to un-hide the custom span you create. Or, better yet, just style their error-message <label> in the way you prefer.
Here's an example using just JQuery Validation:
<form action="/" method="post" id="commentForm">
<div class="form-holder">
<input type="text" name="username" placeholder="username" class="form-control">
</div>
<div class="form-holder col-12">
<input type="email" name="email" placeholder="email" class="form-control">
</div>
</form>
<script>
var validator = $("#commentForm").validate();
validator.showErrors({
"email": "Please enter a valid email address"
});
</script>
(The example leaves out the includes for JQuery and JQuery Validation.)
function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function() {
checkValid(); // run it for the first time
$(".fakeRadio").on("change", checkValid); // bind checkbox
$("#email-download-document").on("change", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" />
</div>
</div>
I would like to get your help because I have a little issue with my simple Javascript part and Chrome Browser.
With Chrome, my button is greyed out until I click outside of the field when this one is filled. I would like to enable my button when the field is automatically filled with email verification thanks to type='email'.
This is an example :
Try with input event instead of change.
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
function checkValid() {
var cbChecked = $(".fakeRadio").is(":checked"); // check if checked
var hasText = $("#email-download-document").val().length > 0; // check if it has text
$("#document-choice-button").prop("disabled", !cbChecked || !hasText);
}
$(function () {
checkValid(); // run it for the first time
$(".fakeRadio").on("input", checkValid); // bind checkbox
$("#email-download-document").on("input", checkValid) // bind textbox
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Fake Radio</label>
<input type="radio" class="fakeRadio" checked>
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument"
placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected"
value="Send to my email"/>
</div>
</div>
Try to use 'input' event instead of 'change' event in your Javascript, to trigger the function when the user is typing into the field.
Have your HTML button by default disabled
<input id="document-choice-button" type="submit" ... disabled="disabled" />
This way, it will load disabled without any javascript.
Then, attach a function to keyup event of your textbox to check if the length of the current text is greater than zero.
$("#email-download-document").keyup(function(){ // triggered at any keystroke
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled"); // enable the field
} else {
$("#document-choice-button").prop("disabled","disabled"); // disable the field
}
});
PS: This will make the button enabled/disabled as you are typing or clearing text from the textfield. If you would like to only disable/re-enable after you have exited the textfield, then you will need to attach the function to the change event
$("#email-download-document").change(function(){ //triggered after leaving textbox
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
$("#email-download-document").keyup(function(){
if ($(this).val().length>0) {
$("#document-choice-button").removeProp("disabled");
} else {
$("#document-choice-button").prop("disabled","disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="row">
<div class=" col-md-5">
<label for="primary">Email address</label>
<input type="email" class="form-control" id="email-download-document" name="EmailDownloadDocument" placeholder="Enter email address to get document(s)">
</div>
</div>
<br>
<div class="row">
<div class=" col-md-5">
<input id="document-choice-button" type="submit" class="btn btn-default" name="DocumentSelected" value="{% trans 'Send to my email' %}" disabled="disabled" />
</div>
</div>
Being directly, I'm working on a project that have a filter button, but one of the requirements is to keep the parameters from the filter forms if the user refreshs the page.
The problem is: When I refresh the page with values into the form, just the DATE input resets
I have three forms, and the last is a Date. I managed to make it work for the first two with jQuery but with the date field it just does not work ...
Does anyone know how to solve it? thank you!
$(document).ready(function() {
if (document.getElementById("car_result"))
document.getElementById("car_result").value = localStorage.getItem("item_result");
if (document.getElementById("car_action"))
document.getElementById("car_action").value = localStorage.getItem("item_action");
if (document.getElementById("dei"))
document.getElementById("dei").value = localStorage.getItem("item_dei");
});
$(window).on('beforeunload', function() {
localStorage.setItem("item_result", document.getElementById("car_result").value);
localStorage.setItem("item_action", document.getElementById("car_action").value);
localStorage.setItem("item_dei", document.getElementById("dei").value);
});
<div class="container-fuid">
<div class="row col-sm-12">
<div class="col-sm-6">
<form class="form text-center" id="form1">
Result: <input id="car_result" type="text" class="form-control"><br>
Last name: <input id="car_action" type="text" class="form-control">
<input placeholder="Initial date" class="textbox-n form-control borderform" type="text" onfocus="(this.type='date')" name="dei" id="dei" /><br><br>
<button>Filter</button>
</form>
</div>
</div>
</div>
The section below should only appear if the user selects the "Yes" option. This section (id="co-op") is embedded inside of a long Form. All of the inputs within the section are required (using HTML5 "Required" attribute). However if the user selects "No" the section below doesn't display within the form. This means that I would like to disable the "Required" fields within the section when the user selects "No"; since they can't view the inputs. Currently they are still submitting and preventing a successful submission.
Thanks!
<section id="co-app">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="fullName">Co-Applican'ts Information</label>
<input type="text" class="form-control" name="firstName" placeholder="First Name" required>
</div><!--/form-gp-->
</div><!--/col-md-4-->
<div class="col-md-1">
<div class="form-group">
<input type="text" class="form-control" name="middleName" placeholder="M.I." maxlength="1" id="middle-name" required>
</div><!--/form-gp-->
</div><!--/col-md-1-->
<div class="col-md-3">
<div class="form-group">
<input type="text" class="form-control" id="last-name" placeholder="Last Name" required>
</div><!--/form-gp-->
</div><!--/col-md-1-->
</div><!--/row-->
</div><!--/container-->
</section><!--/co-app-->
Using the jquery validation engine plugin I was able to use the following jquery to toggle the hidden elements when selected and remove the "required" attribute when not selected.
$(document).ready(function() {
$("#retired-select-coapp, #retired-select-primary ").change(handleNewSelection);
// Run the event handler once now to ensure everything is as it should be
handleNewSelection.apply($("#retired-select-coapp, #retired-select-primary"));
/** Step One Co-App Info **/
$('#co-app').hide();
$(".app-choice").change(function () { //use change event
if (this.value == "option2") {
$('#co-app').stop(true,true).slideDown('1000'); //than show
$('#co-app input,#co-app select').addClass('validate[required]');
} else {
$('#co-app').stop(true,true).slideUp('1000'); //else hide
$('#co-app input, #co-app select').removeClass('validate[required]');
}
});