regain html after emptying it using jquery? - javascript

I have an if/else loop inside my jQuery. I need to hide HTML on my text box inside my if portion and regain it at my else part. How can I do this using jQuery?
if (test == 1) {
$(#id).html(""); //code to hide html
} else {
//code to regain
}
code to hide html will works fine,but how to regain the code after emptying it?

you can't regain lost HTML unless you have saved it somewhere,
you can either show/hide the element
if(test==1){
$(#id).hide();
}
else{
$(#id).show();
}
or you can store the values somewhere in a variable
var html = "";
if (test == 1) {
html = $(#id).html();
$(#id).html( "" );
} else {
$(#id).html( html );
}
or set it to localstorage (if you browser supports it)
if (test == 1) {
localStorage.setItem("savedHTML", $(#id).html()) ;
$(#id).html( "" );
} else {
$(#id).html( localStorage.getItem( "savedHTML" ) );
}

You can assign the complete html inside your div to a variable.
var htmlContent = $(#id).html();
Then in your else, you can assign it back.
$(#id).html(htmlContent);

Related

javascript that hides/shows element based on criteria not working with style.display = "none"

I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>

js on change event getting looped in js confirm

I have a flip toggle button().I am writing a function on change of toggle button,on change I am declaring js confirm box ,if confirms true the button remains in changed state,else it will revert in its previous state.My issue is the function is getting iterating(looping).Please suggest
To me it looks quite ok. Maybe you just forgot to encapsulate your code in $(document).ready - this is necessary because otherwise your Javascript function will be loaded before the HTML DOM has been loaded - so your function will fail to access the DOM elements.
$(document).ready(function() {
$("#btn").on("change", function() {
var txt;
var btnStatus = $("#btn").val();
console.log("btnstataus>>>>>" + btnStatus);
var r = confirm("Are you sure to change?");
if (r == true) {
if (btnStatus == "on") {
$("#btn").val("on");
} else {
$("#btn").val("off");
}
} else {
if (btnStatus == "on") {
$("#btn").val("off");
} else {
$("#btn").val("on");
}
}
});
});
Here is a working sample of your code:
https://plnkr.co/edit/AdzcN04F1fsLe9xw454j?p=preview

TinyMCE validation gives error: Cannot call method 'getContent' of undefined

I have a text area with tiny mce, I load it like this:
$(document).ready(function () {
tinyMCE.init({
mode: "textareas",
...
This text area is in a form. I bind forms submit button to:
$('#btnSubmit').click(function() {
tinymce.triggerSave();
var editorContent = tinyMCE.get('Description').getContent();
if (editorContent == '' || editorContent == null)
{
$(tinymce.activeEditor.getBody()).css("background-color", '#ffeeee');
$(tinymce.activeEditor.getBody().parentNode).css("background-color", '#ffeeee');
$(tinymce.activeEditor.getBody().parentNode).css("border", '1px solid #ff0000');
}
});
In my entity class I have Required attribute.
My goal is to make tinyMCE background red when model is not valid. But I get error from ti question title.
Any help?
So, validation works. If I remove textarea empty check and leave color changing it changes. But the problem is when there is something in text area and I click submit area first become red and then submit.
Is there maybe some fubction where I can do something if validation fail?
It sounds to me just like an undefined object error - where the code can't resolve this line tinyMCE.get('Description').getContent();.
You seem to be mixing between using activeEditor sometimes and other times not, so instead I've standardised the code so you are always relying on activeEditor - this means I've removed the line that was triggering the error. You also seem to switch between using tinymce and tinyMCE which might not be causing problems but is best to be avoided... so I've standardised that as well.
Without seeing more of the way the rest of the code and markup is set-up however it's a bit difficult to tell exactly what is going on. Does my change repair the problem?
$('#btnSubmit').click(function() {
tinyMCE.triggerSave();
var editorContent = tinyMCE.activeEditor.getContent();
if (editorContent == '' || editorContent == null)
{
$(tinyMCE.activeEditor.getBody())
.css("background-color", '#ffeeee')
.parent()
.css({
"background-color": '#ffeeee',
"border": '1px solid #ff0000'
});
}
});
If you do not have control over init method of TinyMCE then, you can follow this solution.
jQuery(document).ready(function($) {
function myCustomSetContent( id, content ) {
// Check if TinyMCE is defined or not.
if( typeof tinymce != "undefined" ) {
var editor = tinymce.get( id );
// Check if TinyMCE is initialized properly or not.
if( editor && editor instanceof tinymce.Editor ) {
editor.setContent( text );
editor.save( { no_events: true } );
} else {
// Fallback
// If TinyMCE is not initialized then directly set the value in textarea.
//TinyMCE will take up this value when it gets initialized.
jQuery( '#'+id ).val( text );
}
return true;
}
return false;
}
function myCustomGetContent( id ) {
// Check if TinyMCE is defined or not.
if( typeof tinymce != "undefined" ) {
var editor = tinymce.get( id );
// Check if TinyMCE is initialized properly or not.
if( editor && editor instanceof tinymce.Editor ) {
return editor.getContent();
} else {
// Fallback
// If TinyMCE is not initialized then directly set the value in textarea.
// TinyMCE will take up this value when it gets initialized.
return jQuery( '#'+id ).val();
}
}
return '';
}
$(".class-to-update-content").on("click", function(e) {
myCustomSetContent( "tinymce-editor-id", "New Content in Editor" );
});
$(".class-to-get-content").on("click", function(e) {
$("div.class-to-display-content").html( myCustomGetContent( "tinymce-editor-id" ) );
});
});
Ref : http://blog.incognitech.in/tinymce-undefined-issue/

Disable Select based on another element on the Same Row

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Showing a div element dependent on if it has content

With jQuery I am trying to determine whether or not <div> has content in it or, if it does then I want do nothing, but if doesn't then I want to add display:none to it or .hide(). Below is what I have come up with,
if ($('#left-content:contains("")').length <= 0) {
$("#left-content").css({'display':'none'});
}
This does not work at all, if the div has not content then it just shows up anyway, can any offer any advice?
Just use the :empty filter in your selectors.
$('#left-content:empty').hide();
if( $( "#left-content" ).html().length == 0 ) {
$( "#left-content" ).hide();
}
try to remove first whitespaces:
// first remove whitespaces
// html objects content version:
var content = $.trim($("#left-content).html()).length;
if(content == 0) {
$("#left-content).hide();
}
// html RAW content version:
var content = $.trim($("#left-content).html()); // <-- same but without length
if(content == "") { // <-- this == ""
$("#left-content).hide();
}

Categories

Resources