Hide DIV when input field is blank - javascript

I wonder if you could help me with an issue.
I am building a content template for an events page, that pulls data through using Advanced Custom Fields.
I have a field in the admin side which will be filled out when adding a new event. The field is called show_info with the ID #acf-editor-46.
On some events however this will be left blank, but the DIV that wraps around the content on the frontend will still show on the template, the DIV has the class .show-info-wrapper.
I would like it so when the show_info field is blank, the DIV .show-info-wrapper does not display on the front end.
I have made some progress from browsing around, you can see the code I have so far here:
HTML (Just a quick testing set up):
<textarea id="acf-editor-46" class="wp-editor-area" aria-hidden="true">1111</textarea>
<div class="show-info-wrapper">CONTENT</div>
JavaScript + jQuery:
$(document).ready(function() {
if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}
$('#acf-editor-46').on('change' , function() {
if( this.value != ''){
$('.show-info-wrapper').show();
}
else{
$('.show-info-wrapper').hide();
}
});
});
It works on JSFiddle (http://jsfiddle.net/ha2nedfb/), however, it seems that on my WordPress site as the input and the DIV are not on the same DOM, it does not work.
Could anyone help me with this?
Thank you!

Just change the event of #acf-editor-46 to input.
$(document).ready(function() {
if($('#acf-editor-46').val() == '' ){$('.show-info-wrapper').hide();}
$('#acf-editor-46').on('input' , function() { // Just change event to input
if( this.value != ''){
$('.show-info-wrapper').show();
}
else{
$('.show-info-wrapper').hide();
}
});
});

if (!$("#acf-editor-46").val()) {
// textarea is empty
}
try this to check textarea is empty or not

You can delegate event if textarea is rendered later.
$(document).on('change', '#acf-editor-46', callback);
Links:
https://api.jquery.com/on/
https://learn.jquery.com/events/event-delegation/

Assuming the <textarea> and <div> are really siblings in this very order (your text contradicts the example) & if you're OK with adding a placeholder to the textarea & you only need new-ish browsers, there is a pure CSS solution:
<textarea ... placeholder=" "> </textarea>
.show-info-wrapper {
display: block;
}
.wp-editor-area:placeholder-shown + .show-info-wrapper {
display: none;
}
Here's a pen.

Related

How to hide form fields with Jquery in Shopify

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).

Enabling input text on page load based on span value

I have a web page which consist of a <span> element and <input> element.
My requirement is to dynamically enabling/disabling the <input> element based on <span> innerHTML.
I have written following javascript:
var vale=document.getElementById("SPAN_ID").innerHTML;
But value is coming as undefined,since I guess at page loading span element is yet to be constructed.I have to perform this operation on page loading time only.Can anyone provide any suitable javascript code for this??
You can use the DOMContentLoaded event to wait for the HTML to be fully loaded and parsed before running your code:
<script>
document.addEventListener('DOMContentLoaded', function () {
var value = document.getElementById("the-span").innerHTML;
if (value) {
document.getElementById('the-input').disabled = false;
}
}, false);
</script>
<span id="the-span">Hi, I'm the span</span>
<input id="the-input" value="I'm the input" disabled>
If you delete the text inside of the span element, and re-run the snippet, you'll see that the input box remains disabled.
If page load is indeed your problem
If you are using jquery, paste the code inside
$(document).ready(function() {
});
If you are using plain js then
window.onload = yourfunctioncomeshere
Try this if your are using jquery:
$(document).ready(function() {
var spanText = $('#SPAN_ID').text();
//based on var spanText value you can disable/enable input
//To disable input
$('#INPUT_ID').attr({
'disabled': 'disabled'
});
// To enable input
if ($('#INPUT_ID').attr('disabled')) {
$('#INPUT_ID').removeAttr('disabled');
}
});

Inline CKEditor adds <br> to empty div on startup

CKEditor in Inline mode adds a <br> in the source of the document to an empty div when it is initialized. When you check the source in CKEditor it shows completely empty. I guess this is done to stop collapsing the div or whatever element it is editing on, but for me this is causing issues since I target the empty div with CSS to display a placeholder.
I have searched about everywhere on how to disable this and have seen some issues with FireFox many years ago, but that seems to be unrelated.
<div id="editarea" placeholder="Title"></div>
CKEDITOR.inline('editarea, {});
<style>
div:empty:after {
content: attr(placeholder);
}
</style>
When you look in the Developer Tools the source of the document looks like:
<div id="editarea" placeholder="Title">
<br>
</div>
Adding the following to the config does not seem to be doing anything:
config.fillEmptyBlocks = false;
Can help someone else, the solution I found, pass by the editor event listener:
// Ckeditor 4
editor.on('key', function (evt) {
var selection = editor.getSelection();
var element = selection.getStartElement();
var html = element.getHtml();
var id = element.getId();
if (evt.data.keyCode !== 13
&& id === 'editarea')) {
if (html.match(/( )?<br>$/)) {
element.setHtml('');
}
}
})
That <br> is a "filler" and is always placed at input (editor initialization) into empty block elements by function createBogusAndFillerRules to give an height to the element so the user can click on it to edit it.
Actually there is not a CKeditor configuration to avoid this behaviour but, using jQuery, we can remove the <br> on instanceReady.ckeditor event with:
if($(this).html().trim() === '<br>'){
$(this).html('');
}
Please try this code it is working for me:
For removing br on load
$('your_id').ckeditor();
CKEDITOR.on('instanceReady', function() {
$('div.application').find('br').remove(); // remove br tag added on empty divs
});
for removing &nbsp use this in destroy function:
for(CKname in CKEDITOR.instances) // delete multiple instances of ckeditor
{
CKEDITOR.instances[CKname].destroy(function(){
$("your_id").html(function (i, html) {
return html.replace(/ /g, ''); // remove
});
})
}

