jQuery: Single change event to fire multiple functions not working - javascript

I'm systematically building jQuery functions such that the css classes of various inputs in a web form have dependencies on other inputs (i.e. when a given input has a given value, the "hide" class is removed from the appropriate subsequent input etc.)
A specific (working) example of the jQuery I am using is:
$(document).ready(function(){
$("input[name$='q_4']").change(function(){
if(this.value == 'Yes') {
$('#qu_5').removeClass('hide');
} else {
$('#qu_5').addClass('hide');
}
});
});
In this example, the dependent question div (#qu_5) depends on the value entered via radio button for (name=q_4) to be "Yes".
Because I am building these functions dynamically (users can edit properties of questions such that they have these kinds of display dependencies) via a database, I end up with multiple chunks of this code on a page with several interdependent inputs. Each chunk of code has the name of the master question, the id of the slave question and the value that the slave relies on to be revealed. This also works as intended.
Sometimes however, one input should reveal multiple other questions so I end up with code something like:
$(document).ready(function(){
$("input[name$='q_87']").change(function(){
if(this.value == 'yes') {
$('#qu_88').removeClass('hide');
} else {
$('#qu_88').addClass('hide');
}
});
$("input[name$='q_87']").change(function(){
if(this.value == 'yes') {
$('#qu_89').removeClass('hide');
} else {
$('#qu_89').addClass('hide');
}
});
});
This does not work. (and indeed stops all the reveal / hide functions working on that page)
I presume it is because jQuery/javascript isn't happy with the same event input[name$='q_87']").change firing two different functions? This is the only thing I can think of.
Does anyone have any advice as to how I could achieve what I want in a way that works? Thanks! :)

If you need a var and an array you can write it like this
var questions = {
"q_87":["qu_88","qu_89"],
"q_96":["qu_95","qu_99"]
}
$.each(questions,function(q,arr) {
$("input[name$='"+q+"']").change(function(){
$("'#"+arr.join(",#")+"'").toggleClass('hide',this.value == 'yes');
});
});

Related

Hiding fields based on email value AND boolean yes/no field using JavaScript

I have a Microsoft Power Apps Portals page on my portal that requires a bit of customization through JavaScript. I would like to hide fields based on an email address entered, which works fine. However, when the user enters the email domain that will show some fields, I would like to apply additional formatting.
Here is the code I currently have:
$(document).ready(function () {
$("#emailaddress1").change(onShowHideEmployeeFields);
onShowHideEmployeeFields();
});
function onShowHideEmployeeFields() {
var varEmail = $("#emailaddress1").val()
//alert(varEmail)
if (varEmail.includes("#example.org")) {
$('#xxx_employeeid').parent().parent().show();
$('#xxx_employeeid').prop('required', true);
$('#xxx_employeeid').closest(".control").prev().addClass("required");
$('#xxx_defaultfacilityid').parent().parent().show();
$('#xxx_defaultfacilityid').prop('required', true);
$('#xxx_defaultfacilityid').closest(".control").prev().addClass("required");
$('#xxx_positiontitle').parent().parent().show();
$('#xxx_officer').parent().parent().show();
$('#xxx_officer').prop('required', true);
$('#xxx_officer').closest(".control").prev().addClass("required");
$('#xxx_jopositiontitle').parent().parent().show();
}
else {
$('#xxx_employeeid').parent().parent().hide();
$('#xxx_defaultfacilityid').parent().parent().hide();
$('xxx_defaultfacilityid_label').parent().parent().hide();
$('xxx_positiontitle_label').parent().parent().hide();
$('#xxx_positiontitle').parent().parent().hide();
$('#xxx_officer').parent().parent().hide();
$('#xxx_jopositiontitle').parent().parent().hide();
}
}
The code works fine, however, I want to extend the code by showing the JO Position Title IF the Officer field has been marked as 'Yes' (it is a boolean yes/no radio checkbox field).
I've tried testing this component separately using the below code:
function onShowHideEmployeeFields() {
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").val();
//alert(varJO)
if (varJO === 'Yes') {
$('xxx_jopositiontitle').parent().parent().show();
}
else {
$('xxx_jopositiontitle').parent().parent().hide();
}
})
}
This code doesn't seem to do anything. Any thoughts on this issue?
Thank you!
AFAICT your question boils down to how can I check if a checkbox is checked?. The code you tried is on the right track, but that's not how you get a checkbox's state. A quick search turns up many many examples:
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").prop('checked');
if (varJO) {
$('xxx_jopositiontitle').parent().parent().show();
} else {
$('xxx_jopositiontitle').parent().parent().hide();
}
});
There are many, many examples of this here on SO, and I've voted to close this question as a duplicate.
How do I check whether a checkbox is checked in jQuery?
Get checkbox value in jQuery
get current state of check box jquery
Check if checkbox is checked with jQuery
Get checkbox selected state with JQuery
...

