append method will not work in jquery - jquery-mobile

I have create JSON. and I have working in jquery mobile, This will not work in my code. Code is executed but element will not append.
var serviceName= [{..},{..},{..}]
$('#service_select').empty();
$('#service_select').append('<select name="day" id="day">');
for(var i = 0; i < serviceName.length; i++ ){
$('#service_select').append('<option value=" '+ serviceName[i].name+'">'+serviceName[i].name+'</option>');
}
$('#service_select').append('</select>');
html code
<div id="service_select"></div>

First ,Close select tags and append it to service_select DIV ,Then append option to it ,Because evenif you dont specify,jQuery creates closing tags immediately for if you dont specify
//NEW CODE just copy paste
<script>
var serviceName= [1,3,5,7,9];
$('#service_select').empty();
$("#service_select").append('<select name="day" id="day"></select>');
for(var i = 0; i < serviceName.length; i++ ){
$("#service_select select").append(new Option(serviceName[i], serviceName[i]));
}
</script>
Check jsfiddeel http://jsfiddle.net/TfM9S/

This is because the first append() creates the closing </select>, too. jQuery will not create invalid html.
try this:
$('#service_select').empty();
$('#service_select').append('<select name="day" id="day"></select>');
for(var i = 0; i < serviceName.length; i++ ){
$('#service_select select').append('<option value=" '+ serviceName[i].name+'">'+serviceName[i].name+'</option>');
}

It is suggested to use this form:
var $selectElement = $('<select>', {
'name': 'day',
'id': 'day'
});
for(var i = 0; i < serviceName.length; i++ ){
var $optionEl = $('<option>', {
'value': serviceName[i].name,
'text': serviceName[i].name
});
$selectElement.append($optionEl);
}

It works Properly
var serviceName = [{..},{..}]
$(document).on("pageinit","#anotherPageId", function(){
$('#service_select').empty();
$('#service_select').append('<select name="service" id="service"></select>');
for (var i = 0; i < serviceName.length; i++) {
$('#service_select select').append('<option value=" ' + serviceName[i].name + '">' + serviceName[i].name + '</option>');
}
});

Related

Convert JSP code into JavaScript for canvasJS

I'm trying to get this canvasJS line chart to render using thymeleaf rather than JSP.
It has the following loop in jsp that I need to convert to javascript. However I'm not proficient in javascript
<c:forEach items="${dataPointsList}" var="dataPoints" varStatus="loop">
<c:forEach items="${dataPoints}" var="dataPoint">
xValue = parseInt("${dataPoint.x}");
yValue = parseFloat("${dataPoint.y}");
dps[parseInt("${loop.index}")].push({
x : xValue,
y : yValue,
});
</c:forEach>
</c:forEach>
The above $dataPointList is created in java as follows
static List<Map<Object, Object>> dataPoints1 = new ArrayList<Map<Object, Object>>();
static {
int limit = 50000;
int y = 100;
Random rand = new Random();
for (int i = 0; i < limit; i += 1) {
y += rand.nextInt(11) - 5;
map = new HashMap<Object, Object>();
map.put("x", i);
map.put("y", y);
dataPoints1.add(map);
}
list.add(dataPoints1);
}
public static List<List<Map<Object, Object>>> getCanvasjsDataList() {
return list;
}
I've tried the following however dps[parseInt(i)].push({ gives a type error. I'm not sure how to create the required data structure for canvasJS given the datalist defined in java.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" th:inline="none" class="init">
/*<![CDATA[*/
window.onload = function (e) {
var dps = [[]];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "dark1", "dark2"
animationEnabled: true,
zoomEnabled: true,
title: {
text: "Try Zooming and Panning"
},
data: [{
type: "area",
dataPoints: dps[0]
}]
});
var xValue;
var yValue;
var dataPointsList = /*[[${dataPointsList}]]*/ 'default';
for (var i = 0; i < dataPointsList.length; i++) {
var dataPoints = dataPointsList[i];
for (var j = 0; j < dataPoints.length; j++) {
dps[parseInt(i)].push({
x : dataPoints[j].x,
y : dataPoints[j].y,
});
}
}
chart.render();
}
/*]]>*/
</script>
The following adjustments have resulted in the graph displaying
<script type="text/javascript" th:inline="javascript" class="init">
/*<![CDATA[*/
window.onload = function (e) {
var dps = [];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "dark1", "dark2"
animationEnabled: true,
zoomEnabled: true,
title: {
text: "Try Zooming and Panning"
},
data: [{
type: "area",
dataPoints: dps
}]
});
var dataPointsList = /*[[${dataPointsList}]]*/ 'null';
count = 0;
for (var i = 0; i < dataPointsList.length; i++) {
var dataPoints = dataPointsList[i];
for (var j = 0; j < dataPoints.length; j++) {
dps[count++] = {
x: dataPoints[j].x,
y: dataPoints[j].y
};
}
}
chart.render();
}
/*]]>*/
</script>

select2 v4 dataAdapter.query not firing