Radio Button "Select" Toggle issue

I am trying to make a very very simple script that checks to see if a certain radio button option is clicked, and if so, shows another set of fields (this works fine), but if you unselect that radio button option, it hides the extra set of fields (seemingly simple, but does not work for me!)
Also I am newish to JS/JQuery so debugging this has been a struggle! Thanks for any help :)
My HTML radio button that triggers the fields display - imagine there are 6 other radio button options with this (each classed with [class="otherFund"]).
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" onclick="set_item('DOP-Relief-Fund', 8)" onchange="relief_fund_handler()" />
Here is the text and field and I want to toggle with the above button's selection
<p id="Earmark1" style="display: none;">
<strong>Please designate below what relief fund you would like your <em>DOP Charitable Relief</em> donation to go towards (see bulleted examples above).</strong><br />
<strong>Earmarked for <span class="required">*</span>:</strong><input type="text" name="Earmark1" id="Earmark1" size="50" />
</p>
And here are my JS attempts...
Attempt 1:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else if (".otherFund".checked) {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 2:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 3:
$("#Relief1:checked")(
function() {
$('#Earmark1').toggle();
}
);
On attempt #3, I have also replaced the :checked with .click, .select, .change and none have worked... Thanks for any help! :)
Try this:
$("input.otherFund").change(function() {
$('#Earmark1').toggle($(this).attr('id') == 'Relief1');
});​
Try removing all of the events off of the radio button like this:
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" />
And using the following jquery script:
​$(function(){
$("#Relief1").change(function(){
$(this).is(":checked") ? $("#Earmark1").show() : $("#Earmark1").hide();
});
});​
You could iterate through each radio button and assign an event handler to each radio button, so when selected it shows the other fields and when deselected it hides the other fields. The code below may help you arrive at the correct answer.
// Iterate the radio buttons and assign an event listener
$('input[name="ItemName1"]').each( function() {
// Click Handler
$(this).live('click', function() {
// Check for selected
if ( $(this).is(':checked') )
{
$('#EarMark1').show();
}
else
{
$('#EarMark1').hide();
}
});
});
It's not perfect, nor is it the most elegant solution. With some tweaking it should point you in the right direction.
thank you to everyone!!! I ended up using kennypu's example - the ":checked" seemed to work fine even though it is a radio button. I had to make some tweaks to it, and ended up with 2 separate functions instead of the "else". For some reason the other examples were not working for me - although I highly doubt it has to do with your code, and likely has to do with other things going on in the page. Since we're using an external form/database handler, we need to keep the events and other code there.
Here's what ended up working..
$(function(){
$("#Relief1").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").show();
}
});
});
$(function(){
$("#Radio1, #Radio2, #Radio3, #Radio4, #Radio5, #Radio6, #Radio7").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").hide();
}
});
});
Pretty clunky, but I got it to work how I needed. Thank you to everyone who contributed, it helped quite a bit.
Try:
<script>
var r=$('input[name="ItemName1"]).is(:checked);
if(r)
{
alert("Item is checked");//replace with any code
}
</script>
if you're already using jQuery, this is simple as using .show() and .hide():
$('#Relief1').on('change',function() {
if($(this).is(':checked')) {
$('#Earmark1').show();
} else {
$('#Earmark1').hide();
}
});
example fiddle: http://jsfiddle.net/x4meB/
also note, don't use duplicate ID's, they are meant to be unique (in this case, you have a dulpicate #Earmark1 for the p tag and span). Also, in the example fiddle, I changed it to a checkbox instead of a radio since You can't uncheck a radio if there is only one option.

Javascript detect scrollbar in textarea

I was wondering if anybody knows how I would go about detecting when the scrollbar appears inside a textarea.
I am currently using mootools for my JavaScript and I am having issues getting it to detect a scrollbar.
function has_scrollbar(elem_id)
{
const elem = document.getElementById(elem_id);
if (elem.clientHeight < elem.scrollHeight)
alert("The element has a vertical scrollbar!");
else
alert("The element doesn't have a vertical scrollbar.");
}
See this jsFiddle http://jsfiddle.net/qKNXH/
I made a jQuery "compatible" version of Tommaso Taruffis code
function resize_until_scrollbar_is_gone(selector) {
$.each($(selector), function(i, elem) {
while (elem.clientHeight < elem.scrollHeight) {
$(elem).height($(elem).height()+5);
}
});
}
It can handle multiple elements and accepts: selectors, jQuery objects, or DOM elements.
It can be called like this:
resize_until_scrollbar_is_gone('textarea');
Tommaso's solution works perfectly, even with a text area. But if the user were to type in the textarea and suddenly the textarea gave itself a scrollbar, your javascript wouldn't know or be triggered.So you might want to add something like
onKeyUp='has_scrollbar("textareaID")'
For React I've found https://github.com/andreypopp/react-textarea-autosize
import Textarea from 'react-textarea-autosize';
...
<Textarea maxRows={3} />

Categories