Form input attributes based on other inputs - javascript

Below I have been trying to get the eoddesc field to be required depending on whether the completetasks value is Yes or No. I made a quick script which executes upon click of the submit button. As of now, it can remove the required property from the eoddesc input, but if the value is changed back to Yes, then it stays without a required attribute.
<form action="/addeod" method="POST" id="addEODForm">
<div class="modal-body">
<div class="row">
<div class="col-8 mt-4">
<label for="completetasks">Did I complete all my tasks that were due today and/or overdue?</label>
</div>
<div class="col-4 mb-3">
<select class="browser-default custom-select" id="completetasks" name="success" style="margin-top: 30px;" required>
<option value="" selected>Yes/No:</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</div>
</div>
<div class="row">
<div class="col-12 mb-2">
<div class="md-form">
<textarea id="eoddesc" class="form-control md-textarea" name="ifno" length="120" rows="3" required></textarea>
<label for="eoddesc">If not, please explain why:</label>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<div class="md-form">
<textarea id="eodsum" class="form-control md-textarea" name="summary" length="120" rows="3" required></textarea>
<label for="eodsum">Briefly summarize all you've completed today:</label>
</div>
</div>
</div>
</div>
<div class="modal-footer d-block">
<div class="row w-100">
<div class="col-sm-6 col-12 "><a type="button" class="btn btn-outline-info waves-effect w-100" data-dismiss="modal">Close</a></div>
<div id="eodSumButton" class="col-sm-6 col-12"><button type="submit" class="btn btn-info waves-effect waves-light w-100">Submit</button></div>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#eodSumButton").click(function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
</script>
Why does the form not update with the required field? When I console.log it, everything outputs as expected, but it does not want to update the attr.

You just need to change the event listener for your completetasks input instead of eodSumButton. Otherwise the code only checks that when you try to submit:
$(document).ready(function(){
$("#completetasks").on('change',function () {
if ($("#completetasks").val() == "Yes"){
console.log("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
console.log("required");
$("#eoddesc").attr("required");
}
})
});
The problem is that the "required" is evaluated before the submit. So when you press submit, it sees the field as "not required" and then it adds the attribute required.
EDIT:
I think I figured out your problem:
$(document).ready(function(){
$("#completetasks").click(function () {
if ($("#completetasks").val() == "Yes"){
$("#output").html("NOT required");
$("#eoddesc").removeAttr("required");
}
if ($("#completetasks").val() == "No"){
$("#output").html("required");
$("#eoddesc").prop("required",true);
}
})
});
When using "attributes" like required and checked, Jquery considers them a property, so to add "required" use .prop. But to remove, you still use removeAttr.
I hope this fixes your problem.
Fixed, the comment of Bharat Geleda is the true correct answer.

Related

How to disable a button if all of the inputs is empty in asp.net core

I'm trying to submit a form. I have a binding dropdown list and an input field. The dropdown list has three input fields. 0 = pending, 1 = accepted, and 2 = denied. I want to store data if the dropdown value is not 0/pending. If the dropdown is changed/ not pending or the comment input field have not empty, then the Save button enables. Otherwise, the save button is disabled.
function success() {
if (document.getElementById("textsend").value === "") {
document.getElementById('button').disabled = true;
} else {
document.getElementById('button').disabled = false;
}
}
<div class="row border-top pt-2">
<div class="col-md-4">
<span>Decision</span><span asp-validation-for="Heating.Status"></span>
<select asp-for="Heating.Status" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control">
<option></option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span>Comments</span><span></span>
<textarea class="form-control " id="textsend" onkeyup="success()" style="height:100px" maxlength="2000"></textarea>
</div>
</div>
<div class="row border-top p-2">
<div class="col">
<input type="submit" id="button" value="Save" class="btn btn-blueTwo float-right" disabled />
</div>
</div>
But I can't use the dropdown list to add these conditions. Couldn't you please help me?
Finally, I solved this problem.
<script>
$(document).ready(function () {
$('.save-btn').attr('disabled', true);
$('#CommentResponse').change(function () {
let cmtData = $("#CommentResponse").val();
if (cmtData !=null ) {
$('.save-btn').attr('disabled', false);
}
if(cmtData == "")
{
$('.save-btn').attr('disabled', true);
}
})
$('#StatusResponse').change(function () {
let statusData= $(this).val();
if (statusData != 0) {
$('.save-btn').attr('disabled', false);
}
else
{
$('.save-btn').attr('disabled', true);
}
})
});
</script>
<div class="row border-top pt-2">
<div class="col-md-4">
<span>Decision</span><span asp-validation-for="BurnOut.Status"></span>
<select asp-for="BurnOut.Status" id="StatusResponse" asp-items="Html.GetEnumSelectList<ApplicationDecision>()" class="form-control ">
<option></option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<span>Comments</span><span asp-validation-for="BurnOut.Remarks"></span>
<textarea class="form-control " id="CommentResponse" asp-for="BurnOut.Remarks" style="height:100px" maxlength="2000"></textarea>
</div>
</div>
<div class="row border-top p-2">
<div class="col">
<input type="submit" value="Save" class="btn btn-blueTwo float-right save-btn" />
</div>
</div>

Bootstrap validation with JavaScript - disable submission with invalid fields

I have the following HTML code:
<form class="row g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">First name</label>
<input type="text" class="form-control" id="validationCustom01" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustom02" class="form-label">Last name</label>
<input type="text" class="form-control" id="validationCustom02" value="Otto" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Username</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="text" class="form-control" id="validationCustomUsername" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
<div class="col-md-6">
<label for="validationCustom03" class="form-label">City</label>
<input type="text" class="form-control" id="validationCustom03" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom04" class="form-label">State</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>...</option>
</select>
<div class="invalid-feedback">
Please select a valid state.
</div>
</div>
<div class="col-md-3">
<label for="validationCustom05" class="form-label">Zip</label>
<input type="text" class="form-control" id="validationCustom05" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
<div class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<div class="col-12">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</form>
With the following JavaScript code, to validate the user input. If there are any invalid fields, it should the user stop submitting his request:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict'
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.querySelectorAll('.needs-validation')
// Loop over them and prevent submission
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated')
// putting alert here does not work..?
// something like alert('successfully validated your request!')
}, false)
})
})()
The problem is: I want to alert the user, if the submission was successfully, with the alert() function. But I can't figure out where to put the alert function. I marked the code where I tried putting the alert function into, but it's always triggering even when it's not even validated. Does somebody know what am I doing wrong here? Thank you very much.

