Unable to make text box exist when checkbox checked - javascript

When i select value 6 then check box exists. When i checked the box then there should appear the text box but when i click on check box the text box is not existing. I tried jQuery and html code. Everything works perfect except existing the textbox.
$(document).ready(function() {
$('#education').on('change', function() {
if ($(this).val() == "6") {
$('#checkBox').show(); //text box exists
} else {
$('#checkBox').hide();
}
if ($('#checkBox').is(":checked")) {
$("#txtData").show();
} else {
$("#txtData").hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 col-md-1">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-4"><br />
</label>
<div class="col-md-3">
<input type="checkbox" id="checkBox">
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-3">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8"><br />
</label>
<div class="col-md-9">
<input type="text" class="form-control" id="txtData" style="display: none;">
</div>
</div>
</div>
</div>

If you want your textbox to appear when you change the value of the checkBox, then you need to put the event listener on the checkBox element.
I did this and it works fine.
$(document).ready(function() {
$('#checkBox').on('change', function() {
if ($(this).val() == "6") {
$('#checkBox').show(); //text box exists
} else {
$('#checkBox').hide();
}
if ($('#checkBox').is(":checked")) {
$("#txtData").show();
} else {
$("#txtData").hide();
}
});
});
Here is a codepen where this works : https://codepen.io/shyrro/pen/PagvMK

I tried it on my own. I got a solution. I written separate function to exist textbox.
<script>
$(document).ready(
function() {
$('#education').on(
'change',
function() {
if ($(this).val() == "6") {
$('#checkBox').show(); //check box exists
} else {
$('#checkBox').hide(); //check box exists
}
});
});
$('#checkBox').on(
'change',
function() {
if ($('#checkBox').is(":checked")) {
$("#txtData").show();
} else {
$("#txtData").hide();
}
});
</script>

Related

Unable to hide and show fields with select

I am trying to show and hide fields with respective selected value from tag. But it is not working. This same code is working perfectly in my other site. But it is not working here, don't know which thing i am missing. Here is the code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 col-sm-12 col-lg-12">
<label>Product Type <sup>*</sup></label>
<div class="select-wrp">
<script>
$('select')
.change(function () {
if ($(this).val() === 'single') {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
})
.change();
</script>
<select name="product_type">
<option value="single">Single</option>
<option value="multiple">Multiple</option>
</select>
</div>
</div>
<div class="col-md-12 col-sm-12 col-lg-12">
<input class="single" name="single" type="text" placeholder="100" />
<input class="multiple" name="multiple" type="text" placeholder="100" />
</div>
Your script needs to be told to wait for the window to be loaded first. You can use jQuery to do this by simply adding $(() => { ... }) around your existing script:
$(() => {
$('select').change(function () {
if ($(this).val() === "single") {
$('.single').show();
$('.multiple').hide();
} else {
$('.multiple').show();
$('.single').hide();
}
}).change();
});
Natively, you would use window.onload = () => { ... }; instead.

bootstrap 4 validation disable submit button until form validated

In the following example of my problem I have 2 fields needing to be validate.
Until all (2 in this case) fields are validated, the submit button should be disabled.
If both are validated it should be enabled.
My problem: The minute the first field is validated - the button is enabled, which is too early.
I understand (ot think that I do) that this occurs because of where I placed $("#submitBtn").attr("disabled",false);
Any hint of how to get it work would be greatly appreciated.
EDIT: For an example of a full registration form with the submit button enabled ONLY when all the form's elements are validated, see this.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red; }
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
window.addEventListener('load', function() {
let currForm1 = document.getElementById('myForm1');
// Validate on input:
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid')
input.classList.add('is-valid');
$("#submitBtn").attr("disabled",false); <<<<======== ??????
} else {
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
});
});
// Validate on submit:
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
currForm1.classList.add('was-validated');
}, false);
});
</script>
Inside your input event listener check if all the inputs have an is-valid class. If all your inputs have an is-valid class, turn off the disabled button.
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
input.classList.remove('is-invalid')
input.classList.add('is-valid');
// $("#submitBtn").attr("disabled",false); <<<<======== ??????
} else {
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
var is_valid = $('.form-control').length === $('.form-control.is-valid').length;
$("#submitBtn").attr("disabled", !is_valid);
});
});
I don't know this is good approach or not and it also depend on your requirement if it fulfil your need so that's fine..
here i'm removing some line and adding some line
remove disable button code from first condition and added at the last
if(input.checkValidity() && index ===1) {
$("#submitBtn").attr("disabled", false);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<style>
input[type="submit"]:disabled {
background-color: red; }
</style>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-md-4 offset-md-4">
<form action="page2.php" id="myForm1" class="needs-validation" novalidate>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" required autofocus>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<input type="text" class="form-control" pattern="^[a-z]{3,6}$" required>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">a to z only (3 to 6 long)</div>
</div>
<div class="form-group">
<button id="submitBtn" type="submit" class="btn btn-primary submit-button" disabled>Submit</button>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
window.addEventListener('load', function() {
let currForm1 = document.getElementById('myForm1');
// Validate on input:
currForm1.querySelectorAll('.form-control').forEach((input, index) => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
console.log(input.checkValidity());
input.classList.remove('is-invalid')
input.classList.add('is-valid');
} else {
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
if(input.checkValidity() && index ===1) {
$("#submitBtn").attr("disabled", false);
}
});
});
// Validate on submit:
currForm1.addEventListener('submit', function(event) {
if (currForm1.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
currForm1.classList.add('was-validated');
}, false);
});
</script>
</body>
</html>
We need to check if all the other inputs are also valid before assuming that we can just enable it
let currForm1 = document.getElementById('myForm1');
// Validate on input:
currForm1.querySelectorAll('.form-control').forEach(input => {
input.addEventListener(('input'), () => {
if (input.checkValidity()) {
/* IF IT PASSES WE NEED TO CHECK THE OTHER INPUTS */
/* STORE ALL THE INPUTS THAT PASS THE CHECKVALIDITY */
let allValid = currForm1.querySelectorAll('.form-control').filter(input =>
{ return input.checkValidity() })
/* WE CAN NOW UPDATE THE SUBMIT BASED ON THE NUMBER OF VALID
INPUTS WE HAVE */
$("#submitBtn").attr("disabled", allValid.length === currForm1.querySelectorAll('.form-control').length);
input.classList.remove('is-invalid')
input.classList.add('is-valid');
} else {
/* IF IT FAILS WE DONT NEED TO CHECK WE WANT THE VALIDATOR AS FALSE */
$("#submitBtn").attr("disabled", true);
input.classList.remove('is-valid')
input.classList.add('is-invalid');
}
});
});
/* FINALLY WE CAN UPDATE THE SUBMIT, BASED ON OUR VARIABLE */
$("#submitBtn").attr("disabled", validatorForSubmit );

