i found error in loading a simple .js file at document .write? - document.write

i had written a code and found an error at document .write what to do ?
code is
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").document.write=('hi');
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo"></p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
this is the error
Uncaught TypeError: Cannot set property 'write' of undefined
at myFunction (test1.html:6)
at HTMLButtonElement.onclick (test1.html:16)
myFunction # test1.html:6
onclick # test1.html:16
help me out!

The problem is : you use some things that doesn't exists
document.getElementById() returns an Element and there is no property document on Element (and even if there was it would make you go back to the original document).
So:
document.getElementById("demo").document === undefined
that's what your error is saying.
but removing it will not be enought as there is no Element.write()
The solution is to use either Element.innerHTML or Element.textContent which are used as normal strings.
The difference between the two is that innerHTML allow you to write HTML tags which will be rendered, while textContent escape HTML tag in order to print the string as is it in your sources.
Exemple of innerHTML and textContent :
function myFunction1() {
document.getElementById("demoTextContent").textContent = 'hi';
document.getElementById("demoInnerHTML").innerHTML = 'hi';
}
function myFunction2() {
content = document.getElementById("demoTextContent").textContent
document.getElementById("demoTextContent").textContent = content + 'hi';
// these to line can also be written as
// document.getElementById("demoTextContent").textContent += 'hi';
content = document.getElementById("demoInnerHTML").innerHTML
document.getElementById("demoInnerHTML").innerHTML = content + 'hi';
// these to line can also be written as
// document.getElementById("demoInnerHTML").innerHTML += 'hi';
}
function myFunction3() {
document.getElementById("demoTextContent").textContent = '<span style="background-color:cyan;">hi</span>';
document.getElementById("demoInnerHTML").innerHTML = '<span style="background-color:cyan;">hi</span>';
}
#demoTextContent::before {content: "textContent: ";}
#demoInnerHTML::before{content:"innerHTML: ";}
<h2>JavaScript in Head</h2>
<p id="demoTextContent"></p>
<p id="demoInnerHTML"></p>
<button type="button" onclick="myFunction1()">Try replace text</button>
<button type="button" onclick="myFunction2()">Try append</button>
<button type="button" onclick="myFunction3()">Try replace by html code</button>
also you wrote
write=('hi')
the = may be a typo but JavaScript will read it as write = ('hi') later traslated to write = 'hi'.
Already had something like this, spent almost an hour finding it :p.

Related

Changing the template data not refreshing the elements