Does jQuery fadeIn() automatically check if element is visible? | Coding Efficiency

I have jQuery loading data for my web app. Being a web app, all my code is being compiled into one file. It's reused often. Filesize and inefficiencies could seriously slow down my website performance and load time.
My question is: Does jQuery have built-in handlers for redundancies?
My example concerns the .fadeIn() function. I don't want $('.search-output') to "fade in" every single time a key is pressed, however, I don't want to add unneeded code that jQuery already handles on its own.
I'm assuming that jQuery does handle these redundancies on its own because no animation is present when running this without my 'if visible' statement. Still, it might run other code that slows down my web app. Is it better/efficient coding practice to code in my own handlers for everything or to let jQuery handle it on its own?
I know I could look at the jQuery code but you guys might have more valuable input than just a yes or a no.
$this.find('.search-input input').keyup(function() {
if ($(this).val() == '') {
$(this).parent().parent().parent().parent().find('.search-output').fadeOut(150)
} else {
if (!$(this).parent().parent().parent().parent().find('.search-output').is(':visible')) {
$(this).parent().parent().parent().parent().find('.search-output').fadeIn(150)
}
formData.append('request', 'req_search_users')
formData.append('searchString', $(this).val())
xhr_request(formData, open)
function open($status, $_rtn) {
if ($status == 200) {
$output = $this.find('.search-output')
$_rtn = $_rtn.split('|,')
if (parseInt($_rtn[0]) > 0) {
$output.append($_rtn[1]).ready(function() {
link_user_click($(this))
})
}
if (parseInt($_rtn[0]) < 3) {
$this.addClass('eof')
$this.find('.auto-loader').hide();
}
} else {
console.log('XHR POST: 404 Error')
}
}
}
})
This is the specific section of code we are looking at:
if (!$(this).parent().parent().parent().parent().find('.search-output').is(':visible')) {
$(this).parent().parent().parent().parent().find('.search-output').fadeIn(150)
}
This is my first stack-overflow post. Thanks for any input you can provide!
The answer is yes. jQuery does apply fade-in animation to all visible elements (elements with the CSS property display not equal to hidden). All jQuery methods which animates visibility are an "extension" of the <collection>.toggle() method, which automatically switches between hidden and inline states, see https://api.jquery.com/toggle/

Can't get tooltip to go away

