I want to display label text for particular record in for loop - angular7

<div ngFor="let data of Requests">
FirstName:<b>{{data.name}}</b>
<button (click)="AcceptRequest()">Accept</button>
<button (click)="CancelRequest()">Decline</button>
<label>{{RequesStatus}}</label>
I want to display a label on accepting or declining requests for that request only in my code it displays for every request.

Try this, this should work:
<div *ngFor="let item of requests; index as ix">
ix: {{ix}} FirstName:<b>{{item.name}}</b>
<button (click)="HandleRequest(true, ix)">Accept</button>
<button (click)="HandleRequest(false, ix)">Decline</button>
<label>{{requesStatus[ix]}}</label>
<!-- or -->
<label>{{(isAccepted[ix]) ? 'accepted' : 'declined'}}</label>
</div>
In TS
// in class level declare this
requesStatus: string[] = [];
// or
isAccepted: boolean[] = [];
// function to set and use in template
HandleRequest(accepted, ix) {
this.requesStatus[ix] = (accepted) ? 'accepted' : 'declined';
// or
this.isAccepted[ix] = accepted;
}

Related

GAS PropertiesService to Save and Return Sort Order

QUESTION
How can I use PropertiesService to store an array from index.html, send the array to code.gs, and return the array in index.html?
SPECIFIC CASE
In a Google Web App, I have a group of sortable lists (made using JQuery UI Sortable). I want to save the most recent order/position of each li. I'm attempting to have that order/position "persist" when the page is refreshed or closed.
EXAMPLE
If you see the default Sortable, you could change the order of the items. If you refreshed the page, or closed it and return, the items would be in their original order.
WHERE I'M HAVING TROUBLE
I am able to get the array to show up in the console, but I don't know how to get it back to code.gs. I think I am now, but I'm not sure. Beyond that, I don't know how to "read" that PropertiesService so that the array is returned to index.html. I'm not really sure what I'm doing so if someone could slow walk me it would be appreciated!
ALTERNATIVES
I also looked into writing directly to the spreadsheet where the values originate. I'm not really sure how to do that either. I made some attempts, and was able to get "undefined" as a value in a spreadsheet cell.
FULL CODE (note: the list items are formed using an array, so they will not show up here): https://jsfiddle.net/nateomardavis/Lmcjzho2/1/
PARTIAL CODE
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('TEST');
var range = sheet.getRange(2, 1, 1000, 1);
var values = range.getValues();
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
teamsArray.push(values[i][0]);
}
var uniqueArray = [];
uniqueArray.push(teamsArray[0]);
for (var i in teamsArray) {
if ((uniqueArray[uniqueArray.length - 1] != teamsArray[i]) && (teamsArray[i] !== "")) {
uniqueArray.push(teamsArray[i]);
}
}
return uniqueArray;
}
function savePositions(myProperty, positions) {
PropertiesService.getScriptProperties().setProperty("myProperty", JSON.stringify(positions));
};
function getPositions() {
var returnedObj = PropertiesService.getScriptProperties()
};
index.html
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
<table id=table1>
<div id="team1">
<p>TEAM 1</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team1s" name='team1s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team1a" name='team1a' class="connectedSortable"></ul>
</div>
</table>
<table id=table2>
<div id="team2">
<p>TEAM 2</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team2s" name='team2s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team2a" name='team2a' class="connectedSortable"></ul>
</div>
</table>
<table id=table3>
<div id="team3">
<p>TEAM 3</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team3s" name='team3s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team3a" name='team3a' class="connectedSortable"></ul>
</div>
</table>
<table id=table4>
<div id="team4">
<p>TEAM 4</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team4s" name='team4s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team4a" name='team4a' class="connectedSortable"></ul>
</div>
</table>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getTeamArray();
});
function buildOptionsList(uniqueArray) {
var div = document.getElementById('myList');
for (var i = 0; i < uniqueArray.length; i++) {
var ul = document.createElement('ul');
var li = document.createElement('li');
var cLass = li.setAttribute('class', 'ui-state-default');
var iD = li.setAttribute('id', uniqueArray[i]);
li.appendChild(document.createTextNode(uniqueArray[i]));
div.appendChild(ul);
div.appendChild(li);
}
}
$(function() {
$("#myList, #team1s, #team1a, #team2s, #team2a, #team2s, #team3s, #team3a, #team4s, #team4a").sortable({
connectWith: ".connectedSortable",
update: function(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
//Instead of using JSON to save, can I use the spreadsheet itself to save the positions and then pull it from there as I did with "buildOptionsList" above?
function saveList() {
google.script.run.savePositions("myProperty", JSON.stringify(positions));
JSON.parse("myProperty");
}
}
})
});
$(function getPositions(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
});
</script>
</body>
</html>
It's also possible to just use the browser's localStorage client side.
localStorage.setItem('id', positions); //Store positions in users browser
localStorage.getItem('id'); //Retrieve the stored positions later
Notes:
For this to work, the url(document.domain of the iframe="*.googleusercontent.com") from which your script is deployed must remain constant. During my brief testing, it was constant even when changing from /dev to /exec of the parent(script.google.com) and even during version update. But there's no official reference.
This solution is better than properties service, if you have multiple users, as each one will have their own data stored in their own browsers and there are no server calls during each change.
Using google.script.run simple example:
<script>
function sendStringToServer() {
var string=$('#text1').val();
google.script.run
.withSuccessHandler(function(s){
alert(s);
})
.saveString(string);
}
</script>
Google Script:
function myFunction() {
PropertiesService.getScriptProperties().setProperty('MyString', string);
return "String was saved in Service";
}
Client to Server Communication