I have an input to which I wish to bind a dataAdapter for a custom query as described in https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection
<input name="pickup_point">
My script:
Application.prototype.init = function() {
this.alloc('$pickupLocations',this.$el.find('[name="pickup_point"]'));
var that = this;
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
var CustomData = function($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
results: []
};
console.log("xxx");
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
that.$pickupLocations.select2({
minimumInputLength: 2,
language: translations[that.options.lang],
tags: [],
dataAdapter: CustomData
});
});
}
But when I type the in the select2 search box the xxx i'm logging for testing doesn't appear in my console.
How can I fix this?
I found the solution on
https://github.com/select2/select2/issues/4153#issuecomment-182258515
The problem is that I tried to initialize the select2 on an input field.
By changing the type to a select, everything works fine.
<select name="pickup_point">
</select>

Dynamically changing select value of jQuery Mobile select box

I have dynamically created select menu. How can I dynamically change selected value to third value(Apple).
HTML
<div>
<select id="stylex" data-mini="true"> </select>
</div>
Code
var wid_settings = ["Banana","Orange","Apple","Mango"];
wid_settings_refresh();
function wid_settings_refresh() {
var index;
for (index = 0; index < wid_settings.length; index++) {
$('#stylex').append('<option value='+index+'>'+wid_settings[index]+'</option>');
}
$('#stylex').listview('refresh');
}
// this is not working
$('#stylex').val(3);
$('#stylex').selectmenu("refresh");
JSFiddle
Updated your JS fiddle: http://jsfiddle.net/rhLt2sxj/5/
var wid_settings = ["Banana", "Orange", "Apple", "Mango"];
wid_settings_refresh();
function wid_settings_refresh() {
var index;
for (index = 0; index < wid_settings.length; index++) {
$('#stylex').append('<option value=' + index + '>' + wid_settings[index] + '</option>');
}
$('#stylex').val(3);
//$('#stylex').listview('refresh'); //not necessary
}

JQM Check Box Not Styling inside Webview ".trigger('create')"

Here is my javascript code snippet:
<script>
function returnStringForID(param) {
var retStr =
param.replace(/[\. ,:-]+/g, '').replace(/'/g, '')
.replace(/&/g, '').replace(/\(|\)/g, '');
return retStr;
}
$(document).ready(function () {
var chanId = 'Demo';
var fs_dyn = $('#fs_dyn');
var data = ['Sony', 'Pix', 'Max', 'Set'];
var seriesColors = ['#4000E3', '#FFC526', '#FF0000', '#C0504D'
, '#1F497D', '#4BACC6', '#8064A2', '#9BBB59', '#F79646', '#948A54'];
for (var i = 0; i < data.length; i++) {
var checkId = "graphItem_" + i;
var color;
color = seriesColors[i];
var chanId = returnStringForID(data[i]);
var tmp = "";
tmp = "<input type='checkbox' checked='true' class='custom' value='" + data[i]
+ "' id='" + chanId + "' name='" + chanId + "'/>"
+ "<label for='" + chanId + "' style='font-size:12pt;font-weight:bold;color:"
+ color + "'>" + data[i] + "</label>";
fs_dyn.append(tmp);
}
fs_dyn.trigger('create');
});
</script>
Here is the HTML:
<td width='30%' style="vertical-align: top;" id="tdDynamic">
<fieldset data-mini='true' id='fs_dyn'></fieldset>
</td>
This code works perfect if done in raw html. However when inside a webview, checkbox doesn't style.
Also I have used .trigger('create') to style a nested collapsible in the same app which is also inside a webview, but that works fine.
PS: I am using JQM 1.3.1 version, just in case this helps.
Use pageinit event which is equivalent to .ready() or any jQuery Mobile events.
Demo
$(document).on('pageinit', function () {
// code
});
Using .ready() in jQuery Mobile isn't recommended, please refer to this post.

How to Upload files in SAPUI5?

How to upload file in SAP Netweaver server using SAPUI5? I tried to upload file using FileUploader but did not get the luck if any one can help it will be very appreciated.
Thanks in Advance
Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.
UploadFile.view.xml
<VBox>
<sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
Controller, MessageToast, MessageBox, History) {
"use strict";
return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
onNavBack: function() {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("admin", true);
}
},
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
});
});
After researching a little more on this issue I finally solved this issue by myself I placed a file controller and a uploader in php which return the details related to files further, we can use it to upload it on server.
Here is the code I have used.
fileUpload.html
<!DOCTYPE html>
<html><head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<title>Hello World</title>
<script id='sap-ui-bootstrap' src='http://localhost/resources/sap-ui-core.js' data-sap-ui-theme='sap_goldreflection'
data-sap-ui-libs='sap.ui.commons'></script>
<script>
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader("myupload",{
name: "upload2",
uploadOnChange: true,
uploadUrl: "uploader.php",
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
alert(sResponse);
}
}});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text:'Trigger Upload',
press:function() {
// call the upload method
oFileUploader2.upload();
$("#myupload-fu_form").submit();
alert("hi");
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");
</script>
</head>
<body class='sapUiBody'>
<div id="sample2"></div>
</body>
</html>
uploader.php
<?php
print_r($_FILES);
?>
It would be good if we can see your code.
This should work.
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader({
name : "upload2",
uploadOnChange : false,
uploadUrl : "../../../upload"
});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text : 'Trigger Upload',
press : function() {
// call the upload method
oFileUploader2.upload();
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");

Resources