jQuery won't hide form on click - javascript

I have three click events. Each one hides and shows different things depending on what is being clicked. Everything works except for the <form> with class markas doesn't get hidden when the <p> with class cancel is clicked.
Here is the jQuery:
$(".cancel").on("click", function(){
$(this).hide().parent().find('.celltext, .editlink, .marklink').show().parent().find('.editas, .markas').hide();
});
$(".editlink").on("click", function(){
$(this).hide().parent().find('.celltext, .marklink, .markas').hide().parent().find('.editas, .cancel').show();
$(this).parent().find(".editas input:text").focus();
});
$('.marklink').on("click", function(){
$(this).hide().parent().find('.celltext, .editlink, .editas').hide().parent().find('.markas, .cancel').show();
$(this).parent().find(".editas input:text").focus();
});
The HTML is exactly what you would assume. I have used a similar code with strings of .prev() and .next() and everything was hidden and shown correctly. Since I know it's not the internal HTML structure, rather than paste unnecessary code (I am using php functions and code to gather info from a database), the general structure is this:
<div>
<p class="celltext">Info from database</p>
<p class-"editlink">Edit</p>
<p class="marklink">Mark</p>
<form class="markas">Form with select box to mark the cell</form>
<form class="editas">Form with text fields to edit the info</form>
<p class="cancel">Cancel</p>
</div>
I have tried to hide the form in a separate line on its own, but that doesn't work either. Why doesn't it hide and how do I get it to hide properly when cancel is clicked?
UPDATE:
It has to do with the order that the forms display in. I swapped markas and editas and now markas hides and editas doesn't.

As per the comments above, this is the answer that solved the problem:
Without seeing a working example with the problem, I can't say for
sure, but I suspect you are picking up more elements than you intend
with the chained find() and parent() calls. I'd suggest doing a
parentEl = $(this).parent(); $(this).hide(); at the start of all of
your functions, then doing parentEl.find(...).show(); and
parentEl.find(...).hide(); It'll make your code easier to read, too.
$(".cancel").on("click", function(){
var parentel = $(this).parent();
$(this).hide();
parentel.find('.celltext, .editlink, .marklink').show();
parentel.find('.editas, .markas').hide();
});

Related

jQuery .insertAfter not working, trying to move element in DOM

I have tried the following jQuery code to move a <select> element (that I can only see within the DOM) after a <form> element but it does not work:
<script type="text/javascript">
jQuery('[id^=lc_currency]').insertAfter('[id^=lc_change]');
</script>
I have also tried:
<script type="text/javascript">
jQuery('select[id^=lc_currency]').insertAfter('form[id^=lc_change]');
</script>
Any coding suggestions? I am using a wildcard selector because on every page the ID changes, 1c_currency1, 1c_currency2, etc.
Live site is at http://thehungrygeek.com/2015/11/17/australia-dairy-company/
I want to move specifically a select dropdown box, from one place to another on a webpage. Unfortunately the element code is only located in the DOM.
This select dropdown box is located at the bottom of the page at http://thehungrygeek.com/2015/11/17/australia-dairy-company/
The code, only located in the DOM, is as follows:
<select style="width:200px" name="lc_currency1" id="lc_currency1" onchange="localCurrencyChange('SGD',lcValues1,1)">...</select>
The select dropdown box is supposed to be moved here:
The relevant code at the area is as follows:
<form name="lc_change1" id="lc_change1" action="http://thehungrygeek.com/2015/11/17/australia-dairy-company/" method="post">
Show currencies in
<noscript>[Please enable JavaScript to change the currency used on this page]</noscript>
<br>
<small>Powered by LocalCurrency. Rates from Yahoo! Finance</small>
</form>
Thanks for any help!
1st: Be sure you include jquery
2nd: Wrap your code in
$(document).ready(function(){
// your code here
});
3rd: Try to use .each()
$(document).ready(function(){
jQuery('select[id^=lc_currency]').each(function(){
var getformId = $(this).attr('id').replace('currency','change');
//alert(getformId);
$(this).insertAfter('form#'+ getformId);
});
});
Working Demo
I guess your id strings should be inside quote , Try this
$(function(){
jQuery("select[id^='lc_currency']").insertAfter("form[id^='lc_change']");
});
Edit:
Try to move the select element after 1 sec after window load. this might works for you as your select element coming from javascript code.
$(window).load(function(){
setTimeout(function(){
jQuery("form[id^='lc_change']").prepend( "select[id^='lc_currency']");
},1000);
});
From the screenshots you added, it seems like you want to insert the select inside the form, not after, this is what I used:
jQuery('[id^=lc_currency]').insertAfter('[id^=lc_change] noscript');

