Javascript localStorage contact with checkbox - javascript

I have a settings panel on which there is a checkbox that is responsible for auto-theme change on off. The first problem is that this checkbox does not allow to be changed(I see a function triggered). The second problem Is that I want on every reload the value (true or false) to be returned and set to the checkbox. How to fix this issues?
TimeSch(localStorage.getItem("'TimeSch'"));
function TimeSch(a) {
if (a) {
document.getElementById('TimeSch').checked = 'true';
console.log('True start');
Set('TimeSch', true);
$('#theme').prop('disabled', true);
const hours = new Date().getHours();
const isDayTime = hours > 6 && hours < 20;
if (isDayTime) {
theme('White');
console.log('Auto White');
} else {
theme('Dark');
console.log('Auto Dark');
}
} else {
document.getElementById('TimeSch').checked = 'false';
console.log('False start');
$('#theme').prop('disabled', false);
Set('TimeSch', false);
}
}
function Set(name, value) {
if (typeof Storage !== "undefined") {
localStorage.setItem("'" + name + "'", value);
} else {
console.log('No localStorage supported. Oh, please chage your browser!');
}
}
https://codepen.io/abooo/pen/PVQaWB

First thing, on line 4 and line 18 use boolean
document.getElementById('TimeSch').checked = true;
Secondly, you don't need to add quotes for localStorage keys. Simply do:
localStorage.setItem(name, value);
localStorage.getItem("TimeSch")
Finally the problem is line 3: The value coming from localStorage is string, so the condition will always be true. Change this to:
if (a === "true" || a === true)
and it should work.
Link to these changes: https://codepen.io/anon/pen/dadjGq?editors=1111

