Angular JS change alert box to actual text on my document - javascript

I'm trying to modify someone's code that displays an alert if values don't match. Here's the code below:
if (finalData.length>0) {
$scope.rowCollection = finalData;
$scope.displayedCollection = [].concat($scope.rowCollection);
}
// $scope.rowCollection = $scope.rowCollection2;
else {
//$scope.rowCollection.push(finalData);
//alert('values are not matching Belinda');
}
$scope.showTable = true;
I'm trying to remove the alert and display 0 results found below a form on the document. Not sure if this even makes sense but would appreciate any help and would be able to answer any questions to get to the right direction.
TIA!
Atlante

you can assign a variable in the html which will be set in the else part
in the html, where you want to display the message:
<span>{{$scope.resultsMsg}}</span>
and in your js
if (finalData.length>0) {
$scope.rowCollection = finalData;
$scope.displayedCollection = [].concat($scope.rowCollection);
}
// $scope.rowCollection = $scope.rowCollection2;
else {
//$scope.rowCollection.push(finalData);
//alert('values are not matching Belinda');
$scope.resultsMsg = "0 results found.";
}
$scope.showTable = true;
2-way variable binding takes care of the rest in angularjs

Related

Window onload function if else statements

I would like to run different functions depending if a field is checked or not during page load.
So I use window.onload. The first if condition works great but I would like to add more if conditions as defined below. But it doesn't seem to be the proper way.
I thought I could work with if and if else. Does someone know how to make multiple if conditions work for window.onload function?
<script>
window.onload=function(){
if (document.getElementById("field1").checked) {
document.getElementById("field2").style.color = "red";
}
else if (document.getElementById("field3").checked) {
document.getElementById("field4").style.color = "red";
}
<script>
Added: I would like to add that all functions must be executed if all the if statements are fitting (so if else functions are maybe incorrect in this context). If only field1 is fitting the conditions, only the matching field2 should turn colour of text into red.
It’s not about the colour (that’s just an example for a JS function) - in real I want 3 things: enter value X, turn red and get disabled for future inputs (I already coded that - so not necessary).
UPDATE: Thanks to your comments. I used the code of Emiel Zuurbier: It's working for field 1 until 4 but not for field 10 until 14, did I wrote it wrong?
<script>
const fieldMap = [
['field1', 'field2', 'field3', 'field4'],
['field10', 'field11', 'field12', 'field14']
];
window.onload = function() {
for (const [fieldA, fieldB, fieldC, fieldD] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).value = "X";
document.getElementById(fieldB).style.color = "red";
document.getElementById(fieldB).disabled = true;
document.getElementById(fieldC).value = "X";
document.getElementById(fieldC).style.color = "red";
document.getElementById(fieldC).disabled = true;
document.getElementById(fieldD).value = "X";
document.getElementById(fieldD).style.color = "red";
document.getElementById(fieldD).disabled = true;
}
}
}
</script>
You can eleminate repeating tasks by taking the dynamic parts of your code, in this case your ID selectors, and put them in an array (or object) which you can loop over.
const fieldMap = [
['field1', 'field2'],
['field3', 'field4']
];
window.onload = function() {
for (const [fieldA, fieldB] of fieldMap) {
if (document.getElementById(fieldA).checked) {
document.getElementById(fieldB).style.color = 'red';
}
}
}
The principle of writing your code like this is called DRY (Don't Repeat Yourself)
winow.onload executes your function() when the page is fully loaded, but it happens just once. If the code you provided is correct then I think you might be missing } at the end. However, there's still one thing that bothers me. If you check if a specified checkbox is checked it checks the checked property only when the page is fully loaded, not when the user clicks on the #field checkbox. If you want the check whether the user checked the checkbox then you can use eventlistener 'check'.

Automatically change a value in a form field