Remove all selected options

I have multiple inputs with the same name and I want to select only one option.
But this option should be null if the checkbox is not selected. I have a problem when the user selects the checkbox chooses a option and then unchecks. the option is still selected. When i untick the checkbox I want to remove all options with that name.
So I tried $('input[name="customerUIBranch"]').val(null); but it's not helping
$('#hasCustomerUITab').hide();
$('#customerUI').change(function () {
if ($(this).is(":checked")) {
$('#hasCustomerUITab').show();
}
else {
$('#hasCustomerUITab').hide();
$('input[name="customerUIBranch"]').val(null);
}
});
$('#submit').click(function() {
console.log($('input[name="customerUIBranch"]').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox checkbox-primary">
<input type="checkbox" id="customerUI" name="hasCustomerUI">
<label for="customerUI">Customer UI</label>
</div>
<div class="row">
<div class="col-sm-10">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#customerUIContent" id="hasCustomerUITab" style="" aria-expanded="true">Customer UI</a></li>
</ul>
<div class="tab-content tab-content-border">
<div id="hostContent" class="tab-pane fade">
<div id="customerUIContent" class="tab-pane fade active in">
<div class="scrollableBranches">
<div class="form-group">
<div class="radio radio-info increase-size">
<input type="radio" value="" name="customerUIBranch" id="customerUIBranch1" data-error="Please, choose one option">
<label for="customerUIBranch1">build-setup
</label>
</div>
<div class="radio radio-info increase-size">
<input type="radio" value="" name="customerUIBranch" id="customerUIBranch2" data-error="Please, choose one option">
<label for="customerUIBranch2">master
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<button id="submit">Submit</button>
Try this
$('#hasCustomerUITab').hide();
$('#customerUI').change(function () {
if ($(this).is(":checked")) {
$('#hasCustomerUITab').show();
}
else {
$('#hasCustomerUITab').hide();
//this
$('input[name="customerUIBranch"]').prop('checked', false);
//or
$('input[name="customerUIBranch"]').attr("checked", false);
}
});
$('#submit').click(function() {
console.log($('input[name="customerUIBranch"]').val());
});
https://jsfiddle.net/h3d7zttj/1/
$('#hasCustomerUITab').hide();
$('#customerUI').change(function () {
if ($(this).is(":checked")) {
$('#hasCustomerUITab').show();
}
else {
$('#hasCustomerUITab').hide();
$('input[name=customerUIBranch]').removeAttr('checked');
}
});
$('#submit').click(function() {
console.log($('input[name="customerUIBranch"]').val());
});
You should change this line
$('input[name="customerUIBranch"]').val(null);
with this line
$('input[name="customerUIBranch"]').prop('checked', false);
Try this:
<script>
jQuery('#hasCustomerUITab').hide();
$('#customerUI').change(function () {
var ischecked= $(this).is(':checked');
if(ischecked){
$('#hasCustomerUITab').show();
}
else {
$('#hasCustomerUITab').hide();
$('input[name="customerUIBranch"]').val(null);
$(":radio").removeAttr("checked");
}
});
$('#submit').click(function() {
console.log($('input[name="customerUIBranch"]').val());
});

Hide/Display a input field based on value from HtmlRadioButtonFor and make it mandatory if display

I have a scenario where I have two different div's and the later should disappear based on boolean value from earlier div. if the radiobutton value is true, later div should be a required filed.
Actual Code:
<div class= row ">
<div class="row col-lg-offset-2 top-buffer">
<h4><strong><span>Is Employment Offered?</span> <span class="text-danger">*</span></strong></h4>
#Html.RadioButtonFor(model => model.IsOffered, true) #Html.Label("Yes")
#Html.RadioButtonFor(model => model.IsOffered, false) #Html.Label("No")
<br>
</div>
<div class="row col-lg-offset-2 top-buffer" id="employeeNumber">
<div class="col-sm-2"><b>Enter Employee Number</b></div>
<div class="col-sm-10">
#Html.TextBoxFor(model => model.EmployeeNumber, new { #class = "form-control" })
<br />
</div>
</div>
</div>
<script>
$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function() {
if ($(this).val() == "true") {
$("#employeeNumber").show();
}
});
I tried above, but no luck. Thanks you for your time!
Change it to "True":
$("#employeeNumber").hide();
$("input[name='IsOffered']").on("change", function () {
if ($(this).val() === "True") {
$("#employeeNumber").show();
} else {
$("#employeeNumber").hide();
}
});
Because Boolean.ToString() returs "True" instead of "true". So this value is added to the radio that is generated by razor.
Why?

How to implement multiple filters using checkboxes?

How do I implement multiple filters using checkboxes preferably using jQuery?
I have multiple div elements with their own data attributes which represent the difficulties of levels the user has completed.
I want to create a filter using checkboxes so that when they check a box for a specific difficulty which are completed, that difficulty is filtered out (hidden). If the user wants to filter multiple difficulties, then those difficulties are filtered out as well. If the user unchecks the box, then obviously it reappears.
Here is the div elements containing the data attributes. The data attributes which are set to true are the ones which are completed. E.g. (data-normal=true means normal difficulty is completed)
<div class="map-col-container col-xs-12 col-sm-6 col-md-4" data-mapname="Level One" data-completed="2" data-easy="true" data-normal="false" data-hard="true" data-expert="false">
<div class="map-col">
<!--Content Here-->
</div>
</div>
<div class="map-col-container col-xs-12 col-sm-6 col-md-4" data-mapname="Level Two" data-completed="4" data-easy="true" data-normal="true" data-hard="true" data-expert="true">
<div class="map-col">
<!--Content Here-->
</div>
</div>
<div class="map-col-container col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="true" data-normal="false" data-hard="false" data-expert="false">
<div class="map-col">
<!--Content Here-->
</div>
</div>
In this example, if I checked expert, then Level Two should become hidden. If I also checked hard, then both Level One and Level Two should be hidden.
Here are my checkboxes
<div class="checkbox">
<label><input type="checkbox" id="hideEasyChkBox">Hide Easy</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideNormalChkBox">Hide Normal</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideHardChkBox">Hide Hard</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideExpertChkBox">Expert</label>
</div>
I did attempt this using a bool for each difficulty however if a box became unchecked despite other boxes being checked, it would unhide all the levels ignoring the fact other boxes are still checked.
If anything is unclear, please ask. Thanks
Edit: Here is the method I used however this does not work as when I uncheck one of the checkboxes, the div's reset and display all the levels ignoring the fact that the other boxes are still checked.
var hideCompleted = false;
var hideEasy = false;
var hideNormal = false;
var hideHard = false;
var hideExpert = false;
function mapCompletionFilter(filterBy){
var $wrapper = $('.map-container');
if(filterBy == "hideCompleted" && !hideCompleted){
//$wrapper.find(".map-col-container[data-completed*=4]").hide();
$wrapper.find(".map-col-container").filter('[data-completed="4"]').hide();
hideCompleted = true;
}
else if(filterBy == "hideCompleted" && hideCompleted){
$wrapper.find(".map-col-container[data-completed*=4]").show();
hideCompleted = false;
}
if(filterBy == "hideEasy" && !hideEasy){
//$wrapper.find(".map-col-container[data-completed*=4]").hide();
$wrapper.find(".map-col-container").filter('[data-easy="true"]').hide();
hideEasy = true;
}
else if(filterBy == "hideEasy" && hideEasy){
$wrapper.find(".map-col-container").filter('[data-easy="true"]').show();
hideEasy = false;
}
if(filterBy == "hideNormal" && !hideNormal){
//$wrapper.find(".map-col-container[data-completed*=4]").hide();
$wrapper.find(".map-col-container").filter('[data-normal*="true"]').hide();
hideNormal = true;
}
else if(filterBy == "hideNormal" && hideNormal){
$wrapper.find(".map-col-container").filter('[data-normal*="true"]').show();
hideNormal = false;
}
if(filterBy == "hideHard" && !hideHard){
//$wrapper.find(".map-col-container[data-completed*=4]").hide();
$wrapper.find(".map-col-container").filter('[data-hard*="true"]').hide();
hideHard = true;
}
else if(filterBy == "hideHard" && hideHard){
$wrapper.find(".map-col-container").filter('[data-hard*="true"]').show();
hideHard = false;
}
if(filterBy == "hideExpert" && !hideExpert){
//$wrapper.find(".map-col-container[data-completed*=4]").hide();
$wrapper.find(".map-col-container").filter('[data-expert*="true"]').hide();
hideExpert = true;
}
else if(filterBy == "hideExpert" && hideExpert){
$wrapper.find(".map-col-container").filter('[data-expert*="true"]').show();
hideExpert = false;
}
}
Buttons
$("#hideAllCompletedChkBox").click(function(){
mapCompletionFilter("hideCompleted");
});
$("#hideEasyChkBox").click(function(){
mapCompletionFilter("hideEasy");
});
$("#hideNormalChkBox").click(function(){
mapCompletionFilter("hideNormal");
});
$("#hideHardChkBox").click(function(){
mapCompletionFilter("hideHard");
});
$("#hideExpertChkBox").click(function(){
mapCompletionFilter("hideExpert");
});
The main issue I am having is when I use multiple checkboxes for hiding each individual difficulty whereby if one of these checkboxes are unticked, all div's become unhidden.
Here, i prepare fiddle t show how it works - https://jsfiddle.net/skyr9999/nynbupwh/
I update you html a bit to make sure and test all works fine.
Here's is html:
<div id="elems">
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level One" data-completed="2" data-easy="true" data-normal="false" data-hard="true" data-expert="false">
<div class="map-col">
Easy, hard
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Two" data-completed="3" data-easy="true" data-normal="true" data-hard="true" data-expert="true">
<div class="map-col">
Easy, Normal, Expert
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="true" data-normal="false" data-hard="false" data-expert="false">
<div class="map-col">
Easy
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="false" data-normal="true" data-hard="false" data-expert="false">
<div class="map-col">
Normal
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="false" data-normal="false" data-hard="true" data-expert="false">
<div class="map-col">
Hard
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="false" data-normal="false" data-hard="false" data-expert="true">
<div class="map-col">
Expert
</div>
</div>
<div class="datadiv col-xs-12 col-sm-6 col-md-4" data-mapname="Level Three" data-completed="1" data-easy="false" data-normal="false" data-hard="false" data-expert="false">
<div class="map-col">
None
</div>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideEasyChkBox">Hide Easy</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideNormalChkBox">Hide Normal</label>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideHardChkBox">Hide Hard</label>
</div>
</div>
<div class="checkbox">
<label><input type="checkbox" id="hideExpertChkBox">Expert</label>
</div>
And js:
jQuery(document).ready(function ($) {
updateVisible = function () {
$("#elems>div.datadiv").each(function (index, value)
{
$(value).show();
if ($(value).attr("data-expert") === "true")
{
if ($("#hideExpertChkBox").is(':checked'))
{
$(value).hide();
}
}
if ($(value).attr("data-hard") === "true")
{
if ($("#hideHardChkBox").is(':checked'))
{
$(value).hide();
}
}
if ($(value).attr("data-normal") === "true")
{
if ($("#hideNormalChkBox").is(':checked'))
{
$(value).hide();
}
}
if ($(value).attr("data-easy") === "true")
{
if ($("#hideEasyChkBox").is(':checked'))
{
$(value).hide();
}
}
});
};
$(document).on("change", "#hideEasyChkBox", function () {
updateVisible();
});
$(document).on("change", "#hideNormalChkBox", function () {
updateVisible();
});
$(document).on("change", "#hideHardChkBox", function () {
updateVisible();
});
$(document).on("change", "#hideExpertChkBox", function () {
updateVisible();
});
});
So how it works - on checkbox change it call updateVisible() function. Than it get first div and show all it. After that it test if checkbox of filter checked and if div have atrr and if so, just hide it, if none attr set to true it just ingore such div. And then all repeated for all other divs.

Categories