Change contents based on single function - dom

Javascript. The following code works, but I have to call the function 3 times.
Should I be using replaceChild()?
This is what I have so far:
<!DOCTYPE html>
<html>
<body>
<ul id="myList1"><li>1</li><li>2</li><li>3</li><li>4</li></ul>
<ul id="myList2"><li>a</li><li>b</li><li>c</li><li>d</li></ul>
<p id="demo">Click the button to move an item from one list to another</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tmp = 5;
for(var i = 0; i < tmp; i++)
{
var node=document.getElementById("myList2").getElementsByTagName("LI")[i];
document.getElementById("myList1").appendChild(node);
var node2=document.getElementById("myList1").getElementsByTagName("LI")[i];
document.getElementById("myList2").appendChild(node2);
}
}
</script>
</body>
</html>

You don't need to replace anything, just move nodes with appendChild Something like this:
function myFunction() {
var list1 = document.getElementById("myList1"),
list2 = document.getElementById("myList2"),
length1 = list1.children.length,
length2 = list1.children.length;
while (list1.children.length) {
list2.appendChild(list1.children[0]);
}
while (list2.children.length > length2) {
list1.appendChild(list2.children[0]);
}
}
Demo: http://jsfiddle.net/dfsq/4v94N/1/

Related

Convert Excel form window to Google Sheets window

As you've probably found, there appears to be no equivalent way to add the following Excel form and associated VBA code to Google Sheets or Scripts or Forms:
Is there some add-in that can be used to pop up this image and its controls? This has to be used many times in an accounting sheet to categorize expenditures at tax time.
It may not look exactly the same but I was able to construct a custom dialog in a short period of time to show how HTML service can be used to produce similar results.
First I construct an HTML template that contains the 2 combo boxes with multiple lines.
HTML_Test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('CSS_Test'); ?>
</head>
<body>
<div id="left">
<label for="expenseCategory">Expense Category</label><br>
<select id="expenseCategory" size="10">
</select>
</div>
<div id="middle">
<label for="expenseSubCategory">Expense Sub Category</label><br>
<select id="expenseSubCategory" size="10">
</select>
</div>
<?!= include('JS_Test'); ?>
</body>
</html>
Then a CSS file to contain all my element formatting.
CSS_Test.html
<style>
#expenseCategory {
width: 90%;
}
#expenseSubCategory {
width: 90%;
}
#left {
width: 25%;
float: left;
}
#middle {
width: 50%;
float: left;
}
</style>
And a javascript file for client side javascript. I've simply hard coded some data to show how the select elements are filled in but this could just as easily be done using template scripting, or google.script.run
<script>
var expenses = [["A","1","2","3"],
["B","4","5"],
["C","6","7","8","9","10"]
];
function expenseCategoryOnClick() {
try {
let expenseCategory = document.getElementById('expenseSubCategory');
expenseCategory.options.length = 0;
expenses[this.selectedIndex].forEach( (expense,index) => {
if( index > 0 ) {
let option = document.createElement("option");
let text = document.createTextNode(expense);
option.appendChild(text);
expenseCategory.appendChild(option);
}
}
);
}
catch(err) {
alert("Error in expenseCategoryOnClick: "+err)
}
}
(function () {
// load first expense
let expenseCategory = document.getElementById('expenseCategory');
expenseCategory.addEventListener("click",expenseCategoryOnClick);
expenses.forEach( expense => {
let option = document.createElement("option");
let text = document.createTextNode(expense[0]);
option.appendChild(text);
expenseCategory.appendChild(option);
}
);
expenseCategory = document.getElementById('expenseSubCategory');
expenses[0].forEach( (expense,index) => {
if( index > 0 ) {
let option = document.createElement("option");
let text = document.createTextNode(expense);
option.appendChild(text);
expenseCategory.appendChild(option);
}
}
);
}
)();
</script>
Then there is the server side code bound to a spreadsheet.
Code.gs
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createMenu("Test");
menu.addItem("Show Test","showTest");
menu.addToUi();
}
// include(filename) required to include html files in the template
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename)
.getContent();
}
function showTest() {
var html = HtmlService.createTemplateFromFile("HTML_Test");
html = html.evaluate();
html.setWidth(800);
SpreadsheetApp.getUi().showModalDialog(html,"Test");
}
The dialog looks like this. Many more html elements can be added as needed. This just shows the basics. This may be more difficult than an wysiwig html editor but I find I have better control of the appearance and function of my pages this way. Notice I clicked "C" and the sub category is filled in automatically.