There are multiple issues with your code snippet:
there's no implementation of the theme() function
input[type="checkbox"] is inside of the select element, which is invalid markup, also they get enabled/disabled simultaneously
css for input[type=checkbox]:after doesn't take into account the state of the checkbox, so it always will show only x
to set the property of the element you do not need jQuery
to check the checkbox through JS you should give it Boolean, not the string
why would you do this: localStorage.setItem("'" + name + "'", ...? consider using: localStorage.setItem(name, ... directly
It is still not clear what you are trying to achieve in general, but I made some patches and at least it got somewhat alive: https://codepen.io/anon/pen/OdQEvr

Related

Check if selection contains link

I am creating a rich text editor and I would like to use the same button to link and unlink selections.
document.execCommand('createLink'...) and document.execCommand('unlink'...) allow users to link and unlink window.getSelection().toString().
However, there are no inbuilt methods to determine whether a selection is linked or not in the first place, so my question is: How can you check whether or not a selection is linked?
I have tried using document.queryCommandState('createLink') and document.queryCommandState('unlink'), but both queries always return false, even though, for example, document.queryCommandState('bold') works properly.
I found the following piece of code, which works well enough for the time being, kicking around on SO:
const isLink = () => {
if (window.getSelection().toString !== '') {
const selection = window.getSelection().getRangeAt(0)
if (selection) {
if (selection.startContainer.parentNode.tagName === 'A'
|| selection.endContainer.parentNode.tagName === 'A') {
return [true, selection]
} else { return false }
} else { return false }
}
}
You also may be able to retrieve the link HTML element and pass it to Selection.containsNode()
const linkHtmlElement = document.getElementById('yourId');
// should return true if your linkHtmlElement is selected
window.getSelection().containsNode(linkHtmlElement)
You need to check the anchorNode and focusNode text nodes to see if they are a elements. More details on MDN
function isLink () {
const selection = window.getSelection()
const startA = selection.anchorNode.parentNode.tagName === 'A'
const endA = selection.focusNode.parentNode.tagName === 'A'
return startA || endA
}

How can I capitalize field text values at OnChange in MS CRM 2015?

I'm fairly new to CRM development and I'm trying to customize my account form to Capitalize any text field at onChange. I'm currently working with this function that I found online:
function UpperCaseField(fieldName)
{
var value = Xrm.Page.getAttribute(fieldName).getValue();
if (value != null)
{
Xrm.page,getAttribute(fieldName).setValue(value.toUpperCase());
}
}
However, when I change a value in my test account it tells me that the method getValue() is not supported. Everything I've found tells me to use getValue(). Im at a loss.
Any help would be appreciated.
Thanks
If you're getting a getValue is not supported error, double check that the value for fieldName is actually a field on the form. It's best to code more defensively, like this:
function UpperCaseField(fieldName)
{
var attr = Xrm.Page.getAttribute(fieldName);
if (!attr) {
console.log(fieldName + " not found");
return;
}
var value = attr.getValue();
if (value != null)
{
attr.setValue(value.toUpperCase());
}
}
Update: When you connect your fields to JS functions via the form editor, CRM passes an event context as the first parameter. Here's what the code would look like in that case:
function UpperCaseField(context)
{
var fieldName == context.getEventSource().getName();
var attr = Xrm.Page.getAttribute(fieldName);
if (!attr) {
console.log(fieldName + " not found");
return;
}
var value = attr.getValue();
if (value != null)
{
attr.setValue(value.toUpperCase());
}
}
Here's more info about the context: https://msdn.microsoft.com/en-us/library/gg328130.aspx
Replace line
Xrm.page,getAttribute(fieldName).setValue(value.toUpperCase());
with line
Xrm.Page.getAttribute(fieldName).setValue(value.toUpperCase());
Also please provide a screenshot that shows how you use/register this handler.

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

ComboBox typeAhead works but valueField is null under certain behavioral conditions

Requesting a sanity check here please...
ExtJS 4.2 comboBox Typeahead works but having issues retrieving the valueField under the following conditions:-
1) If a user types a value and then instead of hitting enter or clicking on the select combo list, they click elsewhere then the valueField is empty but the selected value is present.
2) Assuming that the combobox item was selected correctly, If I enter an additional character and then backspace that character, the combo box can no longer find the valueField..its almost like it has reset itself.
Fiddle example
https://fiddle.sencha.com/#fiddle/je1
How to reproduce
If you enter Maggie in the combo box, you will see the valueField ID in the console window, if you append a character and then backspace the character, the ID in the console window is null
(You will need to open the console window to see the output)
forceSelection does not resolve this issue as I have a template and it will not accept an entry in the combobox that is not part of the store, and I need to use sumID for my valueField as I need to retrieve and pass that value to the server.
Thank you everyone, awesome to have such a great community!!
I was able to get around this by using forceSelection and overriding the setValue thus allowing template items not in the store but in the combo to be selected via forceSelection. From playing around with the combobox, IMO, for a good look and feel, forceSelection is the way to go.
Here is my override, refer to statement //start of override
This was a quick fix, I will refine statement when I am back in the office, below I am pasting the solution from memory, you get the idea.
setValue: function(value, doSelect) {
var me = this,
valueNotFoundText = me.valueNotFoundText,
inputEl = me.inputEl,
i, len, record,
dataObj,
matchedRecords = [],
displayTplData = [],
processedValue = [];
if (me.store.loading) {
// Called while the Store is loading. Ensure it is processed by the onLoad method.
me.value = value;
me.setHiddenValue(me.value);
return me;
}
// This method processes multi-values, so ensure value is an array.
value = Ext.Array.from(value);
// Loop through values, matching each from the Store, and collecting matched records
for (i = 0, len = value.length; i < len; i++) {
record = value[i];
if (!record || !record.isModel) {
record = me.findRecordByValue(record);
}
// record found, select it.
if (record) {
matchedRecords.push(record);
displayTplData.push(record.data);
processedValue.push(record.get(me.valueField));
}
// record was not found, this could happen because
// store is not loaded or they set a value not in the store
else {
//start of override
// 'Select All Names' is the template item that was added // to the combo box, it looks like an entry from the store
// but it is not in the store
if (me.forceSelection && me.getDisplayValue() === 'Select All Names'){
processedValue.push(value[i]);
dataObj = {};
dataObj[me.displayField] = value[i];
displayTplData.push(dataObj);
}
//end of override
if (!me.forceSelection) {
processedValue.push(value[i]);
dataObj = {};
dataObj[me.displayField] = value[i];
displayTplData.push(dataObj);
// TODO: Add config to create new records on selection of a value that has no match in the Store
}
// Else, if valueNotFoundText is defined, display it, otherwise display nothing for this value
else if (Ext.isDefined(valueNotFoundText)) {
displayTplData.push(valueNotFoundText);
}
}
}
// Set the value of this field. If we are multiselecting, then that is an array.
me.setHiddenValue(processedValue);
me.value = me.multiSelect ? processedValue : processedValue[0];
if (!Ext.isDefined(me.value)) {
me.value = null;
}
me.displayTplData = displayTplData; //store for getDisplayValue method
me.lastSelection = me.valueModels = matchedRecords;
if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
inputEl.removeCls(me.emptyCls);
}
// Calculate raw value from the collection of Model data
me.setRawValue(me.getDisplayValue());
me.checkChange();
if (doSelect !== false) {
me.syncSelection();
}
me.applyEmptyText();
return me;
},
Look at the sources of Combobox and try override this method as follows
doLocalQuery: function(queryPlan) {
var me = this,
queryString = queryPlan.query;
if (!me.queryFilter) {
me.queryFilter = new Ext.util.Filter({
id: me.id + '-query-filter',
anyMatch: me.anyMatch,
caseSensitive: me.caseSensitive,
root: 'data',
property: me.displayField
});
me.store.addFilter(me.queryFilter, false);
}
if (queryString || !queryPlan.forceAll) {
me.queryFilter.disabled = false;
me.queryFilter.setValue(me.enableRegEx ? new RegExp(queryString) : queryString);
}
else {
me.queryFilter.disabled = true;
}
me.store.filter();
if (me.store.getCount()) {
if (me.rawValue === me.lastSelection[0].get(me.displayField)){
me.setValue(me.lastSelection);
} else {
if(me.store.getCount() === 1){
me.setValue(me.store.first());
}
me.expand();
}
} else {
me.collapse();
}
me.afterQuery(queryPlan);
},