I have searched and tried suggestions mentioned in various posts but no luck so far.
Here is my issue.
I have created a custom element <month-view id="month-view-element"></month-view> in my mainpage.html. Inside mainpage.html when this page is initially loaded i created a empty json object for all the 30days of a month and print a placeholder type cards in UI. Using the code below.
var json = [];
for(var x = 0; x < total; x++) {
json.push({'hours': 0, 'day': x+1, 'year': year});
}
monthView.month = json; //Doing this line. Prints out the desired empty cards for me in the UI.
created a month-view.html something like below:
<dom-module id='month-view'>
<template>
<template is="dom-repeat" items= "{{month}}">
<paper-card class="day-paper-card" heading={{item.day}}>
<div class="card-content work">{{item.work}}</div>
<div class="card-actions containerDay layout horizontal">
<div style="display:inline-block" class="icon">
<paper-icon-button icon="icons:done" data-hours = "8" data-day$="{{item.day}}" data-month$={{item.month}} data-year$={{item.year}} on-click="updateWorkHours"></paper-icon-button>
<paper-tooltip>Full day</paper-tooltip>
</div>
</div>
</paper-card>
</template>
</template>
<script>
Polymer({
is: "month-view",
updateWorkHours: function (e, detail) {
console.log(e);
this.fire('updateWorkHour', {day: e.target.dataHost.dataset.day,
month: e.target.dataHost.dataset.month,
year: e.target.dataHost.dataset.year,
hours: e.target.dataHost.dataset.work
});
}
});
</script>
</dom-module>
There is another file script.js which contains the function document.addEventListener('updateWorkHour', function (e) { // doStuff });. I use this function to make a call to a google client API. I created a client request and then do request.execute(handleCallback);
Once this call is passed i landed in handleCallback function. In this function i do some processing of the response data and save parts of data into json variable available in the file already. And once all processing is done i did something like below.
monthView.month = json;
But this above line is not refreshing my UI with the latest data. Is there anything I am missing? Any suggestions or anything i am doing incorrectly.
You need to use 'set' or 'notifyPath' while changing Polymer Object or Arrays in javascript for the databinding/obserers to work. You can read more about it in https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#path-binding
In your case try below code
monthView.set('month',json);
Updated suggestions:
Wrap your script on main page with. This is required for non-chrome browsers.
addEventListener('WebComponentsReady', function() {})
This could be scoping issue. Try executing 'document.querySelector('#month-view-element');' inside your callback addWorkHoursCallBack. Also, Use .notifyPath instead of .set.

saveSvgAsPng - getBBox is not a function

I'm using exupero's saveSvgAsPng library to save SVG's to PNG-files, but I've run into a problem when combining it with Angular-Nvd3.
I get an error saying:
Uncaught TypeError: el.getBBox is not a function
Which to me seems like the function cannot "grab" the SVG-element from my nvd3-element.
My code looks like this:
HTML:
<button onclick = "saveAsPng();" type="button" name="button"></button>
<div id = "chart1-canvas">
<nvd3 id = "chart1-svg" options="options1" data="data1"></nvd3>
</div>
Javascript:
function saveAsPng(){
saveSvgAsPng(document.getElementById("chart1-svg"), "diagram.png");
}
Any suggestions on how to make this work properly would be appreciated.
I haven't used that saveSvgAsPng library, but I imagine it expects you to pass it a pointer to an SVG element, not the AngularJS element that surrounds it.
Try the following:
function saveAsPng() {
var svg = document.getElementById("chart1-svg").getElementsByTagName("svg")[0];
saveSvgAsPng(svg, "diagram.png");
}
This worked for me
import saveSvgAsPng from "save-svg-as-png"
let svgDownloadButton = document.getElementsByTagName('button')
svgDownloadButton.addEventListener('click', function () {
console.log("clicked")
var svg = document.getElementById("chart1-svg").getElementsByTagName("svg")[0];
saveSvgAsPng.saveSvgAsPng(svg, "diagram.png");
})

cannot get input value of Struts 2 file selector with Angular

I am using Angular and I want to get access to the file input field's file name attributes and display it in another input box.
This is the file upload field:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="form.filesUpload" multiple="multiple" ng-model="filesUploadModel" id="filesUploadId"/>
</div>
And the input box to show file name:
<input type="text" class="form-control"
id="fileNameId" name="fileName"
ng-model="fileNameModel" ng-disabled="true"
ng-init="" ng-bind="fileNameModel = filesUploadModel">
But the ng-bind is not working.
I also tried to define $watch for the file input field like this:
$scope.$watch(function() {
$scope.files = angular.element(document.querySelector('#filesUploadId'));
return files;
},
function(newValue, oldValue) {
$("#fileNameId").val(files.files[0].name);
});
to watch if the <input type="file" id="filesUploadId"> has changed, select this element and return it as files, and let the element with id fileNameId's value equals to files.files[0].name, because the file upload input has an attribute named files with all the files I upload, and their file names files[i].name.
But FF tells me files is undefined and no avail. It's not working.
Am I doing something wrong here? Please help and thanks!!
Edit: I am using this and no error, but no result either:
if (!angular.equals(document.getElementById("filesUploadId"), null)) {
$scope.$watch(function() {
var myFiles = document.getElementById("filesUploadId");
return myFiles;
},
function(newValue, oldValue) {
$( "#fileNameId" ).val(function(){
var result = null;
$(myFiles).each(function(){
result = name + this.attr(files).attr(name);
});
return result;
});
});
}
I solved it with pure JavaScript, enlighted by another question here:
AngularJs: How to check for changes in file input fields?
Actually, I find it impossible to use onchange() when the function I want to call is wrapped in angular module, except in the way in above answer:
onchange="angular.element(this).scope().setFileName()"
And in my script I only use pure JavaScript, except for the definition of the function:
angular.module('es.redfinanciera.app').controller('PanelMandarCorreoCtrl', function ($scope, $modalInstance) {
....(other functions)
$scope.setFileName = function() {
var result = "";
var adjuntos = document.getElementById("filesUploadId").files;
for (i = 0; i < adjuntos.length; i++){
result = result + adjuntos[i].name + "\r\n";
};
document.getElementById("fileNameId").value = result;
}
}
$scope.btnClean = function() {
document.getElementById("filesUploadId").value = "";
document.getElementById("fileNameId").value = "";
};
And in my jsp page, finally I have my file upload button and a clean button like this:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="correoForm.filesUpload" id="filesUploadId" multiple="multiple" ng-model="filesUploadModel"
onchange="angular.element(this).scope().setFileName()"/>
</div>
<div class="col-sm-2">
<button class="btn btn-default btn-normal" type="button" ng-click="btnClean()">
<s:text name="expedientes.btn.quitar.fichero" />
</button>
</div>
I have a <textarea> to display all the file names:
<textarea class="form-control" ng-model="fileNameModel"
name="fileName" id="fileNameId"
ng-disabled="true"></textarea>
EDIT:
Clear button is not working in IE8 because it is not permitted in IE8 to set "" value to a file input field. My guess is, I can remove this file input field and copy a new one, with same style but no file is selected. But I have found a good question who has amounts of answers here:
clearing-input-type-file-using-jquery
Also, I heard that in IE8 onchange() event will not be triggered if you only select a file, you must add this.blur() after selecting a file. Regarding this issue, IE is following strictly the spec, but FF is not. But in my case, the event is actually triggered. Maybe because I am testing under IE 11 using Developing Tools' emulator for IE8.

How do I change AngularJS ng-src when API returns null value?

In working with the API from themoviedb.com, I'm having the user type into an input field, sending the API request on every keyup. In testing this, sometimes the movie poster would be "null" instead of the intended poster_path. I prefer to default to a placeholder image to indicate that a poster was not found with the API request.
So because the entire poster_path url is not offered by the API, and since I'm using an AngularJS ng-repeat, I have to structure the image tag like so (using dummy data to save on space):
<img ng-src="{{'http://example.com/'+movie.poster_path}}" alt="">
But then the console gives me an error due to a bad request since a full image path is not returned. I tried using the OR prompt:
{{'http://example.com/'+movie.poster_path || 'http://example.com/missing.jpg'}}
But that doesn't work in this case. So now with the javascript. I can't seem to get the image source by using getElementsByTagName or getElementByClass, and using getElementById seems to only grab the first repeat and nothing else, which I figured would be the case. But even then I can't seem to replace the image source. Here is the code structure I attempted:
<input type="text" id="search">
<section ng-controller="movieSearch">
<article ng-repeat="movie in movies">
<img id="myImage" src="{{'http://example.com/'+movie.poster_path}}" alt="">
</article>
</section>
<script>
function movieSearch($scope, $http){
var string,
replaced,
imgSrc,
ext,
missing;
$(document).on('keyup', function(){
string = document.getElementById('search').value.toLowerCase();
replaced = string.replace(/\s+/g, '+');
$http.jsonp('http://example.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
});
imgSrc = document.getElementById('myImage').src;
ext = imgSrc.split('.').pop();
missing='http://example.com/missing.jpg';
if(ext !== 'jpg'){
imgSrc = missing;
}
});
}
</script>
Any ideas with what I'm doing wrong, or if what I'm attempting can even be done at all?
The first problem I can see is that while you are setting the movies in a async callback, you are looking for the image source synchronously here:
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
});
// This code will be executed before `movies` is populated
imgSrc = document.getElementById('myImage').src;
ext = img.split('.').pop();
However, moving the code merely into the callback will not solve the issue:
// THIS WILL NOT FIX THE PROBLEM
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
// This will not solve the issue
imgSrc = document.getElementById('myImage').src;
ext = img.split('.').pop();
// ...
});
This is because the src fields will only be populated in the next digest loop.
In your case, you should prune the results as soon as you receive them from the JSONP callback:
function movieSearch($scope, $http, $timeout){
var string,
replaced,
imgSrc,
ext,
missing;
$(document).on('keyup', function(){
string = document.getElementById('search').value.toLowerCase();
replaced = string.replace(/\s+/g, '+');
$http.jsonp('http://domain.com/query='+replaced+'&callback=JSON_CALLBACK').success(function(data) {
console.dir(data.results);
$scope.movies = data.results;
$scope.movies.forEach(function (movie) {
var ext = movie.poster_path && movie.poster_path.split('.').pop();
// Assuming that the extension cannot be
// anything other than a jpg
if (ext !== 'jpg') {
movie.poster_path = 'missing.jpg';
}
});
});
});
}
Here, you modify only the model behind you view and do not do any post-hoc DOM analysis to figure out failures.
Sidenote: You could have used the ternary operator to solve the problem in the view, but this is not recommended:
<!-- NOT RECOMMENDED -->
{{movie.poster_path && ('http://domain.com/'+movie.poster_path) || 'http://domain.com/missing.jpg'}}
First, I defined a filter like this:
In CoffeeScript:
app.filter 'cond', () ->
(default_value, condition, value) ->
if condition then value else default_value
Or in JavaScript:
app.filter('cond', function() {
return function(default_value, condition, value) {
if (condition) {
return value;
} else {
return default_value;
}
};
});
Then, you can use it like this:
{{'http://domain.com/missing.jpg' |cond:movie.poster_path:('http://domain.com/'+movie.poster_path)}}

