How to keep an element state unchanged forcefully - javascript

I have a form which behaves normally, with the inputs validated by simple validation. We installed a plugin, which provides some in-depth validation.
The issue arises when the plugin disables the submit button if it's validation fails on the elements it's watching.
How can I keep the submit on active state at all time without making any modification to the plugin files. However, I will have control on the page itself, so I can alter anything.
A simple JSFiddle I created to illustrate the situation:
JSFiddle
HTML
<form action="#" id="form">
Name: <input type="text" id="name" class="form-field">
<span class='error-message'>Name is required</span><br>
Age: <input type="text" id="age" class="form-field">
<span class='error-message'>Age is required</span><br>
Password: <input type="password" id="pass" class="adv-form-field">
<span class='error-message'>Advanced messages</span>
<button id="submit">Submit</button>
</form>
CSS
.error-message{
display: none;
}
JavaScript (jQuery)
// Simple validation to check if the fields have values
$(".form-field").on("blur", function(){
if(this.value == ""){
$(this).next(".error-message").css("display", "block");
} else {
$(this).next(".error-message").css("display", "none");
}
});
// Suppose this is the advanced function | we will have no control over this
$("#submit").prop("disabled", true);
$(".adv-form-field").on("blur", function(){
if(this.value == ""){
$(this).next(".error-message").css("display", "block");
$("#submit").prop("disabled", true);
} else {
$(this).next(".error-message").css("display", "none");
$("#submit").prop("disabled", false);
}
});

You can add your own event handlers after the plugin has initialised, and these will effectively override (not actually override) the plugin event handlers...
If you add this it will run on document.ready...
$(function() {
// set submit button enabled after input field blur
$(".adv-form-field").on("blur", function() {
$("#submit").prop("disabled", false);
});
// set initial state of submit button
$("#submit").prop("disabled", false);
});

I don't know which plugin you are using, but from my previous experience with form validation plugins instead of typing <button id="submit">Submit</button> use:
<input type="submit" id="submit">

Related

Toggle visibility of buttons on forgotten required form fields