How to find and highlight text between tags in WKWebView webpage - Like browser find feature

How to find and highlight text in WKWebView? I have search option in my app which will search text inside WKWebview. I have to highlight the searched text in WKWebView.
I want to get "browser Find feature" in WKWebView.
I have tried some code in Mac browser which is working in Mac browser but not working in iPhone WKWebView.
I want search text between tags.
<!DOCTYPE html>
<html>
<head>
<title>Test page for Highlight Search Terms</title>
</head>
<body>
<input type="text" id="search" autofocus onkeyup="highlight(document.getElementById('search').value);" />
<div id="content">
<p>Here is some searchable <b>text</b> with some lápices in it, and more lápices, and some <b>for<i>mat</i>t</b>ing</p>
</div>
<script type="text/javascript">
function highlight(text) {
let colour = "#ff0";
unhighlight(document.body, 'ffff00');
while (window.find(text)) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}
}
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
// Use HiliteColor since some browsers apply BackColor to the whole block
if (!document.execCommand("HiliteColor", false, colour)) {
document.execCommand("BackColor", false, colour);
}
document.designMode = "off";
}
function unhighlight(node, colour) {
if (node.nodeType == 1) {
var bg = node.style.backgroundColor;
node.style.backgroundColor = "";
}
var child = node.firstChild;
while (child) {
unhighlight(child, colour);
child = child.nextSibling;
}
}
</script>
</body>
</html>

Same name class element

How do i change 2 class "myDiv" span name at the same time? Below script only work for the first "myDiv"
<div class="myDIV">
<span>orginial name1</span>
</div>
<div class="myDIV">
<span>orginial name2</span>
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = document.getElementsByClassName("myDIV");
x[0].innerHTML = "<span>new name for all</span>";
}
</script>
document.getElementsByClassName("myDIV");
will give array of elements, you are referring to only first element by [0].
update your function as below to change in both.
function myFunction() {
var x = document.getElementsByClassName("myDIV");
x[0].innerHTML = "<span>new name for all</span>";
x[1].innerHTML = "<span>new name for all</span>";
}
Alternatively you can use jquery to achieve it in just one line.
$('.myDIV').html("<span>new name for all</span>");
if it is working for the first one,then this should work for second one
function myFunction() {
var x = document.getElementsByClassName("myDIV");
x[0].innerHTML = "<span>new name for all</span>";
x[1].innerHTML = "<span>new name for all</span>";
}
A little simple things sometimes forgotten, this simply by adding x[1].innerHTML = "<span>new name for all 2</span>";
function myFunction() {
var x = document.getElementsByClassName("myDIV");
x[0].innerHTML = "<span>new name for all 1</span>";
x[1].innerHTML = "<span>new name for all 2</span>";
}
<div class="myDIV">
<span>orginial name1</span>
</div>
<div class="myDIV">
<span>orginial name2</span>
</div>
<button onclick="myFunction()">Try it</button>

detect dynamically checkboxes/polymer elements ticked in Dart