Creating a 'More posts...' button in Angular.js

I am currently trying to make a 'show posts' button, for my Angular.js app. I am having trouble in setting the limitTo dynamically from an external script. So far I have:
<body ng-controller="FeedCtrl">
<h1>Feeds</h1>
<div ng-repeat="feed in (feedLoader = (feeds | limitTo:5))">
<p>{{feed.content}}</p>
</div>
<button ng-click="showPosts()">Show more...</button>
</body>
The approach I have taken is this:
$scope.showMorePosts = function () {
$scope.feedLoader = (feeds | limitTo:feedLimit);
}
...then replaced limitTo:5 with limitTo:feedLimit in the inline part of the view.
I have set up a Plunker with the basic setup so far here: http://plnkr.co/edit/OFqkGFKVUHKi2A20c4t3
Any help would be great!
Thanks,
JP
Seems like you were on the right track, but you just needed to define showPosts():
$scope.showMore = function() {
$scope.feedLimit += 1;
}
Full example:
http://plnkr.co/edit/pE49Wt0rvDjWhsKD0WiD?p=preview
HTML
<div ng-repeat="feed in (feedLoader = (feeds | limitTo:feedLimit))">
<p>{{feed.content}}</p>
</div>
<button ng-click="feedLimit = feedLimit + 1">Show more...</button>
JavaScript:
app.controller('FeedCtrl', function($scope) {
$scope.feedLimit = 3;
// ...
});

Resources