Help modify a javascript - need to open link instead of displaying result

I'm trying to modify the code from this script. Basically I'm trying to get the script to send the browser to another page rather than display the results in a div.
This is the code in question:
<script type="text/javascript">
function openOneSlot() {
SpinningWheel.addSlot({1: 'First', 2: 'Second'});
SpinningWheel.setCancelAction(cancel);
SpinningWheel.setDoneAction(done);
SpinningWheel.open();
}
function done() {
var results = SpinningWheel.getSelectedValues();
document.getElementById('result').innerHTML = 'values: ' + results.values.join(' ') + '<br />keys: ' + results.keys.join(', ');
}
function cancel() {
document.getElementById('result').innerHTML = 'cancelled!';
}
window.addEventListener('load', function(){ setTimeout(function(){ window.scrollTo(0,0); }, 100); }, true);
</script>
I've changed the 'done' function to as follows:
function done() {
var results = SpinningWheel.getSelectedValues();
if (SpinningWheel.getSelectedValues() == "1,First")
{
window.location="first.html";
}
else if (SpinningWheel.getSelectedValues() == "2,Second")
{
window.location="second.html";
}
else
{
alert("Damn, Still not working..");
}
But now I'm lost as I'm very new to javascript.. Can anyone help the noob to get this working?
:)
Try this:
function done() {
var results = SpinningWheel.getSelectedValues();
if (results.values[0] == "First")
{
window.location.href="first.html";
}
else if (results.values[0] == "Second")
{
window.location.href="second.html";
}
else
{
alert("Damn, Still not working..");
}
The returned values appear to be an array of all the slots. Since yours has only one slot, I'm only looking at the first array position of the "results.values" array.
Try location.href instead of window.location
Note that this particular thing (changing page) is done differently across different browsers so you should google "javascript redirect " if you run into trouble on a particular browser
Look at what is returned by SpinningWheel.getSelectedValues(). It is an object with two properties keys and values. Therefore, it will not equal "1,First". Check into what is in those properties, and base your conditionals on those.
To pass your variables through, use the following syntax:
window.location = "first.html?var1Name=" + var1 + "&var2Name=" + var2;
To get the value of those variables on your first.html and second.html pages, you can use the window's query string to get hold of their values:
http://www.eggheadcafe.com/articles/20020107.asp
You would want to look at the window.location.search property.

Categories

Resources