I have several forms on my profile page. Each form has its own submit button. When a user clicks the submit button, I want the button to disappear and show a spinner.
That works fine. The issue that I am running into, is that if the user forgets to fill-out a required field, the button does not return visible. The spinner stays visible. And the page would have to be reloaded.
Jquery is not intercepting the form submission (though I am open to that if it will fix the issue), it is only toggling the spinner and button visibility.
Any help?
$("#profile-loading").hide();
$("#social-loading").hide();
$(document).ready(function () {
$("#btn_profile").on("click", function (e) {
$("#profile-loading").show();
$("#btn_profile").hide();
checkForm('#formProfile', "#btn_profile", "#profile-loading");
});
$("#btn_social").on("click", function (e) {
$("#social-loading").show();
$("#btn_social").hide();
checkForm('#formSocialMedia', "#btn_social", "#social-loading");
});
});
//Check the passed in form and toggle the buttons and the loading spinner
function checkForm($formid, $buttonid, $spinnerid) {
var emptyFields = $('#formProfile .required').filter(function () {
return $(this).val() === "";
}).length;
if (emptyFields === 0) {
console.log("no emptyFields");
} else {
console.log("emptyFields");
return false;
}
//I tried looping through each form field, but can't seem to get the form targeted.
// $($formid + '.required').each(function () {
// console.log("checkForm");
//
// var self = $(this)
// if (self.val() === '') {
// // empty
// console.log("empty");
// } else {
// // not empty
// console.log("NOT empty");
// }
// });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="somelink" id="formProfile">
<input id="name" name="name" type="text" required="required">
<input id="url" name="url" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="profile-loading"></i>
<button id="btn_profile" type="submit">Save Changes</button>
</form>
<form method="post" action="someotherlink" id="formSocialMedia>
<input id="facebook" name="facebook" type="text" required="required">
<input id="instagram" name="instagram" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="social-loading"></i>
<button id="btn_social" type="submit">Save Changes</button>
</form>
There are several issues with your code, but the most important one is that you are retrieving required form elements using a required class, which does not seem to be used in your html. Instead, you can retrieve required form elements using something like
$('#formProfile [required]')
which returns all subelements of formProfile which have the required attribute. You have another issue in that the id of the form is hard-coded. Instead of hard-coding it, use the variable $formid.
$($formid + ' [required]')
Try reordering your scripts, do validation first and check if it's pass. Make sure the checkForm returns true if valid.
$("#btn_profile").on("click", function (e) {
if (checkForm('#formProfile', "#btn_profile", "#profile-loading")) {
$("#profile-loading").show();
$("#btn_profile").hide();
}
});
$("#btn_social").on("click", function (e) {
if (checkForm('#formSocialMedia', "#btn_social", "#social-loading")) {
$("#social-loading").show();
$("#btn_social").hide();
}
});

Bootstrap jQuery - Issues with empty field validation

I've written some jQuery to validate my Bootstrap forms, however I'm having a few issues.
Firstly, I want a red outline to appear if the user clicks off the input field without typing anything in: JSFiddle example here. In this example I'm using the Bootstrap Validator plugin, however I want to imitate this effect without using the plugin.
Second, and linked to the issue I just mentioned, the green outline only appears once the user clicks the submit button, thus the user only sees it for half a second or so before they are redirected, making it a little pointless. Again, this would be solved by having an error/success outline appear once the user clicks off the input. If anyone could help me out it would be greatly appreciated.
This is the code I have so far:
HTML:
<form id="auth_form" action="action.php" method="post">
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<label for="auth_code" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input" name="auth_code_input" type="password">
<span class="form-control-feedback glyphicon" id="iconBad"></span>
</div>
<div class="form-group">
<div>
<button class="btn btn-info" name="submit" type="submit" id="submit">Submit</button>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#auth_form').on('submit', function(e) {
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
e.preventDefault();
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
}
})
})
JSFiddle
Try this updated fiddle: jsfiddle.net/xqwsobmo/20/
Need to add input blur event and validate input
$(document).ready(function() {
$('#auth_code_input').blur(function(){
if(!ValidateInput()){
e.preventDefault();
}
});
$('#auth_form').on('submit', function(e) {
if(!ValidateInput()){
e.preventDefault();
}
})
});
function ValidateInput(){
var IsValid=false;
var auth_code = $('#auth_code_input').val()
if (auth_code=="") {
$('#auth_code').addClass('has-error');
$('#iconBad').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid=false;
} else {
$('#auth_code').removeClass('has-error').addClass('has-success');
$('#iconBad').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid=true;
}
return IsValid;
}

removing validators on an element using jquery

I have the below html drill down control which is generated at run time..And i want to disable all the validations on it.
<label class="mark" for="SupportTo_L1" id="SupportTo_L1_Label">select a value </label>
<select aria-labelledby="SupportTo_L1_Label SupportTo_L1_Error" aria-required="true"
class="op-combobox" data-ishorizontal="true" data-drilldowntype="true"
data-register-change-event="true" data-val="true"
data-val-required="<img class='validateicon'
src='https://sxsvc.supp.maro.com/PAdvy0.0.0/Content/Images/16x16-red-alert.png'/><font color='Red'>*</font> Required"
id="SupportTo_L1"
name="SupportTo_L1" title="Technology group involved in the project:">
<button class="submitbutton" id="submit" name="submit" type="submit"
value="submit">Submit</button>
But still it fires a validation on the this drill down when i clicked on the submit button.I tried the below code which didn't work.Anything else i need to disable.
$('#SupportTo_L1').attr(
{'data-val':'false','aria-required':'false'}
);
I have done it like that,
document.getElementById("elemenId").required = false;
I would try this:
$('#SupportTo_L1').removeAttr('data-val');
$('#SupportTo_L1').removeAttr('aria-required');
$("#submit").click (function (e) {
e.preventDefault();
$("select.op-combobox").attr("data-val","false");
$("select.op-combobox").attr("aria-required","false");
});

jQuery Validate doesn't remove error if value is auto-inputted via JavaScript