I have a webpage where people enter information (name, job title, address, etc.) and it auto creates a business card for them. I currently have some jQuery that uses .change and looks at a field when a user changes it.
It looks for issues with what they enter, because some things must be in a certain format (ex- They enter the word "Avenue" and it won't let them add the item to their cart until they change it to Ave.)
I am trying to find some way to do this on the fly automatically with JS/jQuery, but I'm not sure what to do. What I would like is for the field to update itself, so if the user puts in "Avenue" it would auto update to "Ave." after the user tabs / exits the field.
Any idea on what JS and/or jQuery can be used to do this?
Here is my current code:
var x = "Clean";
var xD = " ";
$('#cartText4046').change(function () {
if ($(this).val().indexOf("Avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
} else if ($(this).val().indexOf("avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
... Additional rules here, omitted for space.
} else {
x = "Clean";
}
if (x != "Clean") {
$('#cartText4046').addClass("invalid");
xD = x;
} else if (x == "Clean") {
$('#cartText4046').removeClass("invalid");
xD = " ";
}
if (x != "Clean") {
$('.betabutton').html('<span id="addToBaskettext">To add this to the Basket,
please fix the following issue(s):<br><br> ' +xD'</span>');
$('.betabutton').addClass("invalidBtn");
} else if (x == "Clean") {
$('.betabutton').html('<a id="addToBasket" href="#" onclick="actionPageSubmit();return false;"><span id="addToBaskettext">Add to Basket</span></a>');
$('.betabutton').removeClass("invalidBtn");
}
Here is a working sample of what you may be looking for.
$("#textbox").on("change", function() {
$(this).val(function(index, value) {
return value.replace('Avenue', 'Ave.');
});
});
http://jsfiddle.net/decx8sw9/
If you really wanted it to do it after the user has finished making changes ("after the user tabs / exits the field.") you might want to bind to blur (fires when focus is lost/shifted to some other element)...
$('#cartText4046').on( "blur", function() {
$(this).val(function(index, value) {
value = value.replace('Avenue', 'Ave.');
// keep going ... value = value.replace('Street', 'St.') ..
return value;
});
EDIT: I reread the question, and now see that you wanted the correction to happen after the user exits the field. This answer provides inline autocorrection while the user types. I will leave it in case you find it useful after all.
You can lift the code from the jQuery Autocorrect Plugin: jsfiddle.
$("#textbox").autocorrect({
corrections: {
Avenue: "Ave.",
"...": "someWord"
}
});

Remove value from a var

I am having some problems removing parts of a var.
function hotBarClick() {
var likeCount = 0;
$.each(companies, function (key, value) {
if (value.liked) {
likeCount++;
}
if (value.liked && value.alreadyliked ==false) {
var content = value.getHtmlLogo();
matchesHtml.add(content);
this.alreadyliked = true;
}
if (value.liked == false && value.alreadyliked == true) {
var discontent = value.getHtmlLogo();
matchesHtml.remove(discontent);
this.alreadyliked = false;
}
});
I am making a app based on html and javascript. You can like/dislike companies in the neighbourhood. If you liked 5 companies or touch the "hotbar" you will see a slider(owl-carousel) with the logos of the companies you liked.
My problem is that if you liked a company first and then dislike it, i cant remove the images from the slider, that were previously shown.
var matcheshtml is the var containing this infomation. You can see that in my code i add stuff by matcheshtml.add() but i cant seem to use the .remove() method here?
How do i remove the good part?
BTW: i think discontent contains the correct value

CKEditor get table dialog class init Value in Set Up function of another element added on dialogDefinition

PLEASE READ QUESTION BEFORE READING CODE!!!
I've added a checkbox element on Dialog definition of the table dialog (it works). Now I want the checkbox to be checked by default when the table being edited has a certain class (which is usually visible on the advanced tab). According to the documentation, I should be able to do something like this in my setup function. I've tried many things and you could hopefully help me. This is my code.
CKEDITOR.on( 'dialogDefinition', function( evt )
{
var dialog = evt.data;
if(dialog.name == 'table' || dialog.name=='tableProperties')
{
// Get dialog definition.
var def = evt.data.definition;
var infoTab = def.getContents( 'info' );
infoTab.add(
{
type: 'checkbox',
id: 'myCheckBox',
label: 'Table Has Property',
setup: function()
{
//Class to look for if I successfully get the input's value
var classValueToLookFor = 'has-property';
// The current CKEditor Dialog Instance
var thisDialog = CKEDITOR.dialog.getCurrent();
// The Element whose value I want to get
var classElement = theDialog.getContentElement('advanced','advCSSClasses');
// Trying to Get Value of this class Element According to documentation
var containedClasses = theDialog.getValueOf('advanced','advCSSClasses');
// Trying to debug the value above
console.log(containedClasses); // This shows nothing
// Trying to debug InitValue which shows something according to prototype
console.log(classElement.getInitValue()); //This also shows nothing
//Checking if Element has the class I'm looking for to mark the checkbox
if(containedClasses.indexOf(classValueToLookFor) != -1)
{
//Check current checkbox since value has been found
this.setValue('checked');
}
}
onClick: function() // You can ignore this function, just put it in case you were wondering how I'm putting the has-property, might help someone else (works well) ;)
{
var checked = this.getValue();
var classValueToSet = 'has-property';
var thisDialog = CKEDITOR.dialog.getCurrent();
var containedClasses = theDialog.getValueOf('advanced','advCSSClasses');
if(checked)
{
if(containedClasses.indexOf(classValueToSet) != -1)
{
//console.log('already contains class: '+classValueToSet);
}
else
{
containedClasses += containedClasses+" "+classValueToSet;
}
}
else
{
if(containedClasses.indexOf(classValueToSet) != -1)
{
containedClasses = containedClasses.replace(classValueToSet,'');
}
else
{
//console.log('already removed class: '+classValueToSet);
}
}
thisDialog.setValueOf('advanced','advCSSClasses',containedClasses);
}
}
}
Here are some debug statements that can be helpful to add into the setup function and understand what is going on, you shouldn't need to go through all I've went through ;)
console.log('in setup function');
console.log(classElement);
console.log(classElement._);
console.log(classElement.getInitValue());
console.log(classElement.getInputElement());
var inputElement = classElement.getInputElement();
var inputElementId = inputElement.getId();
console.log($('#'+inputElementId+'.cke_dialog_ui_input_text'));
console.log(classElement.getInputElement().value);
It would be nice to test your answer before suggesting. Many of the things I've tried should work in theory, but are practically not working.
Alright, so finally after a few days of trial and error, this is what finally worked for me. Maybe it could be helpful to someone. I'm sure there should be a much cleaner way to do this. All the best to everyone.
setup: function()
{
//This current checkbox
var checkbox = this;
//the class I want to find on my table
var var classValueToLookFor = 'has-property';
//Current Dialog instance
var thisDialog = CKEDITOR.dialog.getCurrent();
//This code below gets a <td> element in the table
var startElement = thisDialog.getParentEditor().getSelection().getStartElement();
// This gets me the parent of the <td> element which is my current table instance
var parentTable = $(startElement.$.offsetParent);
//Finally check if the table has the property I'm looking for.
if(parentTable.hasClass(classValueToLookFor))
{
//Mark the checkbox
checkbox.setValue('checked');
}
}

Use stored properties when creating an HTML Sidebar

Using a sidebar, I get user input and save it as a script property. Next time the sidebar is loaded, I'd like to check if the saved property exists. If so, display it instead of the text entry box.
I know to use:
google.script.run.withSuccessHandler().myFunction()
Honestly, I have tried so many different things at this point. Any help would be greatly appreciated.
This is what I have tried, I want to load values in the sidebar if they exist. If they do not I want it load a text entry box, that is what it does by default.
Edit - Adding Code
function loadSidebarValues() {
if (dateText != 'ErrorStuff') {
var div = document.getElementById('dateValue');
div.innerHTML = dateText;
var errorDiv = document.getElementById('error');
errorDiv.innerHTML = "";
$('#dateText').val(
PropertiesService.getScriptProperties().getProperty('dateColumn')
);
} else {
var div = document.getElementById('sidebarValues');
div.innerHTML = "";
var errorDiv = document.getElementById('error');
errorDiv.innerHTML = 'There was an error.';
}
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({
'dateColumn': 'dateText',
});
Logger.log("date: " + userProperties.getProperty('dateColumn'));
}
function onLoad(){
if (PropertiesService.getScriptProperties().getProperty('dateColumn') != null) {
loadSidebarValues();
};
}
You can write server code to retrieve UserProperties value, then run the HTML script to get that value as instructed in File-open dialogs
section in this guide
What they do:
getOAuthToken in Code.gs
Call that function in Picker.html by this code:
function getOAuthToken() {
google.script.run.withSuccessHandler(createPicker)
.withFailureHandler(showError).getOAuthToken();
}
createPicker method from withSuccessHandler take token value from getOAuthToken in first step.
You can use the same pattern for your own case.

Categories