I have this code that is supposed to create a new list item (li) that is editable (contenteditable="true"):
var currenthtml = document.getElementById("0").innerHTML;
var newhtml = currenthtml + '<li class="object" contenteditable="true">...</li>';
The object is created and visible, the purehtml for #0 after editing is:
<div id="0">
<li class="object" contenteditable="true">First object</li>
</div>
To save the content, I have the following helper:
function SaveObject(html) {
localStorage.setItem("obj", html);
}
which is supposed to be called because of:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
SaveObject(html);
return false;
}
});
(I'll change it to save on other cases, but this is the current saving method.)
but when I edit a new item and try to save, it is not saved the text. It stays there temporarily, but then changes to the default "...". How can I make this work?
The #0 is set this way
if(localStorage.getItem("obj") != null) {
document.getElementById("0").innerHTML = localStorage.getItem("obj");
}
Well, there's several steps you should check:
in your keydown handler, check the value of html:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
console.log(html); // is the value equal to what is expected?
SaveObject(html);
return false;
}
});
Second, try to check if it is saved to local storage directly after you have saved:
$('li[contenteditable]').keydown(function(e) {
if (e.keyCode === 13) {
document.execCommand('insertHTML', false, '');
$(this).blur();
var html = document.getElementById("0").innerHTML;
SaveObject(html);
console.log(localStorage.getItem("obj")); // is the value equal to what was saved?
return false;
}
});
If the two answers are "yes", check out the value after reloading of your page: just type localStorage.getItem("obj") in your console.
Finally, if the data is still there, make sure that you actually add it back to DOM. You haven't shown us the code which adds list items with the saved data to the page.
Related
So I have a button that whenever clicked appends whatever the user entered below the input field. I want to make it so when clicked with an empty field nothing appends (essentially the function does not run).
Here is my code:
var ingrCount = 0
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
var ingredientSpace = $("<p>");
ingredientSpace.attr("id", "ingredient-" + ingrCount);
ingredientSpace.append(" " + ingredientInput);
var ingrClose = $("<button>");
ingrClose.attr("data-ingr", ingrCount);
ingrClose.addClass("deleteBox");
ingrClose.append("✖︎");
// Append the button to the to do item
ingredientSpace = ingredientSpace.prepend(ingrClose);
// Add the button and ingredient to the div
$("#listOfIngr").append(ingredientSpace);
// Clear the textbox when done
$("#ingredients").val("");
// Add to the ingredient list
ingrCount++;
if (ingredientInput === "") {
}
});
So I wanted to create an if statement saying when the input is blank then the function does not run. I think I may need to move that out of the on click function though. For the if statement I added a disabled attribute and then removed it when the input box contains something. But that turns the button another color and is not the functionality I want. Any ideas I can test out would help. If you need any more information please ask.
If you're testing if ingredientInput is empty, can you just return from within the click event?
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if(ingredientInput === '') { return; }
// rest of code
Simply use :
$("#addIngrButton").on('click', function() {
var ingredientInput = $("#ingredients").val().trim();
if (ingredientInput.length == 0) {
return false;
}
// ..... your code
var container = document.createElement("lastExp");
container.innerHTML = 'html code new form field';
document.getElementById("lastExp").appendChild(container);
It's simple i click button extra form field is added.
Question: When i refresh page how to not lose this extra fields on my form.
Stack Overflow is not the place to write code, but this will sits here in case someone besides OP need.
It's a minimal example--getting started--with localStorage. As I mentioned, under the hood, you have to append that element every time the page is loaded.
The snippet won't work here, unfortunately because the iframe is sandbox'd. Head over to my hub to experiment it.
var container = document.getElementById('container'),
toggle = document.getElementById('toggle');
element = null;
// initial check
init();
// add click event and listen for clicks
toggle.onclick = function() {
// both cases will update localStoage _inputIsThere
// if element is null -- doesn't exists, then add it
if (element == null) {
add();
} else {
// remove the element
remove();
}
}
// check if key exists in localStorage; this is where all the "magic" happens.
function init() {
var exists = localStorage.getItem('_inputIsThere');
if (exists && exists == 'true') {
add();
}
}
function remove() {
element.remove();
element = null;
// update key in localStorage to false
localStorage.setItem('_inputIsThere', false);
}
// adds the input and updates
function add() {
var e = document.createElement('input');
e.type = 'text';
element = e;
container.appendChild(e);
// update key in localStorage to true
localStorage.setItem('_inputIsThere', true);
}
<button id="toggle">Add/Remove</button>
<div id="container"></div>
I want to make the checkbox work more or less like a radio button in this instance. This is what I have so far. I would like to be able to do this in the treeCheckboxClicked() function so that it would just uncheck all the remaining checkboxs then check the one that was selected.
buildTocTree: function (cp1) {
var self = this;
var toc = new TOC({
checkboxes: false,
enableDelete: true,
deleteRecursive: true,
showRoot: false,
checkBoxes: false,
}, self._viewId + '_tocTree');
toc.on("checkBoxClick", dojo.hitch(this, "treeCheckboxClicked"));
},
treeCheckboxClicked: function (e) {
if (e.checked) {
if (e.subLayers || e.name === 'GISLayer')
this.selectedLayerValue('');
else if (e.layerInfos)
this.selectedLayerValue('');
else
this.selectedLayerValue(e.name);
if (this.selectedLayerValue() != '')
this._selectedGISSourceLayer = e;
else
this._selectedGISSourceLayer = '';
}
}
Without knowing the internal details of the TOC widget, especially its DOM, it's difficult to know how to query all checkboxes within its template. Assuming your treeCheckboxClicked is already getting called, and e.target is the checkbox element itself, the following code should get you close to your desired functionality:
if (e.checked) {
query('checkbox', self.domNode).forEach(function (checkbox) {
checkbox.checked = checkbox != e.target;
});
//...
}
Note: This assumes the dojo/query module has been loaded.
Are you using agsjs.TOC? They have a handler included to do this for you. In the examplesat http://gmaps-utility-gis.googlecode.com/svn/tags/agsjs/latest/examples/toc.html they toggle the function off and on with a button, but you can make it default on and include the following snippet in your tree declaration. (replace DynaLayer 1 with your layer)
toc.on('toc-node-checked', function(evt){
// when check on one layer, turn off everything else on the public safety service.
if (evt.checked && evt.rootLayer && evt.serviceLayer && evt.rootLayer == dynaLayer1){
evt.rootLayer.setVisibleLayers([evt.serviceLayer.id])
}
I have turned on allowedContent property in config.
config.allowedContent = "true"
This allows me to add ids to paragraphs inside contenteditable div.
However, now whenever I hit enter key inside the contenteditable div a new paragraph with same id is generated. I would assume after hiiting enter key a new paragraph should be inserted without any ids but it looks like the ids are copied from previously generated paragraph.
Is there any way to avoid this?
Try this. It's not bullet proof but works well enough. Even though I wrote it, I kind of hate it so if you improve on it, please share the love ;)
editor.on('key', function (evt) {
// Only if editor is not in source mode.
if (editor.mode === 'source') { return; }
// Enter is keyCode 13
if (evt.data.keyCode === 13) {
// if we call getStartElement too soon, we get the wrong element sometimes
setTimeout(function () {
var selection = editor.getSelection();
if (typeof selection === 'undefined') { return; }
var startElement = selection.getStartElement();
// If there are spans nested in the paragraph preserve them
// And we need to find the parent paragraph
// This could be optimized...
if (startElement.getName() == 'span') {
var text = "";
while (startElement.getName() == 'span') {
text += startElement.getHtml();
startElement = startElement.getParent();
}
if (text.length === 0) {
startElement.setHtml(' ');
} else {
startElement.setHtml(text);
}
}
// HERE I remove the "id" attribute.
startElement.removeAttribute("id");;
}, 10);
}
});
I have here script for Enabled and Disabled submit button. I tried to use each function but isn't working. Every fields had it's value from database. The process should not allowed to submit if one of the fields was empty. Every fields has a value because I used it for editing window. Any help will appreciate. Thanks..
And this my fiddle http://jsfiddle.net/cj6v8/
$(document).ready(function () {
var saveButton = $("#save");
var empty = true;
$('input[type="text"]').change(function () {
$('.inputs').each(function () {
if ($(this).val() != "") {
empty = false;
} else {
empty = true;
}
});
if (!empty) {
saveButton.prop("disabled", false);
} else {
saveButton.prop("disabled", true);
}
});
}); // END OF DOCUMENT READY
The problem is the first else statement.
When $('.inputs').each(... iterates through your fields the empty variable is re-assigned a new value for every input field. In other words, the way you did it, only the last field was significant. (To test it, try this: leave the last one empty, and the button will be disabled, no matter what you put in the first two fields.)
Instead, try initializing empty at false just before the loop (you assume your fields are all filled with something), and then, when you iterate, as soon as you come across an empty field, set empty to true.
var empty = false;
$('.inputs').each(function() {
if($(this).val() == "")
empty = true;
});
As you can see, I removed the problematic else.
you need to init empty to false and cange it only if you find empty inputs inside to loop. http://jsfiddle.net/cj6v8/1/
If you don't want to submit when at least one field is empty you'll need to do this:
....
var empty = true;
$('input[type="text"]').change(function () {
empty = false;
$('.inputs').each(function () {
if ($(this).val() == "") {
empty = true;
break;
}
}
...
each is asynchronous, http://jsfiddle.net/cj6v8/4/
$(document).ready(function() {
var saveButton = $("#save");
$('input[type="text"]').change(function() {
var empty = true;
var inputs = $('.inputs');
inputs.each(function(i) {
if ($(this).val().length == 0) {
console.log($(this).val());
empty = false;
}
if (i === inputs.length-1) saveButton.attr("disabled", !empty);
});
});
});// END OF DOCUMENT READY