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
Related
I am trying to write a simple script which follows the logic below but I am having difficulties.
If "Name" field = blank
Then Hide "Comment" field
Else Show "Comment" field
$(document).ready(function() {
if ($('#ContactForm-name').value() == "") {
$('#ContactForm-body').hide();
} else {
$('#ContactForm-body').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Can someone please help me? I provided a screen shot of the form and its HTML.
The shopify store is https://permaink.myshopify.com/pages/contact with the store PW = "help".
Taking a look at the example link you provided w/ 'help' password, it doesn't look like jQuery is actually loaded on the site, after running the following in console: console.log(typeof window.jQuery) returns undefined.
You may need to use vanilla JS to achieve what you're trying to do (or side load jQuery, if you have permissions to do so and really need to use it).
Using JS without jQuery, you can try doing something like:
window.addEventListener('load', function() {
if (document.getElementById('ContactForm-name').value === '') {
document.getElementById('ContactForm-body').style.display = 'none';
} else {
document.getElementById('ContactForm-body').style.display = 'block';
}
});
Note, that just hiding the ContactForm-body textarea will still leave a border outline and the label Comment showing, so you may need to do more than just hiding the textarea (find the parent <div> in JS and hide whole block).
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
...
I run a WoW guild forum based on php (phpbb), javascript and html. Ever since long, Wowhead allows links to be posted to their item/spell IDs etc. The basic code to the Wowhead JS and it's variables is:
<script src="//static.wowhead.com/widgets/power.js"></script>
<script>var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }</script>
There is an extension that puts this code in the footer of every page via a HTML file. Every Wowhead link posted will be converted in a link with a tooltip explaining what it links to. The '"renamelink": true' portion of the wowhead_tooltips variable makes it as such that any link of an item or spell is renamed to the exact name of what it is linked to.
The problem: when I generate custom URLs using a Wowhead link, ie:
Teleport
instead of displaying 'Teleport' with a tooltip of Blink, it will rename the entire URL to Blink with an icon, as described in the wowhead_tooltips variable.
What I want to achieve is:
Any direct URL to Wowhead should be converted into a renamed spell/item.
Any custom URL to Wowhead should be retain it's custom text, but retrieve the tooltip.
This should both be possible on a single page.
The best solution I have come up with is to add an 'if' function to var wowhead_tooltips based on class, then add the class to URLs:
<script>if ($('a').hasClass("wowrename")) { var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": false } }</script>
<a class="wowrename" href="http://www.wowhead.com/spell=1953">Teleport</a>
This works, however, the problem with this solution is that once the script recognizes one URL with the class "wowrename" on the page it will stop renaming all links, meaning that custom URLs and direct URLs can't be mixed on a single page.
Any other solution I've tried, using IDs, defining different variables etc either don't work or come up with the same restriction.
Hence the question, is it possible to change Javascript variables (in this case "var wowhead_tooltips { "renamelinks": false}" per element (URL), based on id, class or anything else?
Direct link that gets renamed with tooltip and iccn.
Teleport
Custom link with tooltip and original text.
I've stored the original link text as a data attribute so we can restore it after it's been changed.
<a class="wowrename" href="http://www.wowhead.com/spell=1953" data-value="Teleport">Teleport</a>
Keep checking for when static.wowhead.com/widgets/power.js changes the last link text. Once changed, restore using the data-value value, remove the styling added that creates the icon and stop the timer.
$(function () {
//timmer
checkChanged = setInterval(function () {
// check for when the last link text has changed
var lastItem = $("a.wowrenameoff").last();
if (lastItem.text() !== lastItem.data('value')) {
$("a.wowrenameoff").each(function () {
//change value
$(this).text($(this).data('value'));
//remove icon
$(this).attr('style', '');
//stop timer
clearInterval(checkChanged);
});
}
i++;
}, 100);
});
This does cause the link icon to flicker on then off, but it is repeated after a page refresh.
JSFiddle demo
This is simple solution. It's not the best way.
var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true }
$('a').hover(function() {
if ($(this).hasClass('wowrename') {
wowhead_tooltips.renamelinks = true;
}
else {
wowhead_tooltips.renamelinks = false;
}
});
I don't know how exactly wowhead API works, but if wowhead_tooltips variable is loaded exactly in the moment when the user points the link with the mouse (without any timeout) - this can fail or randomly work/not work.
The reason can be that the javascript don't know which function to execute first.
I hope this will work. If it's not - comment I will think for another way.
You have to loop on all the links, like this:
$("a.wowrename").each(function() {
// some code
});
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');
});
});
I have an accordion set up to handle registration. I am wanting to validate the data entered on each panel when the user clicks on a different panel tab. I have a continue button on each panel, and am able to validate to my heart's content when the user uses that to go to the next panel.
My problem is that they can also click independently on the accordion tabs (and I want them to be able to skip around for editing purposes), but I would like to validate on those events too.
I've done a bunch of searching, but have not found a satisfactory answer. I am fairly new to Javascript and super-brand-new to jQuery, so please, if you have code snippets for me, be thorough in explaining them.
This should be a straightforward problem (similar to on-click, etc.). I'm quite surprised and frustrated that I haven't found an answer yet.
Edit:
Eric, I couldn't get this to work. Here is my version. I put it in the head section. I have some test code in there that has worked reliably for me in the past (changing the label on one of the tabs). I'm assuming this code has worked for you? Anyway, thanks for your help and I hope we've understood each other sufficiently.
// add capability to detect when accordion tab has been clicked
RegFormAccordion.addEventListener('click', function(e){
var btnElement;
(function findAccordionButton(el){
//e.target is the original element actually clicked on
//the event bubbles up to ancestor/parent nodes which is why you can listen at
//the container
if(!btnElement){ btnElement = e.target; }
else { btnElement = el; }
if(e.target.className !== 'accordionBtn')
{
findAccordionButton(btnElement.parentNode);
}
else
{
var curr_panel_index = RegFormAccordion.getCurrentPanelIndex();
document.getElementById("verify-reg-panel-label").innerHTML = "Index = " + curr_panel_index; // test code to see if it's even getting here
if (curr_panel_index == 1) // contact section
{
ValidateContact();
}
else if (curr_panel_index == 2) // payment section
{
ValidatePayment();
}
UpdateVerifyPanel(); // update contents of verification panel
}
})()
} );
Event delegation.
someAccordianContainer.addEventListener('click', function(e){
var btnElement;
(function findAccordionButton(el){
//e.target is the original element actually clicked on
//the event bubbles up to ancestor/parent nodes which is why you can listen at
//the container
if(!btnElement){ btnElement = e.target; }
else { btnElement = el; }
if(e.target.className !== 'accordionBtn'){
findAccordionButton(btnElement.parentNode);
}
else { doSomething(btnElement); }
})()
} );
You will have to normalize for IE<=8 however if you're supporting older browsers, since it uses a proprietary attachEvent method. Hit quirksmode.org for the details or just use something like jQuery or MooTools.
OK. I found the function that SpryAccordion.js uses to open a new panel and added my own code. Simple and elegant. It's not what I would normally do (usually I leave "libraries" alone). But if you make it editable without giving me another way to take needed control, then the hack is gonna happen.
If I need to use another accordion somewhere else on my website, I will have to double check that I have the correct accordion before invoking the hack. A trade-off I'm willing to make. It works perfectly now. Here is the code:
Spry.Widget.Accordion.prototype.openPanel = function(elementOrIndex)
{
var panelA = this.currentPanel;
var panelB;
if (typeof elementOrIndex == "number")
panelB = this.getPanels()[elementOrIndex];
else
panelB = this.getElement(elementOrIndex);
if (!panelB || panelA == panelB)
return null;
// Start Becca's code
var panelIndex = this.getPanelIndex(panelA);
if (panelIndex == 1) // contact info panel
{
if (ValidateContact())
UpdateVerifyPanel();
else
return null;
}
else if (panelIndex == 2) // payment info panel
{
if (ValidatePayment())
UpdateVerifyPanel();
else
return null;
}
// End Becca's code
var contentA = panelA ? this.getPanelContent(panelA) : null;
var contentB = this.getPanelContent(panelB);
...
...
...
};
Yes, all I wanted was the same control over the panel tabs as I have over my own user-defined buttons, to make sure I could both validate before moving on, and to update my verification screen after any edit the user makes, not just the ones where they happen to hit my continue button. I'm a happy camper. So glad I took a couple of days off.
I hope this helps someone get more control over their own accordions. So glad I don't have to do a crash-course on jQuery when all I want right now is to get my blasted website up.