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>
Related
With JS, I populate the form with a group of fields which I then either duplicate or remove.
As I duplicate the fields, my intention is to have the input values stored in an object.
When I click on the plus button, the fields duplicate, but the values entered disappear and the data is not captured.
JS
var html = `<div class="form-inline">
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Field Name" name="field_name">
</div>
<span>-</span>
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Field Type" name="field_type">
</div>
<span>-</span>
<div class="form-group">
<label class="sr-only" for="field-name">Field Name</label>
<input type="text" class="form-control" id="field-name" placeholder="Default value" name="field_default">
</div>
<div class="form-group">
<span class="btn btn-danger" data-role="remove">
<span class="glyphicon glyphicon-remove">-</span>
</span>
<span class="add_button btn btn-primary" data-role="add">
<span class="add_button glyphicon glyphicon-plus">+</span>
</span>
</div>
</div>`;
var crud_name = document.querySelector('.crud_name') // this is the first input box
var field_group = document.querySelector('.form-container')
// load the first group of fields to the DOM
field_group.innerHTML += html
var fields = []; // this will store all the database/crud fields
var plus_button = document.querySelector('.add_button')
/**
* The event is used when the user clicks on the plus button
* The event is on the form itself, but the target is the plus button
*/
plus_button.addEventListener('click', function(e) {
e.preventDefault()
if(e.target.classList.contains('add_button')) {
let inputs = e.target.parentElement.querySelectorAll('input')
var obj = {};
Array.from(inputs).forEach(input => {
obj[input.name]= input.value;
})
fields.push(obj);
console.log(fields);
field_group.innerHTML += html
// field_group.insertAdjacentHTML('beforeend', html)
}
})
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<form action="" method="post" id="crud_form">
<div class="form-group">
<input type="text" name="name" placeholder="Enter CRUD name. Eg: Task" class="crud_name form-control">
</div>
<div class="form-container"></div>
<button type="submit" class="btn btn-primary save_crud">Save</button>
</form>
How can I store the data each time I click to add the new group of inputs?
I tried to mimic this here
I'm not sure if i understand your question. If you don't want the inputs to disappear replace the last field_group.innerHTML += html by field_group.insertAdjacentHTML('beforeend', html).
Your button type is submit, so it submits the form when its clicked and the browser will refresh the page. Change the button type to type="button" and the form wont submit when you click the button. Then you can save the form input values to your javascript objects and add the new extra fields in to the page with javascript as well.
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>
Hi have a form which has two submit buttons:
(Button 2)The user clicks the submit button and a modal pop up appears and in the modal is some T&Cs they have to accept, (Button 1) once they click accept the second submit button does the form submission.
There are required form fields that don't show (required) once the first button is pressed just the modal pop up comes, How can I achieve this? My Jquery code is:
$(document).ready(function () {
$("#login-form button").click(function (ev) {
ev.preventDefault()
if ($(this).attr("value") == "button1") {
// alert("First Button is pressed")
$("#login-form").submit();
}
if ($(this).attr("value") == "button2") {
$(".modal").addClass("active");
}
});
});
The form field is:
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname>
Any ideas?
Here is a little code i wrote, i try to make it as dynamic as possible.
Instead of click you should have it onchange but its really upp to you.
make sure too look at validationType
$("input[type='button']").click(function(){
if ($(this).hasClass("disable"))
return false;
if ($(this).hasClass("validate")){
var errors = [];
// all required input that need validation
var input = $(this).parent().find("input[type='text'][required='required']");
input.each(function(){
var vType= $(this).attr("validationType");
var value =$(this).val();
var fName =$(this).attr("placeholder");
switch(vType){
case "notEmpty":
if (!value || value== "")
errors.push(fName +" cant be empty");
break;
}
});
if (errors.length>0){
$(this).parent().find(".submit").addClass("disable");
alert(errors)
}
else {
$(this).parent().find(".submit").removeClass("disable");
}
}else return true; // submit the form
});
input[required="required"]{
border:1px solid red;
}
.disable{
color:#CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" validationType="notEmpty" required="required" value="" placeholder="firstName" />
<input type="button" class="validate" value="button 1" />
<input type="button" class="submit disable" value="button 2" />
</form>
Ok this is how steps works on my own way .. The idea here is the first form is a main one and the second is a just for users not for programming .. This means the first form will have all the required fields and I will hide the fields and control it with javascript from the fake form
I create two forms one is a main and the second is a fake one
I add a hidden checkbox in a main form
I make separated submit events for each form
I made a change event for the fake checkbox to control the main checkbox in the main form
$(document).ready(function(){
// Main Form Submit
$("#mainForm").on("submit" , function(e){
e.preventDefault();
if($("#mainCheck").is(":checked")){
alert("First Form is Submitted correctly");
}else{
//alert('Show Modal With Form');
$("#fakeForm").show();
}
});
// Fake form in Modal submit
$("#fakeForm").on("submit" , function(e){
e.preventDefault();
if($("#fakeCheck").is(":checked")){
$("#mainForm").submit();
}else{
alert("Please Accept our policies first");
}
});
// fake checkbox to change main checkbox
$("#fakeCheck").on("change" , function(){
$("#mainCheck").prop("checked" , this.checked);
});
});
#mainForm, #fakeForm{
background : #eee;
border : 5px solid #555;
margin : 20px;
padding : 20px;
}
#mainCheckLabel,#fakeForm{
display : none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- first Form -->
<form id="mainForm">
<label class="form-label" for="firstname">First name:</label>
<input class="form-input" required type="text" name="firstname" id="firstname" value="firstname" />
<br/>
<label id="mainCheckLabel"><input type="checkbox" id="mainCheck"/>Accept to our policies</label>
<button type="submit">Submit First Form</button>
</form>
<!-- End First Form -->
<!-- Second Form in Modal -->
<form id="fakeForm">
<label id="fakeCheckLabel"><input type="checkbox" id="fakeCheck"/>Accept to our policies</label>
<button type="submit">Submit Second Form</button>
</form>
<!-- End Second Form in Modal -->
Note hide the #mainCheckLabel in the main form
Example of how to use [required] selector
$('input[required]').css('border' , '1px solid red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" required placeholder="First Name"/>
<input type="text" placeholder="Last Name"/>
Following solution works for me:
$("#uploadBtn").click(function() {
var form_data = new FormData($("#data-uploader-form")[0])
if ($("#data-uploader-form")[0].checkValidity()) {
alert("valid form")
} else {
alert("incorrect form")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='data-uploader-form' onsubmit='return false;'>
<div class="form-group row">
<label>Input field</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="testInputField" placeholder="some text" required="required">
</div>
</div>
<div class="form-group row">
<label class="col-12 col-lg-3 col-form-label"></label>
<div class="col-12 col-lg-6">
<button type="submit" class="btn btn-primary float-left" id="uploadBtn">Submit</button>
</div>
</div>
</form>
I have the following HTML code.
function document_save_changes(){
if (is_key_dirty == true){
var elm = document.getElementById('set_doc_button');
key_change_warning(elm, 'D');
return;
}
if (document_save_warning('A') == false){
return;
}
collect_nonkey_data();
do_recaptcha();
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" disabled="disabled" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>
My problem is that the "required" INPUT elements are not causing the form submission to fail when the INPUT elements are not filled properly. (For instance, by the type="email" INPUT element which requires special syntax.)
How do I make it so that the "required" INPUTs interrupt the form action if they are not filled in properly? Thanks.
This is because you're not submitting the form. Making a button at the last of type button doesn't make it a submit button. You'll have to specify the type='submit' explicitly to make a button submit the form.
And now to the second part,
If you're trying to submit the form from JS function. The HTML5 validation won't work.
Inshort they are only in action when form is submitted with a button of type submit inside that form. And if you do want to use a button of type button and submit the form with JS, you'll have to check for validation in your JS code.
And in your JS code you can use checkValidity() function on any form to check if it's a valid from or not and then run the other things accordingly
var form = document.getElementById("email_form");
function document_save_changes() {
//Do your things
if (form.checkValidity()) {
form.submit();
} else {
alert("Something worng yet")
}
}
<form id="email_form">
<div id="email_table" class="emltbl inbtop" style="margin:auto;">
<div class="emlrow">
<div class="emlcll">Name:</div>
<div class="emlcll"><input class="email_input" type="text" name="email_1" id="email_1" placeholder="First and last name" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Email:</div>
<div class="emlcll"><input class="email_input" type="email" name="email_2" id="email_2" placeholder="Return email address" required autocomplete="on" data-lpignore="true"/></div>
</div>
<div class="emlrow">
<div class="emlcll">Messg:</div>
<div class="emlcll"><textarea class="email_textarea" name="email_3" id="email_3" placeholder="Message to admin" required autocomplete="off"></textarea></div>
</div>
</div>
<div id="email_recaptcha" class="g-recaptcha" data-sitekey="key goes here"></div>
<div><button id="set_doc_button" type="button" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button></div>
</form>
try this one
Use button type='submit' instead of button
<button id="set_doc_button" type="submit" style="padding:0.3em 1em;" autocomplete="off" onclick="document_save_changes();" title="Submit changes to data">Submit Data</button>
and remove disabled="disabled" after that your form will submit
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');