Issue with handling a form using javascript

We have a website hosted at hubspot, we use their native WYSIWYG to design layouts then style them with css and js.
On the homepage http://www.lspatents.com/ it used to have a form under the "Get started here" title, it had around 10 questions, and used javascript to split them to steps so they can fit in the same area on the currently shown blank box.
It was working just fine till two days ago the form disappeared and left it with a blank area as you can see now, and as far as i know no one has touched this code recently.
Here is the js code that was used to manipulate the form
// Hero Form
$(window).load(function() {
// disable autocomplete to fix bug
$('.hero-form form').attr("autocomplete", "off");
$('.hero-form .hs-richtext').each(function() {
$(this).nextUntil('.hs-richtext').wrapAll('<div class="step" />');
});
// Hide Loading icon
$('.hero-form form').css('background', 'none');
$('.hero-form form .step:nth-of-type(2)').show();
// First Step to Second Step
$('.step').find('.hs-richtext').change(function() {
$('.step:nth-of-type(2)').hide().next().next().fadeIn();
});
// Second Step to Third Step
$('.step').find('.hs-input').change(function() {
var names = {};
$(':radio').each(function() {
names[$(this).attr('name')] = true;
});
var count = 0;
$.each(names, function() {
count++;
});
if ($(':radio:checked').length === count) {
$('.step:nth-of-type(4)').hide().next().next().fadeIn();
}
});
});
As far as i was able to tell, the developer used css to hide the whole form area with display:none; and used the js above to split the questions to steps and show a certain number in each step.
You can see the code being called in the footer so there is no problem with the link to the .js file, also if you inspect the element and disable the display:none; that's declared for any of the divs within the hero-form all questions get displayed, so there is no problem with the form either, so why has it stopped working?
Would appreciate any help,
This line will no longer work with your mark-up...
$('.hero-form form .step:nth-of-type(2)').show();
There are a number of additional divs that wrap your mark-up, placed there by react, React has placed a series of div inside your form which are being hidden by your existing CSS (which I assume used to just be a series of STEP's)
The CSS that hides the nodes is :
.hero-form form>div, .hero-form form>.step {
display: none;
}
The nodes that are being hidden with display:none
<div data-reactid=".0.0:$1">
<div class="hs-richtext" data-reactid=".0.0:$1.0">
<hr>
</div>
<div class="step">
<div class="hs_patent field hs-form-field" data-reactid=".0.0:$1.$patent">
<label placeholder="Enter your Do you have a patent?" for="patent-9fc8dd30-a174-43bd-be4a-34bd3a00437e_2496" data-reactid=".0.0:$1.$patent.0">
<span data-reactid=".0.0:$1.$patent.0.0">Do you have a patent?</span>
<span class="hs-form-required" data-reactid=".0.0:$1.$patent.0.1">*</span>
</label>
<div class="hs-field-desc" style="display:none;" data-reactid=".0.0:$1.$patent.1">
</div>
</div>
Your JQuery will add display:block to the DIV with the class 'step' bit wont alter the parent DIV (inserted by React) which still prevents your node from being shown.
You need to alter you JQuery to call show() on the parent() that contains the "step" div you wish to show.
Please check your browser console ans see you have problem loading this form:
https://forms.hubspot.com/embed/v3/form/457238/9fc8dd30-a174-43bd-be4a-34bd3a00437e
and this is the error:
net::ERR_NAME_RESOLUTION_FAILED
It's better you change your DNS to something like 8.8.8.8 and see if the problem still exists or not.

JQuery Cookies with dynamic div ID's

I hope you guys can give me a push in the right direction as this problem has been eating me up all day now..
What I'm basicly trying to accomplish is this. I have several div's on a page that can be collapsed independently from eachother with the use of a button. Every div has it's own specific ID, generated with a string of static text, and a numeric value based on a auto-incremented database-value. This ensures I never have two div's with the same ID on one page. To target each specific div with Javascript (jQuery) I use the following code:
http://jsfiddle.net/LU7QA/0/
This works really well and does what it's supposed to do. Only there is one problem. On every page frefresh, every div that was opened is closed. Everything resets, and that's why I want to use JQuery Cookies in this construction. Only problem is, I know how it works, but I can't get it to work in this specific construction as it has to deal with a completely unique ID every time and needs to store the values of that particular ID.
As seen here: http://jsfiddle.net/LU7QA/1/
I tried to fiddle around with it but I can't seem to get it working properly and I'm starting to lose my sight on the problem..
<div>
<button class="button_slide" value="1">Show hide</button>
</div>
<div id="slidingDiv_1" class="slidingDiv">Stuff</div>
<div>
<button class="button_slide" value="2">Show hide</button>
</div>
<div id="slidingDiv_2" class="slidingDiv">Stuff</div>
function initMenu() {
$(".slidingDiv").hide();
// Toggle Field
$(".button_slide").click(function(){
//alert($(this).val()); debugging purposes
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
$(div_sliding_id).next().slideToggle('slow', function() {
$.cookie(div_sliding_id, $(this).is(':hidden') ? "closed" : "open");
return false;
});
});
$('.button_slide').each(function() {
var sliding_id = $(this).val();
div_sliding_id = '#slidingDiv_'+sliding_id;
if ($.cookie(div_sliding_id) == "open") $(this).next().show();
});
}
jQuery(document).ready(function() {initMenu();});
May you have missed a dot on the last *button_slide* declaration?
Btw, look at https://code.google.com/p/sessionstorage/

jQuery code behaves wrong

jQuery is not working the way it should and is completely ignoring the logic.
If I click a link, it shows up the given description, and fades the other menus.
If I click the same link again, it should hide that description, and fade the other links back in.
But instead it just hides the text, and doesn't fade them back in.
When running the code alone from the console and when you click on the whitespace next to the paragraphs, it works just fine.
Site for reference
jQuery:
$('a[class]').click(function(){
var clas = $(this).attr('class');
$('#'+clas.substring(0,2)).fadeTo('fast',1).removeClass('faded');
$('p:not(#'+clas.substring(0,2)+')').fadeTo('fast',0.3);
$('.ans:visible').toggle('slow');
$('#'+clas.substring(0,2)+'a'+':hidden').fadeIn('slow');
$('p:not(#'+clas.substring(0,2)+')').addClass('faded');
return false;
});
$('p:not(p.faded)').click(function(){
$('.ans:visible').toggle('slow');
$('p[class="faded"]').fadeTo('fast',1).removeClass('faded');
});
HTML:
<p id="q1">1. <a class="q1">Nem látom a kedvenc karakterem, hozzá tudod adni?</a>
<br>
<span id="q1a" style="display:none;" class="ans">
Persze. Írj egy e-mail-t a djdavid98#gmail.com címre a karakter nevével.
<br>
<span style="color:red">OC-kat és fillyket NEM adok hozzá.</span>
</span>
</p>
<p id="q2">2. <a class="q2">Hogyan tudok karaktert választani?</a>
<br>
<span id="q2a" style="display:none;" class="ans">
Látogass el a Karakterválasztás oldalra, ahol kiválaszthatod a kedvenced.
<br>
Haználhatod továbbá a "<i>Véletlenszerű karakter</i>" linket is.
</span>
</p>
<p id="q3">3. <a class="q3">Mi ennek az oldalnak a célja/alapötlete?</a>
<br>
<span id="q3a" style="display:none;" class="ans">
Eredetileg a milyennapvanma.hu weboldal pónisított változataként indult,
<br>
de azóta már nagy mértékben továbbfejlődött az oldal.
</span>
</p>
I admire your self-confidence: your code doesn't work so you assume the problem is with jQuery.
In your code, this statement:
$('p:not(p.faded)').click(function(){
...binds a click handler to any elements that don't have the "faded" class at that moment. Which would be all elements since none are faded initially. If you want it to apply only to elements that have not later had that class added you need to use a delegated handler which you assign via .on() (or .delegate() if using jQuery older than 1.7, or .live() if using a ridiculously old jQuery):
$(document).on('click', 'p:not(p.faded)'), function() {
Ideally you wouldn't bind the handler to document, you'd use the closest anscestor of the paragraphs in question, but since you haven't shown that much markup I'll leave that part to you.
Also though, you return false; from your click handler on the anchor elements, which prevents the click event from propagating up to the paragraphs anyway.
However, I think you're making the whole thing more complicated than you need to. The following code gets the job done:
var $questions = $('p'); // add class selectors here
$questions.click(function(){
var $this = $(this),
isOpen = $this.hasClass('open');
$this.fadeTo('fast',1).toggleClass('open',!isOpen)
.find('span.ans').toggle('slow');
$questions.not(this).fadeTo('fast', isOpen ? 1 : 0.2)
.removeClass('open')
.find('span.ans').hide('slow');
});
​
That is, when any paragraph is clicked, figure out whether it already has the answer open. Then make sure the clicked one is visible, and toggle its answer. Then take all of its sibling paragraphs and fade them in or out as appropriate and hide their answer.
Where I've put the comment "add class selectors here" it would be good to add a class to identify which paragraphs in your document are the questions.
Demo: http://jsfiddle.net/DxFDP/2
I would never use jQuery to apply styles to the code, but simple add and remove classes...
It will get messy, and sometime, we can simplify instead of complicate things.
here is simple example: http://jsbin.com/amiloc/1/
the same, but without <li>'s: http://jsbin.com/amiloc/3/
added colors so we know what's going on "under the hood", will let you judge by yourself.

Getting my head around jQuery

OK, I'm designing a site and thought I'd stick some jQuery in as I really need so js experience.
Page with my problem is here: http://new.focalpix.co.uk/moreinfo.php
JS in question is:
$(document).ready(function(){
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideUp('slow');
var id = $(this).attr('href');
$(id).slideDown('slow');
return false;
});
});
This works fine, but if you click on a link where the answer has already slid down, then it slides up, then back down again.
I'm not sure on the cleanest way to stop this happening - any ideas?
You should be using the .slideToggle() effect.
$(document).ready(function() {
$(".answer").css("display","none");
$("#maincontent a.animate").click(function() {
$("#maincontent .answer").slideToggle('slow');
});
});
First, I'd suggest the following structure for your faq's:
<div id="faq">
<div class="qa" id="faq_greenandflies">
<span class="q">What is green and flies</span>
<div class="a">
Super Pickle!
</div>
</div>
<div class="qa" id="faq_redandbadforteeth">
<span class="q">What is Red and bad for your teeth</span>
<div class="a">
a Brick
</div>
</div>
<!--
More FAQ's here
-->
</div>
and then defining your jQuery as follows:
<script type="text/javascript">
$(function(){
// hide all answers
$('div#faq .qa .a').hide();
// bind a click event to all questions
$('div#faq .qa .q a').bind(
'click',
function(e){
// roll up all of the other answers (See Ex.1)
$(this).parents('.qa').siblings().children('.a').slideUp();
// reveal this answer (See Ex.2)
$(this).parents('.qa').children('.a').slideDown();
// return true to keep any other click events
return true;
});
// check location.hash to see if we need to expand one (direct link)
$(location.hash).find('.q a').click();
});
</script>
Explanation:
(Ex.1)
this is the link that was clicked
get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
select all of its siblings. (we now have all qa's as a jQ object)
hide the answers
(Ex.2)
this is the line or link that was clicked
get the element that contains this and has a class of 'qa' (the box that contains both question and answer)
reveal the answer
A working demo is here.
This does several things for you:
If a user deep-links to an answer, the answer is automatically revealed
If a user clicks on one answer, all other answers are hidden
You can give your divs proper ids, so which helps search engine optimization of links to individual answers
Use slideToggle() like Soviut said, but just as a tip -- you can declare the display property in the actual CSS file instead of declaring it inside the javascript. jQuery will pick up on the fact that it is hidden in the stylesheet and still perform the appropriate slide function.
You can also use $(".answer").hide();
Instead of setting the display CSS property. Just thought I would let you know.
try using the one method, something like:
$(selector).one('effect', 'data for effect', callback function);
it makes sure an effect only happens once per element.

Categories