In a form, I have a State dropdown and a Zip Code text box. The client has specified they want to check to be sure the zip code matches the state, and if not, to pop up a message and prevent the form from being submitted.
After either the zip or the state is changed, I call an ajax function on the server to make sure the zip code is inside the state. If not, I pop up a tooltip over the zip code check box that says "Zip Code Not In Selected State". So that the tooltip doesn't appear unless there is a mismatch, I don't add it until/unless the zip doesn't match the state. That all works well.
Then, if the zip code changes, and it matches, I want to get rid of the tooltip. This is the part I can't get working. No matter what I try, that pesky tooltip sticks around, even after the zip matches the state.
Here's the client side method:
function CheckZip() {
var zip = $("#ZipCode").val();
var zipLength = zip.length;
var state = $("#StateCode").val();
if (zipLength === 5) {
$.getJSON("/Home/CheckZip", { zipCode: zip, stateCode: state },
function (data) {
if (data == "true") {
$('#ZipCode').tooltip('disable');
$('#ZipCode').tooltip().mouseover();
}
if (data == "false") {
$('#ZipCode').attr('data-toggle', 'tooltip');
$('#ZipCode').attr('data-placement', 'top');
$('#ZipCode').attr('title', 'Zip code not in selected state.');
$('#ZipCode').tooltip().mouseover();
DisableSubmitButton();
}
if (data == "error") {
// todo
}
});
}
else {
DisableSubmitButton();
}
}
This doesn't seem to be the right combination to make the tooltip go away.
$('#ZipCode').tooltip('disable');
$('#ZipCode').tooltip().mouseover();
I've also tried just removing all the attributes, opposite of what's done in if (data == "false"). That didn't work either.
Any ideas?
Try this once :
$("#ZipCode").off('mouseover',rf);
As I asked you in the comments if you were using bootstrap, I have an anwer for you. To hide the tooltip you must change disable to hide. Also you have to remove the line below the hide event, like this:
if (data == "true") {
$('#ZipCode').tooltip('hide');
}
Documentation for bootstrap tooltips can be found here
I hope this will help!
What I ended up doing was just creating my own div which, using CSS, hovers just over the Zip textbox. I can hide it and show it whenever I want. This works perfectly. Found a thread here on Stack Overflow that showed me how to do the css:
Relatively position an element without it taking up space in document flow

Auto-advance on choice selection code doesn't work

Qualtrics provides some JavaScript that it claims will automatically move participants to the next survey question when they select an answer choice. They have options for single-answer and multiple-answer multiple choice questions, but I only need the former for my survey. I put their code in the correct place, but I can't get it to work. NOTE: I'm trying to make a mobile compatible survey (not just compatible, but very well made for mobile use). Qualtrics' code does not work on mobile devices or on my laptop. I'm not sure if their code is incorrect or if I have to do something else to implement it correctly.
Here's the code for Auto-Advance SINGLE-Answer Multiple Choice questions Qualtrics provides:
var that = this;
this.questionclick = function(event,element){
if (element.type == 'radio') {
that.clickNextButton();
}
}
Here's the code for Auto-Advance MULTIPLE-Answer Multiple Choice questions Qualtrics provides:
var that = this;
this.questionclick = function(event,element){
if (element.type == 'checkbox') {
that.clickNextButton();
}
}
Again, I'm only using the former for my survey, but I thought I'd include both anyway. I know Java and C fairly well but I've never learned JavaScript, so I'm not sure how these work with Qualtrics and if this code is correct or if there's something I'm not doing.
Also, if anyone has a solution that isn't in JavaScript (like if there's one in CSS or HTML or something weird) I would appreciate the other options.
Thanks in advance!
I'm really not sure why the code did not work before, because now it works perfectly fine:
Qualtrics.SurveyEngine.addOnload(function()
{
var that = this;
this.questionclick = function(event,element){
if (element.type == 'radio') {
that.clickNextButton();
}
}
});
I'm guessing it was some error on Qualtrics' part because it's the same exact code which is now working.
you are correct, it is only set up to work for either single answer multiple choice or multiple answer multiple choice, so it is not meant for additional coding other than that. Here is a site you can use to test it: https://new.qualtrics.com/SE/?SID=SV_1S8i98l8YClkZ5H&Preview=Survey&BrandID=qcorp
Also, Qualtrics can help you troubleshoot code if you give the support team a call.
Automatically shift to next question + No Next button (fastest way to navigate through survey)
Enter Javascript view on any question
Copy and delete all code
Paste the following
Qualtrics.SurveyEngine.addOnload(function()
{
var that = this;
this.questionclick = function(event,element){
if (element.type == 'radio') {
that.clickNextButton();
}
}
});
Enter into HTML view for same question
Add the cursor to the bottom/end of the text
Add the following
<style>
#NextButton {display:none;}
</style>
Your all done. Preview to test