How do I create the range picker in my google spreadsheet add-ons

I want to create my spreadsheet add-on. How can I implement the range picker like the picture:
I know the app script can use this:
SpreadsheetApp.getActiveSpreadsheet().getActiveRange().getA1Notation();
But I don't know how to send the result to the add-on html input text.
The code from this Medium post (author Piyush Goel) seems to do the trick. The range should be selected by the user before to click the button.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<div class="sidebar branding-below">
<div class="block form-group">
<label for="names-range"><b>Comissions</b></label>
<input id="names-range" type="text" placeholder="Specify Range.." value=""/>
<button class="blue" id="names-range_button" onClick="getSelectedRange(this);">Get Selected Range</button>
</div>
<div class="block form-group">
<label for="ages-range"><b>Easyship Handling Fees</b></label>
<input id="ages-range" type="text" placeholder="Specify Range.." value=""/>
<button class="blue" id="ages-range_button" onClick="getSelectedRange(this);">Get Selected Range</button>
</div>
</div>
<div class="sidebar bottom">
<span class="gray">
Code sample by Piyush Goel</span>
</div>
<script>
function getSelectedRange(button){
button.innerHTML = "Picking.."; // Change the button value while getting range
button.disabled = true; // Disable the button while getting range
google.script.run // Executes a Apps Script JS Function
.withSuccessHandler(updateTextField) // function to be called upon successfull completion of Apps Script function
.withUserObject(button) // To pass the event element object
.getSelectedRange(); // Apps Sript JS Function
return;
}
// Function to be called on success
function updateTextField(range, button){
var textFieldId = button.id.split("_").shift();
document.getElementById(textFieldId).value = range; // Update the text field value
button.innerHTML = "Get Selected Range"; // Reset the button value
button.disabled = false;
}
</script>
</body>
</html>
// Add the options to the custom menu
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Custom Menu')
.addItem('Show Settings', 'showSidebar')
.addToUi();
}
// initiates the sidebar
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('settings')
.setTitle('Settings Sidebar')
.setWidth(300);
SpreadsheetApp.getUi().showSidebar(html);
}
/** Function to pick the selected range from the Google Sheet
* This returns the picked range, so that the client-side JS
* function (in HTML file) can populate it in the text field **/
function getSelectedRange(){
var selected = SpreadsheetApp.getActiveSheet().getActiveRange(); // Gets the selected range
var rangeString = selected.getA1Notation(); // converts it to the A1 type notation
return rangeString;
}