A newbie to Dart with no experience in JS.
I have written code to populate a dropdown from JSON.
Edit:
i am trying to add polymer elements.
Polymer .dart
import 'package:polymer/polymer.dart';
#CustomTag('player-item')
class PlayerItem extends PolymerElement{
#observable String playerName='hello';
void removePlayer(){
playerName='';
}
PlayerItem.created(): super.created(){}
}
Initially was getting error of constructor not defined. added empty brackets to
super.created. error fixed
What am i doing wrong. how to do this correctly??
polymer.html
playername = name of player to be displayed dynamically.
right now using default string.
removeplayer = (ideas is to) remove entire polymer element.
<polymer-element name="player-item">
<template>
<input type="image" src="button_minus_red.gif" on-click="{{removePlayer}}">
<div>{{playerName}}</div>
</template>
<script type="application/dart" src="player-item.dart"></script>
</polymer-element>
Edited Dart Code:
Objective is first generate options then select one of them and the subsequently remove them if clicked on image(polymer element intended for this purpose).
Went through polymer example master. but couldnt find something related.
Help Needed:
1. how do i dynamically add polymer elements?
how to pass values (ie. in this case name of player) to the dynamically added
polymer element?
how to remove polymer elements?
How to remove appended text added via *.appendedtext ?
import 'dart:html';
import 'dart:convert' show JSON;
import 'dart:async' show Future;
import 'package:polymer/polymer.dart';
import 'player-item.dart';
//ButtonElement genButton,desButton;
SelectElement selectTeam;
FormElement teamPlayer;
FormElement yourPlayer;
InputElement teamPlayers;
//final subscriptions = <StreamSubscription>[];
List<String>teams=[];
List<String>players=[];
main() async{
selectTeam = querySelector('#teamNames');
teamPlayer = querySelector('#teamPlayers');
yourPlayer = querySelector('#yourPlayers');
selectTeam.onChange.listen(populateTeams);
try {
await prepareTeams1 ();
selectTeam.disabled = false; //enable
//genButton.disabled = false;
} catch(arrr) {
print('Error initializing team names: $arrr');
}
}
void populateYourPlayers(String name){
querySelector('#yourPlayers').children.add(new Element.tag('player-item'));
var input = new InputElement();
input.type = "image";
input.src = "button_minus_red.gif";
input.id = name;
print('yo');
input.width = 15;
input.height =15;
input.appendText(name);
input.onClick.listen((remove){
remove.preventDefault();
input.remove();
//yourPlayer.children.remove();
});
yourPlayer.append(input);
// yourPlayer.append(y);
yourPlayer.appendText(name);
yourPlayer.appendHtml("<br>");
}
void removeYourPlayers(Event e){
yourPlayer.querySelectorAll("input[type=checkbox]").forEach((cb) {
// print('${cb.checked}');
if(cb.checked == true){
print('${cb.id}');
yourPlayer.children.removeWhere((cb)=>cb.checked==true);
}
}
);
}
Future prepareTeams1()async{
String path = 'teams.json';
String jsonString = await HttpRequest.getString(path);
parseTeamNamesFromJSON(jsonString);
}
parseTeamNamesFromJSON(String jsonString){
Map team = JSON.decode(jsonString);
teams = team['Teams'];
print(teams);
for (int i =0; i< teams.length; i++){
var option = new OptionElement();
option.value = teams[i];
option.label =teams[i];
option.selected = false;
selectTeam.append(option);
}
}
Future prepareTeams2(String Team)async{
String path = 'teams.json';
String jsonString = await HttpRequest.getString(path);
parsePlayerNamesFromJSON(jsonString, Team);
}
parsePlayerNamesFromJSON(String jsonString,String Team){
Map team = JSON.decode(jsonString);
teamPlayer.children.clear();
teams = team[Team];
print(teams);
for (int i =0; i< teams.length; i++){
var input = new InputElement(type:"image");
// input.type = "image";
input.id = teams[i];
input.src = "button_plus_green.gif";
input.width = 15;
input.height =15;
input.onClick.listen((p){
p.preventDefault();
populateYourPlayers(teams[i]);
});
//input.onClick.listen((event){populateYourPlayers(teams[i]);});
//subscription.cancel();
teamPlayer.append(input);
teamPlayer.appendText(teams[i]);
teamPlayer.appendHtml("<br>");
}
}
void populateTeams(Event e){
print('selectTeam.length: ${selectTeam.length}');
print(selectTeam.value);
prepareTeams2(selectTeam.value);
if (selectTeam.length == 0){
}
}
Modified HTML:
<html>
<head>
<meta charset="utf-8">
<title>Pirate badge</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="piratebadge.css">
<link rel="import" href="player-item.html">
</head>
<body>
<h1>Team Names</h1>
<select id="teamNames">
</select>
<h1>Team players</h1>
<form id="teamPlayers">
</form>
<div>
<button id="generateButton" disabled>Add Player/Players</button>
</div>
<h1>Your players</h1>
<form id="yourPlayers">
</form>
<player-item></player-item>
<div>
<button id="destroyButton" disabled>Remove Player/Players</button>
</div>
<script type="application/dart" src="piratebadge.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
and based on that selection display a form with checkboxes.
The issue i am facing is how to detect them which checkboxes have been checked and if so how the value of that checkbox can be captured.
Possible duplicate
How to know if a checkbox or radio button is checked in Dart?
However them checkboxes not dynamically created.
If the above approach is wrong, kindly advise.
Depending on when you want to detect the checked state there are two ways.
You can add a click handler to the submit button and then query the checkboxes.
querySelector("input[type=submit]").onClick.listen((e) {
querySelectorAll("input[type=checkbox]").forEach((cb) {
print('${cb.id} {cb.checked}');
});
});
Currently you are assigning the same id to each checkbox. This is a bad choice because you have no way to know which checkbox represents what item.
Another way is to assign a click handler to each checkbox to get notified immediately when the checkbox is clicked.
(I simplified your checkbox creation code a bit by using continuations and forEach instead of for)
teams.forEach((team) {
var input = new InputElement()
..type = "checkbox"
..id = "player"
..onClick.listen((e) {
print('${cb.id} {cb.checked}');
});
teamplayer
..append(input)
..appendText(team)
..appendHtml("<br>");
}
In this case you might need to reset the click notifications when the selection changes.
import 'dart:async';
// ...
final subscriptions = <StreamSubscription>[];
// ...
subscriptions
..forEach((s) => s.cancel())
..clear();
teams.forEach((team) {
var input = new InputElement()
..type = "checkbox"
..id = "player";
subscriptions.add(input.onClick.listen((e) {
print('${cb.id} {cb.checked}');
}));
teamplayer
..append(input)
..appendText(team)
..appendHtml("<br>");
}
Caution: code not tested and it's a while I used checkboxes.
You can read the checked property of the CheckboxInputElement
parsePlayerNamesFromJSON(String jsonString,String Team){
Map team = JSON.decode(jsonString);
teams = team[Team];
print(teams);
for (int i =0; i< teams.length; i++){
var input = new CheckboxInputElement();
input.type = "checkbox";
input.id = "player";
input.onChange.listen((_) {
print("teamplayer ${input.checked}");
});
teamPlayer.append(input);
teamPlayer.appendText(teams[i]);
teamPlayer.appendHtml("<br>");
}

Implementing Search on a JqxTree using JqxdataAdapter Plugin..?

I am trying to implement a Search Over a JqxTree in which i am populating data with the help of JSON.
I want to implement the Search in a way that when i enter a string in a textbox the tree should expand till that component.
Can anyone help me out with this.
Following is my jsp code:-
<link rel="stylesheet" href="<%=request.getContextPath()%>/css/jqwidgets/styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/scripts/demos.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxcore.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxdata.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxbuttons.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxscrollbar.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxpanel.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jqwidgets/jqxtree.js"></script>
</head>
<body>
<div id='content' style='float: right;'>
<script type="text/javascript">
$(document).ready(function () {
$('#ExpandAll').jqxButton({ height: '25px', width: '100px'});
$('#CollapseAll').jqxButton({ height: '25px', width: '100px'});
// Expand All
$('#ExpandAll').click(function () {
$('#jqxWidget').jqxTree('expandAll');
});
//Collapse All
$('#CollapseAll').click(function () {
$('#jqxWidget').jqxTree('collapseAll');
});
var data = <%=request.getAttribute("data")%>
// prepare the data
var source =
{
datatype: "json",
datafields: [
{ name: 'categoryId' },
{ name: 'parentId' },
{ name: 'categoryName' },
],
id: 'categoryId',
localdata: data
};
// create data adapter.
var dataAdapter = new $.jqx.dataAdapter(source);
// perform Data Binding.
dataAdapter.dataBind();
// Get the tree items.
//The 1st parameter is the item's id.
//The 2nd parameter is the parent item's id.
//The 'items' parameter represents the sub items collection name.
//Each jqxTree item has a 'label' property, but in the JSON data, we have a 'text' field.
//The last parameter specifies the mapping between the 'text' and 'label' fields.
var records = dataAdapter.getRecordsHierarchy('categoryId', 'parentId', 'items', [{ name: 'categoryName', map: 'label'}]);
$('#jqxWidget').jqxTree({ source: records, width: '500px'});
});
</script>
</div>
<!-- DIV COMPONENTS -->
<div style='margin-top: 10px;'>
<input type="button" id='ExpandAll' value="Expand All" />
</div>
<div style='margin-top: 10px;' >
<input type="button" id='CollapseAll' value="Collapse All" />
</div><br/>
<div id='jqxWidget'>
</div>
</body>
</html>
Please Help me out..!! :)
Here's how I achieved It
$("#btnSearchTree").on('click', function () {
//Setting current selected item as null
$('#jqxWidget').jqxTree('selectItem', null);
//collapsing tree(in case if user has already searched it )
$('#jqxWidget').jqxTree('collapseAll');
//Using span for highlighting text so finding earlier searched items(if any)
var previousHighlightedItems = $('#jqxWidget').find('span.highlightedText');
// If there are some highlighted items, replace the span with its html part, e.g. if earlier it was <span style="background-color:"Yellow">Te></span>st then it will replace it with "Te""st"
if (previousHighlightedItems && previousHighlightedItems.length > 0) {
var highlightedText = previousHighlightedItems.eq(0).html();
$.each(previousHighlightedItems, function (idx, ele) {
$(ele).replaceWith(highlightedText);
});
}
//Getting all items for jqxTree
var items = $('#jqxWidget').jqxTree("getItems");
//Getting value for input search box and converting it to lower for case insensitive(may change)
var searchedValue = $("#ipSearchTreeText").val().toLowerCase();
//Searching the text in items label
for (var i = 0; i < items.length; i++) {
if (items[i].label.toLowerCase().indexOf(searchedValue) > -1) {
//If found expanding the tree to that item
$('#jqxWidget').jqxTree('expandItem', items[i].parentElement);
//selecting the item : not necessary as it selects the last item if multiple occurrences are found
$('#jqxWidget').jqxTree('selectItem', items[i]);
//changing the innerhtml of found item and adding span with highlighted color
var itemLabelHTML = $(items[i].element).find('div').eq(0).html();
//splitting the item text so that only searched text
can be highlighted by appending span to it.
var splittedArray = itemLabelHTML.split(searchedValue);
var highlightedText = '';
//if there are multiple occurrences of same searched text then adding span accordingly
for (var j = 0; j < splittedArray.length; j++) {
if (j != splittedArray.length - 1)
highlightedText = highlightedText + splittedArray[j] + '<span class="highlightedText" style="background-color:yellow">' + searchedValue + '</span>';
else
highlightedText = highlightedText + splittedArray[j];
}
//var highlightedText = splittedArray[0] + '<span style="background-color:yellow">' + searchedValue + '</span>' + splittedArray[1];
//replacing the item html with appended styled span
$(items[i].element).find('div').eq(0).html(highlightedText);
}
};
});