My HTML looks like this:
<form id="mainform" method="post">
<input type="text" class="required" name="receiver" />
<span id="clickMe">Click me</span>
<input type="submit">
</form>
And my JavaScript is as follows:
$(document).ready(function () {
$("#clickMe").click(function() {
$("input[name=receiver]").val("Clicked");
});
$("#mainform").validate({
submitHandler: function (form) {
alert("Success!");
return false;
}
});
});
Fiddle: http://jsfiddle.net/Y9RFt/2/
If you submit leaving the input empty, an error appears.
If you click the 'Click Me' span, the input is auto-filled, but the error remains until you submit the form. If you type something instead, the error disappears instantly.
Is there a way to emulate user input so that the error disappears on click?
Simply use the built-in .valid() method to force an immediate validation test of the form.
$("#clickMe").click(function () {
$("input[name=receiver]").val("Clicked");
$("#mainform").valid(); // <<-- Add this line to force a test
});
DEMO: http://jsfiddle.net/Y9RFt/8/
Got it. The solution is to simply blur the input:
$("input[name=receiver]").val("Clicked").blur();
Fiddle: http://jsfiddle.net/Y9RFt/7/

Fairly easy JQuery Input Selection location problem

I am having a problem with getting my JQuery javascript code to apply to the select box elements that it is supposed to. What's happening is that the select boxes are not following the actions that are specified in the javascript code. They are simply staying disabled and checked (see code below) instead of changing based on the first checkbox's selection.
I believe it is a problem regarding how I specify the location of the select boxes in the javascript code, but I don't know how to go about fixing it. Then again, I could be wrong about that too.
If you have any insight on this or can correct the code, please do! Cheers.
HTML:
<div class="medium_box">
<form name="searchform" class="FECKsearch" method="get" onSubmit="return dosearch();">
<input name="s" id="searchBox" class="input" type="text" value="" onfocus="myFocusHandler(this);" onblur="myBlurHandler(this);" size="18" maxlength="50">
<input type="submit" name="searchsubmit" class="button" value="Go" />
<span class="searcher">International: <input type="checkbox" id="International" checked="yes"></input></span>
<span class="searcher1">Americas: <input type="checkbox" id="Americas" disabled checked="yes"></input></span>
<span class="searcher1">Europe: <input type="checkbox" id="Europe" disabled checked="yes"></input></span>
Asia: <input type="checkbox" id="Asia" disabled checked="yes"></input>
</form>
</div>
Javascript:
$('#International').click(function() {
var paramChangeBoxes = $('input:checkbox');
if ($(this).is(':checked')) {
$('#Americas').attr('checked', 'checked');
$('#Americas').attr('disabled', 'disabled');
$('#Europe').attr('checked', 'checked');
$('#Europe').attr('disabled', 'disabled');
$('#Asia').attr('checked', 'checked');
$('#Asia').attr('disabled', 'disabled');
}
else {
paramChangeBoxes.removeAttr('disabled');
$('#Americas').removeAttr('disabled');
$('#Europe').removeAttr('disabled');
$('#Asia').removeAttr('disabled');
}
});
Update & Solution:
Cheers to John for the code $('#International').live("click",function() { which corrected the error of the JQuery code not functioning. Apparently if you are importing the code from a remote file you must include the "live" portion inside of your coding.
Thanks again John!
$('#International').live("click",function() {
var paramChangeBoxes = $('input:checkbox');
if ($(this).is(':checked')) {
$('#Americas').attr('checked', 'checked');
$('#Americas').attr('disabled', 'disabled');
$('#Europe').attr('checked', 'checked');
$('#Europe').attr('disabled', 'disabled');
$('#Asia').attr('checked', 'checked');
$('#Asia').attr('disabled', 'disabled');
}
else {
paramChangeBoxes.removeAttr('disabled');
$('#Americas').removeAttr('disabled');
$('#Europe').removeAttr('disabled');
$('#Asia').removeAttr('disabled');
}
});
For Dynamic content (includes and element dom creation after page load) use live.
Have a nice day
There's a lot of room for tightening the following code up, but it works:
$('#International').click(function() {
var paramChangeBoxes = $('input:checkbox');
if ($(this).is(':checked')) {
if (!$('#Americas').is(':checked')) {
$('#Americas').click();
}
$('#Americas').attr('disabled', 'disabled');
if (!$('#Europe').is(':checked')) {
$('#Europe').click();
}
$('#Europe').attr('disabled', 'disabled');
if (!$('#Asia').is(':checked')) {
$('#Asia').click();
}
$('#Asia').attr('disabled', 'disabled');
} else {
paramChangeBoxes.removeAttr('disabled');
$('#Americas').removeAttr('disabled');
$('#Europe').removeAttr('disabled');
$('#Asia').removeAttr('disabled');
}
});

Categories