Hide / Show Multiple Divs

I am trying to create a form that has various hide/reveals in it and one of the last parts I need to do to this form is SHOW the payment information fields when only Credit Card is selected.
I have a test page setup here: http://www.faa.net.au/test/femmes-member-form.html
Process so far is:
Enter your details
Select Event Date
Selecting Member + 1 or more Guests ask for payment details
At the moment, I have displayed the 3 DIVs that I want to appear depending on the radio selection made but when I hide these, the code I have in place at present doesn't work.
Can anyone help me here at all please?
If you need the code, please let me know, with a number of different elements involved I didnt want to paste the whole thing on here, hopefully you can see the Source Code?
Here is the Javascript I have at present but not sure if its this that is wrong or if its clashing with something else?
<script type="text/javascript">
$(function() {
$('.cat_dropdown').change(function() {
$('#payMethod').toggle($(this).val() >= 2);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".payOptions").click(function () {
$(".paymentinfo").hide();
switch ($(this).val()) {
case "Credit Card Authorisation":
$("#pay0").show("slow");
break;
case "Direct Deposit":
$("#pay1").show("slow");
break;
case "Cash Payment (FAA Office)":
$("#pay2").show("slow");
break;
}
});
});
</script>
As per viewing code from View Souce and guessing that you have not added correct class in event handler. thus click event for radio is not getting invoked.
Change
$(".payOptions").click(function () {
to
$(".paymentmethod").click(function () {
You have not posted any source, but if you are using jQuery, you can simply do:
$(".commonclass").hide();
Provided that all 3 divs have the "commonclass" class.
Process goes something like this:
Start clean: hide all payment methods
Your radio inputs have paymentmethod class, so attach a change event listener to those elements
When one of the radios is selected, hide all of the payment methods, determine the one you want to show using index, and show that div
$('#pay0, #pay1, #pay2').hide();
$('input.paymentmethod').on('change', function(){
$('#pay0, #pay1, #pay2').hide();
var selected = $('input.paymentmethod').index($('input.paymentmethod:checked'));
$('#pay'+selected).show();
});
Used to jquery as like this
Css
#pay0, #pay1, #pay2{display:none;}
Jquery
$(document).ready(function(){
$('#payment').change(function(){
if($('#CAT_Custom_255277_0').attr('checked')){
$('#pay0').show();
$('#pay1').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_1').attr('checked')){
$('#pay1').show();
$('#pay0').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_2').attr('checked')){
$('#pay2').show();
$('#pay0').hide();
$('#pay1').hide();
}
});
});
Demo
As per my understanding, you're trying like below,
select value from dropdown, if the value !== "1" then show payment radio buttons
Based on the radio button selection, you want to show the respective div
From viewing your source code, it seems you're using jQuery lib and there use this
$(document).ready(function() {
$('input[type=dropdown]').on('change', function(){
if($(this).val() !== 1)
{
$('input[type=radio]').show();
}
}
$('input[type=radio]').on('change', function(){
if($(this).val() === "Credit Card Authorisation") {
$('#pay1').hide();
$('#pay2').hide();
$('#pay0').show();
}
else if($(this).val() === "Direct Deposit"){
$('#pay0').hide();
$('#pay2').hide();
$('#pay1').show();
}
else if($(this).val() === "Cash Payment (FAA Office)"){
$('#pay0').hide();
$('#pay1').hide();
$('#pay2').show();
}
});
});
Hope you understand.

Categories