jQuery on click not performing actions as expected

I've faced a very weird issue today. I'm using below HTML code for a login form and I am using below JS to make sure that it performs operations as expected.
$('body').on('click', '.account__login-form-button', function() {
$('form#login input').each(function() {
if (isBlank($(this).val())) {
proceed = false;
toastr.error('Login credentials cannot be left blank.', 'Please Enter Login Details!', {
closeButton: !0,
showMethod: 'slideDown',
hideMethod: 'slideUp',
preventDuplicates: true,
positionClass: 'toast-bottom-right'
});
} else
proceed = true;
});
if (proceed) {
var buttonText = $('.account__login-form-button').text();
var username = $('.account__login-form-username').val();
var password = $('.account__login-form-password').val();
$('[class^=account__login-form-]').attr('disabled', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="login">
<div class="form-group text-center text-success col-md-offset-4 col-md-4" style="cursor: pointer;">
<span id="create_account">
Don't have an account? Click here to create one!
</span>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="text" class="form-control account__login-form-username" name="account_login" placeholder="Username / Mobile / Email-ID">
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="password" class="form-control account__login-form-password" name="account_login" placeholder="Enter Password">
<div class="pull-right" style="cursor: pointer;">
<span id="for-pass" name="account_login">
Forgot password?
</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<button name="account_login" class="btn btn-block btn-primary account__login-form-button">Login Now!</button>
</div>
</div>
For some reasons I don't know what the click event is not being triggered, I also saw if there is an error in the console but nothing there as well.
I even tried changing the class name but same also I'm using this code $( '[class^=account__login-form-]' ).attr( 'disabled', true ); as a direct inject from developers tool console to check if it works or not it does not work there as well. I'm working for a long time on JS but never encountered this weird issue.
A couple tiny mistakes...
There is no <form> element in your HTML. You only have a Bootstrap .form-group class used.
You should declare the proceed variable before the .each() loop.
After the loop, test the proceed value... Not inside.
To disable the inputs, use the *= (contains) operator instead of ^= (starts with)... Because the account__login-form-___ class is not always the first class in the class attribute.
And I changed the condition to test if an input is empty... isBlank() seems to be an excel function... Unless you coded it yourself.
$('body').on('click', '.account__login-form-button', function() {
// Add this here
var proceed = true
// There is no <form> element in your HTML.
$('#login input').each(function() {
if ($(this).val().trim() === "") {
proceed = false;
toastr.error('Login credentials cannot be left blank.', 'Please Enter Login Details!', {
closeButton: !0,
showMethod: 'slideDown',
hideMethod: 'slideUp',
preventDuplicates: true,
positionClass: 'toast-bottom-right'
});
}
}); // END each loop
// AFTER the each loop, test the "proceed" value
console.log("proceed", proceed)
if (proceed) {
var buttonText = $('.account__login-form-button').text();
var username = $('.account__login-form-username').val();
var password = $('.account__login-form-password').val();
console.log(buttonText, username, password)
$('[class*=account__login-form-]').attr('disabled', true);
console.log("inputs are now disabled")
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>
<div id="login">
<div class="form-group text-center text-success col-md-offset-4 col-md-4" style="cursor: pointer;">
<span id="create_account">
Don't have an account? Click here to create one!
</span>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="text" class="form-control account__login-form-username" name="account_login" placeholder="Username / Mobile / Email-ID">
</div>
<div class="form-group col-md-offset-4 col-md-4">
<input type="password" class="form-control account__login-form-password" name="account_login" placeholder="Enter Password">
<div class="pull-right" style="cursor: pointer;">
<span id="for-pass" name="account_login">
Forgot password?
</span>
</div>
<div class="clearfix"></div>
</div>
<div class="form-group col-md-offset-4 col-md-4">
<button name="account_login" class="btn btn-block btn-primary account__login-form-button">Login Now!</button>
</div>
</div>

How to check whether all the other div contains a particular class on input events?

I have html generated dynamically through code and it is rendered in browser like:
<div class="required">
<label class="col-sm-3 control-label text-danger">Contact Details</label>
<div id="dynamic-contact-details" class="col-sm-4">
<div id="count0" class="space form-group has-error"><div class="col-sm-4">
<select id="contact-type0" class="form-control"><option value="">Select</option><option value="Phone">Phone</option><option value="Whatapp">Whatapp</option><option value="Facebook">Facebook</option><option value="Web">Web</option><option value="Fax">Fax</option></select>
<small id="contact-type0" class="text-danger">Contact Type is Required</small>
</div>
<div class="col-sm-7">
<input type="text" name="contact-type-value0" id="contact-type-value0" class="form-control">
<small id="contact-type-value0" class="text-danger">Contact Type Value is Required</small>
</div>
<button value="count0" class="remove_field btn btn-danger"><i class="fa fa-trash"></i></button>
</div>
<div id="count1" class="space form-group has-error"><div class="error">
<div class="col-sm-4">
<select id="contact-type1" class="form-control"><option value="">Select</option><option value="Phone">Phone</option><option value="Whatapp">Whatapp</option><option value="Facebook">Facebook</option><option value="Web">Web</option><option value="Fax">Fax</option></select>
<small id="contact-type1" class="text-danger">Contact Type is Required</small>
</div><div class="col-sm-7">
<input type="text" name="contact-type-value1" id="contact-type-value1" class="form-control">
<small id="contact-type-value1" class="text-danger">Contact Type Value is Required</small>
</div>
<button value="count1" class="remove_field btn btn-danger"><i class="fa fa-trash"></i></button>
</div></div>
<div id="count2" class="space form-group has-error"><div
....
</div>
</div>
</div>
Note that that has-error class is appended to the div when the corresponding inputs are kept blank and clicked on save buttons. The has-error classes are removed from the div when the input is filled. Now I want to remove class text-danger from label only when all the div inside dynamic-contact-details does not contain has-error classes.
I have tried below lines of code but it does not work.
$('#dynamic-contact-details').on('change', ':input', function() {
$(this).closest(".form-group").removeClass("has-error");
$(this).next('small').addClass('hide');
if($(this).find('div.has-error').length == 0)
{
$(this).closest(".form-group").parent().parent().find(".control-label").removeClass("text-danger");
}
});
Please help me in finding better way to do it.
You need to check the length for the has-error class inside the element that has id as dynamic-contact-details so you need to change the if condition something like this:
$('#dynamic-contact-details').on('change', ':input', function() {
$(this).closest(".form-group").removeClass("has-error");
$(this).next('small').addClass('hide');
if($('#dynamic-contact-details').find('.has-error').length == 0)
{
$(this).closest(".form-group").parent().parent().find(".control-label").removeClass("text-danger");
}
});
Now I want to remove class text-danger from label only when all the div inside dynamic-contact-details does not contains has-error classes.
You can simply count how many .has-error classes. If such a value is 0 you can remove:
if ($('#dynamic-contact-details').find('.has-error').length == 0) {
$('#dynamic-contact-details').find(".control-label").removeClass("text-danger");
}

The submit button is not getting enabled even after every field is filled

https://jsfiddle.net/xrxjoaqe/
I don't know what's wrong with the bootstrap inline validation files... Even after entering all the values, the submit button is not getting enabled.
$('#registerbutton').attr('disabled', 'disabled');
function updateFormEnabled() {
if (verifyAdSettings()) {
$('#registerbutton').attr('disabled', '');
} else {
$('#registerbutton').attr('disabled', 'disabled');
}
}
function verifyAdSettings() {
if ($('#b2b_service_type').val() != '') {
return true;
} else {
return false
}
}
$('#b2b_service_type').change(updateFormEnabled);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form accept-charset="UTF-8" method="post" role="form" id="bookform" data-toggle="validator" enctype="multipart/form-data">
<div class="form-group col-md-6 col-xs-6 has-feedback" style="padding:5px">
<input id="b2b_customer_name" name="b2b_customer_name" class="form-control input-lg headerform" type="text" required placeholder="Your Name *" pattern="^[_A-z\s]{3,}$" data-error="Please enter atleast 3 alphabets">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-md-6 col-xs-6 has-feedback" style="padding:5px">
<input id="b2b_cust_phone" name="b2b_cust_phone" type="tel" class="form-control input-lg headerform" type="tel" maxlength="10" placeholder="Mobile Number. *" pattern="^[789]\d{9}$" data-error="Please enter a valid mobile number" required>
<p class="help-block with-errors"></p>
</div>
<div class="form-group col-md-6 col-xs-6 has-feedback" style="padding:5px">
<select id="b2b_service_type" name="b2b_service_type" class="form-control input-lg headerform status" required>
<option value="" disabled="" selected="" hidden="">Service Type</option>
<option value="22">something</option>
<option value="34">Another</option>
</select>
<p class="help-block with-errors"></p>
</div>
<button id="registerbutton" type="submit" class="btn btn-xl submit" disabled>Submit</button>
</div>
<!-- Book div -->
Please be sure & finish all your edits before posting a question. Try this out. This will help you!
<button id="registerbutton" type="submit" class="btn btn-xl submit" disabled="disabled">Submit</button>
Use removeAttr
function updateFormEnabled() {
if (verifyAdSettings()) {
$('#registerbutton').removeAttr('disabled');
} else {
$('#registerbutton').attr('disabled', 'disabled');
}
}
From the fiddle / code provided, it appears you are trying to:
enable the submit button when the combo changes
The fiddle doesn't work as you've not included jquery in the javascript options and the one you've included (via script src) is not being loaded as it's not https (always check the browser console window - it shows an http error and '$ is not defined'.
Fixing the jquery link (either of the two) still doesn't let it work, because you've used attr
Change this to prop
$('#registerbutton').prop('disabled', 'disabled');
function updateFormEnabled() {
if (verifyAdSettings()) {
$('#registerbutton').prop('disabled', '');
} else {
$('#registerbutton').prop('disabled', 'disabled');
}
}
Updated fiddle: https://jsfiddle.net/xrxjoaqe/4/

Categories

Resources