I have a form with a series of radio items. If a user chooses a specific entry on one of the radio items (missing item) I use JQuery to add a bootstrap is-invalid class to two specific inputs on the form along with a label asking them to add detail and disable the submit button to stop them submitting the form.
$(function () {
$("input[name=optradio]:radio").click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
}
});
});
I would like to add further checks to make sure the user updates the two inputs (ones a textarea) before I re-enable the submit button.
I know I can use the following to check for input changes
$("textarea[name=sentTo]").on("input", function(){
$('textarea[name=sentTo]').removeClass('is-invalid');
});
This works fine. However I am at a loss how to integrate it all together:
So basically user selects the radio, is-invalid gets added to 2 input fields and the submit button disabled - user completes 2 fields as required and only when both fields have been updated do we then re-enable the submit button.
I am thinking I need an if statement but I can't seem to get the code right.
I tried
if `$("textarea[name=sentTo]").on("input") && $("textarea[name=dateSent]").on("input")`
but this doesnt work
Thanks to Mamum I am using the code below.
$(function () {
$('input[name=optradio]:radio').click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
$('#submit').addClass('btn-danger');
$('#submit').removeClass('btn-primary');
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
});
var sentTo = false;
var dateSent = false;
$("textarea[name=sentTo], input[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') {
sentTo = true;
$(this).removeClass('is-invalid');
}
if($(this).attr('name') == 'dateSent') {
dateSent = true;
$(this).removeClass('is-invalid');
}
if(sentTo && dateSent){
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
You can pass multiple selector separated by comma and use this keyword to refer the current element inside the event handler function:
var sentTo = dateSent = false;
$("textarea[name=sentTo], textarea[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') sentTo = true; //true for sentTo
if($(this).attr('name') == 'dateSent') dateSent = true;//true for dateSent
if(sentTo && dateSent){ // if both are true
$(this).removeClass('is-invalid');
sentTo = dateSent = false;
}
});
Related
I have a form which consists of some elements such as a select-input and a checkbox.
The submit-button is disabled and I want to enable the button only if two conditions are fulfilled. An initial version works well, but only if clicking on the checkbox is the last step. But it should be a function that reacts on both, clicks/changes in the select and the checkbox.
The following code is working but with the problem explained above.
$('#toscheck').click(function() {
if ($(this).is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
The following solution doesn't work:
$('document').ready(function() {
if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
But how can I solve this? What I have found on SO wasn't really helpful.
Again: it should work as following; if the checkbox is selected AND the selected option has a value, the button would be enabled.
Thanks in advance.
First, store you element in variables:
let $toscheck = $('#toscheck'),
$ctry = $("#ctry"),
$pjo = $('#pjo'),
$sjo = $('#sjo');
Then, create your validation function with the stored variables. Note that I replace attr and removeAttr with .prop, it is better:
function checkThings(){
if ($toscheck.is(':checked') && $ctry.val().length > 0) {
$pjo.prop('disabled', false);
$sjo.prop('disabled', false);
} else {
$pjo.prop('disabled', true);
$sjo.prop('disabled', true);
}
}
Then, bind the events:
$toscheck.add($ctry).on( 'change', checkThings );
Note that I used change on both elements since it does work with inputs and checkboxes.
Final code :
let $toscheck = $('#toscheck'),
$ctry = $("#ctry"),
$pjo = $('#pjo'),
$sjo = $('#sjo');
function checkThings(){
if ($toscheck.is(':checked') && $ctry.val().length > 0) {
$pjo.prop('disabled', false);
$sjo.prop('disabled', false);
} else {
$pjo.prop('disabled', true);
$sjo.prop('disabled', true);
}
}
$toscheck.add($ctry).on( 'change', checkThings );
$(document).ready(function() {
$('#toscheck,#ctry').change(function() {
if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
});
use this code
.change function detects change and then on call check whether your AND condition is met or not
and add #toscheck in quotes i.e. '#toscheck'
$('#toscheck,#xyz,#abc').change()
for detecting change for multiple elements
In registration form I have a 2 radio button, when one button is selected a dropdown list appears. But after register fails, the selected radio button remains but the dropdown list is not shown anymore, I want the dropdown list to be shown after register fail. There should be a solution with local storage but I dont know exactly how to write it.
here is the code, what I should add to make it happen?
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
});
});
So I found the solution finally, I tried and made it :
<script>
$(document).ready(function() {
$('input[type=radio][name=rdUserType]').change(function() {
if (this.value == '1') {
$('#cityClient').show();
$('#cityLawyer').hide();
}
else if (this.value == '0') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
localStorage.removeItem("last");
});
});
function fix(){
var check = localStorage.getItem("last");
console.log(check);
if (check === 'a') {
$('#cityClient').hide();
$('#cityLawyer').show();
}
else{
$('#cityClient').show();
$('#cityLawyer').hide();
}
}
function save(){
// rdAttorney is a id of the selected radio
if (document.getElementById('rdAttorney').checked) {
localStorage.setItem('last', 'a');
}
else{
localStorage.setItem('last', 'b');
}
}
window.onload = fix();
</script>
I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields
I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY
I doing a field validation using jquery to check if it is empty. If it is I want to display a message and then refocus on the field so the user can enter some data. Code:
$('#fieldId').blur(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
$(this).focus();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
It sort of works but it moves the cursor to the next field and not the one I refocused on.
You can try this:
$('#fieldId').blur(function(evt) {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId')
.text('You must enter a value in this field')
.show();
this.focus();
evt.preventDefault();
}
else {
if ($(this).is('.error')) {
$(this.removeClass('error');
$('#errorDivId').hide()
}
}
});
However that may not completely solve the problem, as some browsers might be confused. As an alternative, wrap your "focus" call up as a timeout and run it after the current event finishes:
var self = this;
setTimeout(function() { self.focus(); }, 1);
It's kind-of a hack but it should also work.
edit — #Gus is right about which "focus()" to call
The blur event is triggered during a focus change (as the control you are validating loses focus). This could cause weird behaviour if you try to alter the focus while it is already changing. Instead of blur, try attaching the validation to the change event.
Also, there's no need to call the jQuery version of focus: $(this).focus(), you can just call this.focus().
$('#fieldId').change(function() {
var fieldValue = $(this).val();
if(fieldValue == null || fieldValue.length == 0) {
$(this).addClass('error');
// show error message
$('#errorDivId').text('You must enter a value in this field').show();
this.focus();
} else {
if ($(this).is('.error')) {
$(this).removeClass('error');
$('#errorDivId').hide()
}
}
});