JQuery Mobile filterable listview with multiple filters

I have a JQM 1.4.2 filterable listview which contain entries in different languages.
I would like to search only within items code, not the whole description, whereby i set the data-filtertext for list items to the item code, e.g. "Apple" or "Banana".
This works ok but now i need an additional language filter, e.g. "EN", "DE", and so on:
...
<li data-filtertext="Apple language_en">
<h2>Title</h2>
<p>Red fruit</p>
<p class="ui-li-aside"><strong>EN</strong></p>
</li>
...
...
<li data-filtertext="Banana language_de">
<h2>Titel</h2>
<p>Beschreibung</p>
<p class="ui-li-aside"><strong>DE</strong></p>
</li>
...
This is my data input:
<form class="ui-filterable">
<div class="ui-grid-a">
<div class="ui-block-a">
<input id="descriptions-input" data-type="search" placeholder="Search..." />
</div>
<div class="ui-block-b">
<fieldset data-role="controlgroup" data-type="horizontal">
<input name="lang-en" id="lang-en" type="checkbox" data-mini="true">
<label for="lang-en">EN</label>
<input name="lang-de" id="lang-de" type="checkbox" data-mini="true">
<label for="lang-de">DE</label>
<input name="lang-fr" id="lang-fr" type="checkbox" data-mini="true">
<label for="lang-fr">FR</label>
</fieldset>
</div>
</div>
</form>
What i try to do now, is that when a checkbox is selected, only the list items belonging to that language are visible.
How can i set this additional filter to my filterable jQuery Mobile listview?
Plunker: http://plnkr.co/edit/TV6rcatzdvaIvQzWBdoI?p=preview
EDIT:
This is the final solution, thanks to EZANKER: https://jsfiddle.net/m64kg5fw/4/
The filterable widget as a filterCallback property: http://api.jquerymobile.com/filterable/#option-filterCallback
You can use this to write a function that checks both the text and which language checkboxes are checked.
$(document).on("pagecreate", "#list-descriptions", function () {
$("#descriptions-list").filterable('option', 'filterCallback', checkedOrMatch);
$("#searchLangs input").on("change", function(){
$("#descriptions-list").filterable("refresh");
});
});
function checkedOrMatch(idx, searchValue) {
var ret = false;
var en = $("#lang-en").is(':checked');
var de = $("#lang-de").is(':checked');
var fr = $("#lang-fr").is(':checked');
var ignoreLang = false;
if (!en && !de && !fr) {
ignoreLang = true;
}
if (searchValue && searchValue.length > 0) {
searchValue = searchValue.toLowerCase();
var filttext = $(this).data("filtertext") || '';
filttext = filttext.toLowerCase();
if (filttext.indexOf(searchValue) < 0) {
ret = true; //filter this one out
} else if (!ignoreLang) {
//found filter text now check language
if ( (filttext.indexOf("language_en") > 0 && !en) || (filttext.indexOf("language_de") > 0 && !de) || (filttext.indexOf("language_fr") > 0 && !fr) ) {
ret = true; //filter this one out
}
}
}
return ret;
}
Updated DEMO
The checkedOrMatch functions runs for each item in the list. It first tests if the entered search text is found in the filter text. If it is, it then sees which language buttons are checked and tests the item for that language. I also added code to re-trigger the filter if the user selects language buttons after typing the search criteria.
NOTE: if the user types in "lang" you might not get what you want... In that case you could move the language designation out of the filter text and into a separate data-attribute.

MVC Force jQuery validation on group of elements

