I am trying to hide and/or show form elements when a user selects certain values.
For example, if the user selects "yes" to the consent question, I need it to show a few questions, However, if they change their response to the consent question, I need it to hide those questions.
Here is what I have come up with so far...
$(document).ready(function () {
var input = document.getElementById('consent');
var consent_responses = [{ "0": hideConsent },{ "1": showConsent }];
input.addEventListner('click', function () {
var consent_response;
if (consent_responses[this.value]) {
content_response = consent_responses[this.Function()]
}
else {
content_response = consent_responses[this.Function]
}
});
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
function hideConsent(){
$("#date").hide(),
$("#referrer").hide(),
$("#f_name").hide(),
$("#phone_num").hide(),
$("#leave_msg").hide(),
$("#email").hide(),
}; });
Fiddle here: http://jsfiddle.net/7jX47/1/
You could do it like this: JSFiddle
Basically I only fixed a few typos (did you actually try your code before you posted here?) and added event listeners to the radio buttons with
document.getElementById(...).addEventListener(...)
I also gave your radio buttons unique IDs.
This can be simplified:
var input = document.getElementById('consent');
// Let's use the value as key, and the functions as values
var consent_responses = {
"0" : hideConsent,
"1" : showConsent
};
input.addEventListener("click", function () {
// Get the appropriate function given the value, and invoke it
consent_responses[this.value]();
});
function hideConsent() {
// ...
}
function showConsent() {
// ...
}
It's better to envelop your questions (that needs to be hidden) by a div with a class ".hidden" or style "display: none;". And simplify your code by simply asking that div to show() or hide() when needed.
Like so:
<form id="screening">
<div class="col-md-12 col-sm-12 col-xs-12 nopad" id="create">
<div class="form-group text-center">
<b>Do you agree to answer the screening questions?</b><br />
<div class="radio" id="consent">
<label>
<input type="radio" name="consent" id="consent" value="1">
Yes, I consent
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="consent" id="consent" value="0">
No, I do not consent
</label>
</div>
</div>
<!-- simplify by using this -->
<div id="questions" style="display: none;">
<div class="form-group" id="date">
<label for="date">What is today's date?</label>
<input type="date" class="form-control" id="date" name="date" />
</div>
<div class="form-group" id="referrer">
<label for="referrer">How did you hear about us/our studies?</label>
<select class="form-control" name="referrer" id="referrer">
<option></option>
<option value="1">Flyers</option>
<option value="2">Print Media</option>
<option value="3">A friend</option>
<option value="4">Online (e.g., Craigslist)</option>
<option value="5">Other</option>
</select>
</div>
<div class="form-group" id="other_explain">
<label for="other_explain">Please specify other source.</label>
<textarea class="form-control" rows="3" id="other_explain" name="other_explain"></textarea>
</div>
<div class="form-group" id="f_name">
<label for="f_name">What is your first name?</label>
<input type="text" class="form-control" id="f_name" name="f_name" />
</div>
<div class="form-group" id="phone_num">
<label for="phone_num">What is a phone number at which you can be contacted? </label>
<input type="tel" class="form-control" id="phone_num" name="phone_num" />
</div>
<div class="form-group" id="leave_msg">
<label for="leave_msg">If we call and you are not available, may we leave a message?</label><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="1">
Yes
</label>
</div><br />
<div class="radio">
<label>
<input type="radio" name="leave_msg" id="leave_msg" value="0">
No
</label>
</div>
</div>
<div class="form-group" id="email">
<label for="email">What is an e-mail at which you can be contacted?</label>
<input type="email" class="form-control" id="email" name="email" />
</div>
</div>
</div>
</form>
and in your javascript instead of using this:
function showConsent(){
$("#date").show(),
$("#referrer").show(),
$("#f_name").show(),
$("#phone_num").show(),
$("#leave_msg").show(),
$("#email").show(),
};
you use:
function showConsent(){
$("#questions").show(),
};
Related
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.
I would like to be able to edit a multi-select field when ("Update Data?") Checkbox is checked, and disabled the field again, when checkbox is un-checked.
Important is that checked status always leads to being able to edit, meanwhile un-checked means field is disabled, regardless if I load the form with a checked box or as un-checked as the initial state (I can save either or)
I find several useful answers but struggling with syntax to combine those into my solution.
Below can toggle once, then it gets stuck:
$(function() {
$("#checkbox1").change(function() {
if ($("#field2").attr('disabled', !this.checked)) {
$("#field2").removeAttr("disabled");
} else {
$("#field2").attr("disabled", "disabled");
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<div id="div_id_product" class="form-group row"> <label for="field2" class="col-form-label col-sm-4">
Multiselect
</label>
<div class="col-sm-7">
<select name="multiselect" class="select2-show-search selectmultiple form-control" id="field2" disabled="disabled" multiple style="width: 100%;">
<option value="1" selected>Product 1 </option>
<option value="3" selected>Product 3</option>
<option value="2">Product 2</option>
</select>
</div>
</div>
<div class="form-group row" id="checkbox1"> <label for="id_to_update" class="col-form-label col-sm-4">
Update Data?
</label>
<div class="col-sm-7">
<div class="input-group"> <input type="checkbox" name="to_update" class="checkboxinput" id="id_to_update"> <span class="input-group-append"></span> </div>
</div>
</div>
</form>
Just change your JS to this. You have the change listener on the wrong id.
The listener should be on #id_to_update (input) instead of #checkbox1 which is the div.
$(function() {
$("#id_to_update").change(function() {
$("#field2").prop('disabled', !this.checked);
});
})
Here is the solution you are looking for
$(function() {
$('#field-editable').change(function() {
$('#firstname').prop('disabled', !this.checked);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<label for="field-editable">
<input type="checkbox" id="field-editable">
do you want to edit
</label>
<input type="text" name="firstname" id="firstname" disabled="disabled">
</form>
I'm a novice php programmer and only knew a little about programming. I am trying to develop a job portal system where users can fill in their information to find jobs. My problem right now is very tiny but it's a small change that I want to make. Previously, I didn't put the part of Employment History but now I did. Users can select whether they are experienced or fresh graduate. If they are experienced, a form will be shown so that they can fill in the form.
Now the problem is, the form is hidden, but it leave a huge gap of whitespace between Employement History and other's section.
I've read others similar problems but can't find the right solutions. Can anyone help me by giving me guidance on how to remove the gap?
source code:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.visibility = 'visible';
} else document.getElementById('ifYes').style.visibility = 'hidden';
}
<label> Have you worked before?</label> <br>
<label for="yesCheck">Experienced Employee</label>
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"> <br>
<label for="noCheck">Fresh Graduate</label> <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"><br>
<div id="ifYes" style="visibility:hidden">
<p> Please describe your employement history, listing the most recent position first</p>
<div>
<p>1</p>
<div class="form-group">
<input class="form-control" id="emp1" name="emp1" placeholder="Employer"></input>
</div>
<div class="form-group">
<input class="form-control" type="text" id="pos1" name="pos1" placeholder="Position">
</div>
<div class="form-group">
<input class="form-control" type="text" id="date1" name="date1" placeholder="Dates [From-To]">
</div>
<div class="form-group">
<input class="form-control" type="text" id="reason1" name="reason1" placeholder="Reasons for Leaving">
</div>
</div>
<div>
<p>2</p>
<div class="form-group">
<input class="form-control" id="emp2" name="emp2" placeholder="Employer"></input>
</div>
<div class="form-group">
<input class="form-control" type="text" id="pos2" name="pos2" placeholder="Position">
</div>
<div class="form-group">
<input class="form-control" type="text" id="date2" name="date2" placeholder="Dates [From-To]">
</div>
<div class="form-group">
<input class="form-control" type="text" id="reason2" name="reason2" placeholder="Reasons for Leaving">
</div>
</div>
<div>
<p>3</p>
<div class="form-group">
<input class="form-control" id="emp3" name="emp3" placeholder="Employer"></input>
</div>
<div class="form-group">
<input class="form-control" type="text" id="pos3" name="pos3" placeholder="Position">
</div>
<div class="form-group">
<input class="form-control" type="text" id="date3" name="date3" placeholder="Dates [From-To]">
</div>
<div class="form-group">
<input class="form-control" type="text" id="reason3" name="reason3" placeholder="Reasons for Leaving">
</div>
</div>
</div>
I try this code based on the code I found on Write in a form by clicking on a button
Thank you in advance for guidance and help.
In CSS, visibility: hidden only makes the element invisible, but it still takes up space.
In your JavaScript code, use the display-property instead, which will completely hide the element:
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display= 'block';
} else document.getElementById('ifYes').style.display= 'none';
}
Here is my fiddle: My Fiddle (updated)
In my form (ID: #form), inputs fields are shown or hidden based on the selected option of a select input.
Each Input and its labels a wrapped in a div, which is hidden or shown based on the selected option. The attribute data-children of the select contains the information (in JSON Format) which inputs are to be shown when a certain option is selected.
I use the data-parsley-excluded attribute to remove the fields not visible from the parsley validation (Parsley Documentation).
Before I execute the parsley method $('#form').destroy();, at the end $('#form').parsley();
My HTML:
<div class="container">
<div class="row">
<div class="col-sm-offset-2 col-sm-8">
<form id="form" method="post" accept-charset="UTF-8" class="form-horizontal" data-parsley-validate="">
<div class="form-group">
<label class="control-label" for="question_01" style="">Question 1</label>
<select class="form-control" name="question_01" id="question_01" required data-children="{"option_01":["input_01","input_02","input_03","input_04","input_05","input_06"],"option_02":["input_01","input_06","input_07","input_08","input_09","input_10"],"option_03":["input_02","input_04","input_05","input_07","input_09","input_10","input_11"]}">
<option value="" selected>Bitte auswählen</option>
<option value="option_01">Option 01</option>
<option value="option_02">Option 02</option>
<option value="option_03">Option 03</option>
</select>
</div>
<div id="div_input_01" class="form-group input-div hidden">
<label for="input_01" style="">Input 01</label>
<input type="text" class="form-control" name="input_01" id="input_01" required>
</div>
<div id="div_input_02" class="form-group input-div hidden">
<label for="input_02" style="">Input 02</label>
<input type="text" class="form-control" name="input_02" id="input_02" required>
</div>
<div id="div_input_03" class="form-group input-div hidden">
<label for="input_03" style="">Input 03</label>
<input type="text" class="form-control" name="input_03" id="input_03" required>
</div>
<div id="div_input_04" class="form-group input-div hidden">
<label for="input_04" style="">Input 04</label>
<input type="text" class="form-control" name="input_04" id="input_04" required>
</div>
<div id="div_input_05" class="form-group input-div hidden">
<label for="input_05" style="">Input 05</label>
<input type="text" class="form-control" name="input_05" id="input_05" required>
</div>
<div id="div_input_06" class="form-group input-div hidden">
<label for="input_06" style="">Input 06</label>
<input type="text" class="form-control" name="input_06" id="input_06" required>
</div>
<div id="div_input_07" class="form-group input-div hidden">
<label for="input_07" style="">Input 07</label>
<input type="text" class="form-control" name="input_07" id="input_07" required>
</div>
<div id="div_input_08" class="form-group input-div hidden">
<label for="input_08" style="">Input 08</label>
<input type="text" class="form-control" name="input_08" id="input_08" required>
</div>
<div id="div_input_09" class="form-group input-div hidden">
<label for="input_09" style="">Input 09</label>
<input type="text" class="form-control" name="input_09" id="input_09" required>
</div>
<div id="div_input_10" class="form-group input-div hidden">
<label for="input_10" style="">Input 10</label>
<input type="text" class="form-control" name="input_10" id="input_10" required>
</div>
<div id="div_input_11" class="form-group input-div hidden">
<label for="input_11" style="">Input 11</label>
<input type="text" class="form-control" name="input_11" id="input_11" required>
</div>
<button type="button" class="btn btn-info btn-block btn-submit-settings">Submit</button>
</form>
</div>
</div>
</div>
My Javascript:
$(document).ready(function() {
$('.btn-submit-settings').on('click', function(e) {
window.Parsley.on('field:error', function()
{
console.log('Validation failed for: ', this.$element);
});
$('#form').submit();
});
$('#form select').change(function() {
var $this = $(this);
if ($this.data('children')) {
$('#form').parsley().destroy();
// Hide all child elements
$.each($this.data('children'), function(value_id, input_id_array) {
$.each(input_id_array, function(key, input_id) {
if ($('#div_' + input_id).length ) {
$('#' + input_id).val(null);
if (!$('#div_' + input_id).hasClass('hidden')) {
$('#div_' + input_id).addClass('hidden');
}
}
});
});
// show the child elements of the selected option
if ($this.data('children')[$this.val()]) {
$.each($this.data('children')[$this.val()], function(key, input_id) {
if ($('#div_' + input_id).length )
{
if ($('#div_' + input_id).hasClass('hidden'))
{
$('#div_' + input_id).removeClass('hidden');
}
}
});
}
// For all inputs inside hidden div set attribute "data-parsley-excluded" = true
$('#form div.input-div.hidden').find(':input').each(function() {
var attr_data_parsley_excluded = $(this).attr('data-parsley-excluded');
if (typeof attr_data_parsley_excluded === typeof undefined || attr_data_parsley_excluded === false) {
$(this).attr('data-parsley-excluded', 'true');
}
});
// For all inputs inside not hidden div remove attribute "data-parsley-excluded"
$('#form div.input-div:not(.hidden)').find(':input').each(function() {
console.log(this.id);
$(this).removeAttr('data-parsley-excluded');
});
$('#form').find(':input').each(function() {
// Log shows that attribute is set right, seems to be ignored by parsley
console.log('ID: ' + this.id + ' TYPE: ' + $(this).prop('nodeName') + ': excluded=' + $(this).attr('data-parsley-excluded'));
});
$('#form').parsley();
$('#form').parsley().refresh();
}
});
});
I can't get it to work, even though the attributes seem to be set the right way.
The fields once hidden, stay out of the validation.
I guess you should add the attribute data-parsley-required="false" to exclude hidden fields from validation.
I mean, try to change
<input type="text" class="form-control" name="input_01" id="input_01" required>
to this
<input type="text" class="form-control" name="input_01" id="input_01" data-parsley-required="false">
and just change the attribute value if you want to validate it or not
This is more of a personal opinion than a factual answer, but I think you are attempting to solve the problem incorrectly. If I were doing this, I would create 2 parsley groups "shouldValidate" and "shouldNotValidate", and add your fields accordingly based on whether they are displayed or not. Then when you call validate, pass the group name "shouldValidate", and only that set of elements will be validated.
You probably need to call refresh on your parsley form after you modify excluded.
I have 4 multiple check boxes which each one of them is specifically correspondent to 4 text-boxes. I need to enable the disabled texbox when the corresponding checkbox is checked. I wrote a same function for each checkbox's onclick event in html tag itself as onclick="document.getElementById('txtLrgPrc').disabled=!this.checked;" .
But I need to automate this by calling a function only once by sending the parameters of textboxes and heckboxes(i.e. id or name,,) to my js file using jQuery. Can anyone help me for refining this please?
Here is the code which I am currently using and it works finely.
jsp page:
<div class="row item-tbl-row" id="addItmChkbxReg">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="regular" class="checkbox sizechkbx" path="size" label="Regular" id="chkReg" onclick="document.getElementById('txtRegPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtRegPrc" disabled="true"/>
</div>
</div>
<div class="row item-tbl-row" id="addItmChkbxMed">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="medium" class="checkbox sizechkbx" path="size" label="Medium" onclick="document.getElementById('txtMedPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtMedPrc" disabled="true"/>
</div>
</div>
<div class="row item-tbl-row" id="addItmChkbxLrg">
<div class="col-xs-5">
<label class="checkbox-inline">
<form:checkbox value="large" class="checkbox sizechkbx" path="size" label="Large" onclick="document.getElementById('txtLrgPrc').disabled=!this.checked;"/>
</label>
</div>
<div class="col-xs-7">
<form:input type="text" class="form-control price" path="price" id="txtLrgPrc" disabled="true"/>
</div>
</div>
You can automate like the following.
<script type="text/javascript">
$(document).ready(function () {
$(".checkbox").click(function () {
$(this).parent().parent().next().find(".form-control").prop("disabled", !$(this).prop("checked"));
});
});
</script>
Also, remove the click event of the checkboxes.
Another solution:
<script type="text/javascript">
function C(t, textBoxId) {
$("#" + textBoxId).prop("disabled", !$(t).prop("checked"));
}
</script>
<form:checkbox value="regular" id="chkReg" onclick="C(this, 'txtRegPrc')"/>