My form I am designing with MVC 4 has mutiple DIVS with many elements in each one. My objective is to open/close DIVS as the user completes the fields. However, I want to use the unobtrusive validation on each DIV, rather than the whole form. Is that possible without checking each element individually? Maybe using a DIV ID or something? I don't want to build this massive function to check each and every element in each DIV just so the user can move to the next DIV.
I am trying this and it is not working:
var elems = [];
var valid = true;
("#Contact").find('.text_input').each(function() {
elems.push(this.id);
}
for (var i = 0; i<= elems.length; i++) {
if ($("#" + elems[i]) != undefined) {
$("#form1").validate().element("#" + elems[i]))
if ($("#" + elems[i]).valid()) {
}
else {
valid = false;
}
}
}
but I keep getting an undefined error. The elements in the DIV that have the class text_input are the ones with validation required.
You can validate individual controls using Validator.element(element) - see documentation here, so you could use the following approach (you haven't posted the views html so can't write the actual code for you)
In the Next button click event
Select all the the controls within the
associated div - e.g. var controls = $(this).closest('div').find('input, textarea, select');
In an $.each loop, call $("form").validate().element($(this));
If necessary, test if valid with $(this).valid();
If everything is valid, hide the current div and display the next
Edit (example added)
View
<div class="section">
<h2>Section 1</h2>
.... // Your inputs and validation
#Html.LabelFor(m => m.SomeProperty)
#Html.TextBoxFor(m => m.SomeProperty)
#Html.ValidationMessageFor(m => m.SomeProperty)
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 2</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 3</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="submit" class="next">Submit</button> // submit button for last section
</div>
CSS
.section:not(:first-of-type) {
display:none;
}
Script
$('button').click(function () {
var container = $(this).closest('.section');
var isValid = true;
$.each(container.find('input'), function () {
$('form').validate().element($(this));
if (!$(this).valid()) {
isValid = false;
return false;
}
});
if (isValid) {
container.next('.section').show().find('input').first().focus();
container.hide();
} else {
container.find('.error').text('please complete');
}
});

How to prevent saving of duplicate data?

I am developing MVC app.
I am using Jquery in Creat-Veiw for validate the data.
I am adding the Role and checking whether that Role(or you can say UserName) already exists in DB or not.
If Role already exists then validation message should display and should not be allow to add in db (should not allow to save).
I have a text-box which accepts the Role, on the blur function I have checked whether Role already exists or not.
Every thing working ok, If Role already exists then validation message comes up.
But after clicking on save button it saves in db.
I want to prevent it ? How to do this ?
I have below code of Create View.
#model IEnumerable<PaymentAdviceEntity.Role>
<div id="roleList">
<div class="span6">
<div class="span12 HeaderField2">
Roles
<legend style="margin-bottom:2px;margin-top:5px;"></legend>
</div>
<div class="span12">
<div style="display:inline-block"></div>
<div id="addrole" style="display:none">
<span> #Html.TextBox("RoleName", String.Empty, new { #id = "RoleName",style="margin-bottom:0px;" })</span>
<span>
<input type="button" value="Save" id="btnSave"/>
<input type="button" value="Cancel" id="btnCancel" />
</span>
</div>
<div style="margin-top:5px;">
<span id="RoleNameValidation" style="display:none;color:Red;">Role already exists</span>
</div>
</div>
</div>
For this I am using the below Jquery.
$("#RoleName").blur(function ()
{
var Role_Name = $('#RoleName').val();
//alert(RoleName);
var url = "#Html.Raw(Url.Action("checkForUniqueName","Role",new {#RName = "RoleName"}))";
url = url.replace("RoleName", Role_Name);
$.post(url, function (data)
{
if (data == false) {
$("#RoleNameValidation").show();
$('#RoleName').focus();
}
else {
$("#RoleNameValidation").hide()
}
});
});
and the controller Code is....
public ActionResult checkForUniqueName(string RName)
{
bool Valid = false;
var RoleList = from e in db.Roles
where e.Name.Equals(RName)
select e;
if (RoleList.Count() > 0 )
{
Valid = false;
}
else
{
Valid = true;
}
return Json(Valid, JsonRequestBehavior.AllowGet);
}
You can use validation for this purpose if you don't want to insert duplicate records in database.
Try to create a custom rule using the jQuery Validate plugin (using addMethod) that checks if the role is already exists in database.You can find good help at http://matthewmuro.com/2012/05/08/adding-custom-jquery-validation-to-your-form/

Resources