I am trying to create an array that pass one item waits for a response from my node server from a list.
My data input to JavaScript is from a text area in html then I am trying to send each line one at a time it can only send the next array item when my nodeJS has finished can anyone show me any example's or ways to post an array one item at a time.
instead of in one big chunk like I am getting currently.
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
my full html
<html>
<html>
<head>
<title>Welcome To ....</title>
<script src="js/socket.io.js"></script>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
socket.emit("dout", { message : msg[i] } );
}
// the old code
// document.getElementById("message").innerHTML = msg.join("
");
}
</script>
<script>
var socket = io.connect("https://json2-c9-ashg1990.c9.io");
socket.on("news", function(data) {
document.getElementById("message").innerHTML = JSON.stringify(data.hello);
});
// socket.emit("my other event", { message : "client emit" } );
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body>
</html>
Well, you code seems OK, except the regexp you use.
You should split the string using \n character. You are using \n\r, which is not a Windown line break character sequence.
Window character sequence is \r\n.
See here: http://www.regular-expressions.info/nonprint.html
Related
I am trying to build a simple dashboard where if user access their dashboard it will show data from the google spreadsheet. But There is one problem I don't know why only my first div is getting target via JavaScript not the second one..
any Help and solution would apricated..
Why My Second Line Targeting div id="load1" is not executing ????
Code.gs
`function loadDetails(id){
var ss = SpreadsheetApp.openById("14RM_170AefKbQq82NXAdSOemQLyAGcv_BTwYWd1-qtM")
var ws = ss.getSheetByName("Data")
var data = ws.getDataRange().getValues()
for(var i=0; i<data.length; i++){
var row = data[i]
if(row[0]== id){
password = {
psd: row[1],
id: row[0]
}
}
}
if(row[0]!= id){
password = "not found"
}
return password;
}`
Dashboard.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hey this is other Employee Dashboard</h1>
<p>Your Employee Id: = </p>
<p>Your Password : = </P>
<div id="load">
<div>
<div id="load1">
<div>
<script>
window.onload = function(){
var id = "MN00018"
google.script.run.withSuccessHandler(function(output){
document.getElementById("load").innerHTML = `passing objects are ${output.psd} & ${output.id}`
document.getElementById("load1").innerHTML = `passing objects are ${output.id}`
}).loadDetails(id)
}
</script>
</body>
</html>
If you are actually testing your showing script, I think that there are 2 modification points.
HTML & Javascript side:
The tag of div is not enclosed. How about modifying as follows?
From:
<div id="load">
<div>
<div id="load1">
<div>
To:
<div id="load">
</div>
<div id="load1">
</div>
I think that this is the reason of your issue of Why My Second Line Targeting div id="load1" is not executing ????.
Google Apps Script side:
At Google Apps Script side, by if(row[0]!= id){password = "not found"}, even when id is found from the column "A", "not found" is returned. How about modifying as follows?
Modified script:
function loadDetails(id) {
var ss = SpreadsheetApp.openById("###");
var ws = ss.getSheetByName("Data")
var data = ws.getDataRange().getValues()
var password = {psd: "", id: ""};
for (var i = 0; i < data.length; i++) {
var row = data[i]
if (row[0] == id) {
password = {
psd: row[1],
id: row[0]
}
break;
}
}
return password;
}
i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>
I need some help because my callback function, parseMovie() is only being called once! Despite being in a for loop which iterates it twice. I am using a free Rottentomatoes API
The output only returns one ID, and not two ID's!
And runs parseMovie() only once and returns the movie ID with the last movie.
Does anyone have a fix for this script running problem?
HTML CODE
<!doctype html>
<html class="no-js">
<head>
<title>Movies</title>
<link rel="stylesheet" href="css/main.css">
<script src="js/main.js"></script>
</head>
<body>
<form name="input">
<p> Actor/Actress Name: <input type="text" name="fullName"> </p>
<p> Movie 1 <input type="text" name="movie"> </p>
<p> Movie 2 <input type="text" name="movie"> </p>
<p><input type="button" value="Search movies" onclick="getMovies()"></p>
<p><textarea name="output" readonly> </textarea> </p>
</form>
</body>
</html>
JAVASCRIPT
//api key
var APIKEY = "qf54ubt95fea9n7jytr5xh6h";
var movieID = new Array();
var actor = new Array();
var actorName = "Jennifer Lawrence";
var movieTitle;
var output;
function callScript(call) {
var script = document.createElement('script');
script.setAttribute("src", call);
document.body.appendChild(script);
}
function getMovies() {
for (var x=0; x<2; x++) {
movieTitle = document.getElementsByName('movie')[x].value;
movieTitle= cleanMovieTitle(movieTitle);
var movieURL = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=";
callScript(movieURL + movieTitle + "&page_limit=10&page=1&apikey=" + APIKEY + "&callback=parseMovie");
}
}
function cleanMovieTitle(movie) {
movie = movie.trim();
movie = movie.replace(/ /g, "+");
return movie;
}
function parseMovie(data) {
var titleData = data.movies;
for (var t=0; t<titleData.length; t++) {
movieID[movieID.length] = titleData[t].id;
aCast = titleData[t].abridged_cast;
sample = [];
for (var person = 0; person < aCast.length; person++) {
sample[sample.length] = aCast[person].name;
}
actor[actor.length] = sample;
}
for (var arry = 0; arry < actor.length; arry++) {
if (actor[arry].indexOf(actorName) >= 0) {
output = movieID[arry];
break;
} else {
alert("spelling error of some sort! Error 404");
}
}
document.input.output.value = output;
}
Your statement var titleData = data.movies; is wrong, because the data returned by the API contains an array of movies.
You have to iterate through data.movies to get the data for the other movies (and not only the first one).
See the raw JS code and JSON data returned by the API: api.rottentomatoes.com
Three things that strike me as odd that might be causing the problem.
Using for…in for an array is considered bad practice, especially when there's a native forEach method and a polyfill for ie8-
cleanMovieTitle isn't doing anything because it doesn't return a value. If you were passing it an array or object, it would pass by reference and it would be altered, but that is considered bad practice for the exact reason that it's not working. You're passing a value, the function modifies that value within the function's scope, then does nothing with it. You need to return the string and set movieTitle = cleanMovieTitle(movieTitle); So maybe the API isn't returning for one of the titles because it hasn't been cleaned. See Passing by Reference or by Value.
The callback may be is getting called again before it finishes running. Not sure on this one, but you could check by flooding the loop with console.logs and seeing whether it's the case.
Edit
So I just ran your script on this page and I'm getting an error on document.input.output.value = output; As expected, parseMovies runs twice when I remove this line. What's document.input?
Problem : So I have alerted the value of textarea by:
var source = document.getElementById('source').value;
alert(source);
But the value of textarea is alerted as it was at the time of page load. And I want to alert current value of the textarea. I have also tried
$("form").submit(function(){
But that also haven't helped me. So how can I do this?
This is my code.
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="http://code.guru99.com/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="http://code.guru99.com/Perl1/codemirror.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
So how can I get the current value of the textarea? Please help me guys.
I'm not familiar with CodeMirror, but what you exactly see on the screen, is not your original #source anymore. Instead there are several elements created by CodeMirror, and the original textarea is hidden.
When I look at the documentation, I found this:
var source = editor.doc.getValue();
alert(source);
Or, since you've constructed the editor object with fromTextArea() method, you can update the value of the the textarea before reading it:
editor.save();
var source = document.getElementById('source').value;
alert(source);
Notice also what Adam has said about submitting the form. And there are invalid </br> tags in your HTML, the correct form is <br />.
Please visit at CodeMirror User Manual for the furher information.
As you have jQuery loaded you can do as follows:
var content = $('#source').val();
alert(content);
Of course, if you do it at page load, the textarea will be empty (or even uncreated). You could extract its content on form submit, as you seem to suggest.
This code will create a button that will alert the content of your textarea when clicked:
<button onclick="alert($('#source').val())">Click me</button>
Try the following inside the submit()
var textAreaVal = $("#print-result").val();
alert(textAreaVal);
Your form does not get submitted when the button in it is pressed since this is not a submit button.
This will not submit the form, and will not alert its' contents.
<input type="button" value="Run" onclick="execute()"/></br>
Add something like this in the form:
<input type="submit" value="Submit">
if yout want the value to alert when the mouse leaves the textarea you could try to add onblur="myFunction()" to the input something like: (actually if you want it on mouse leave, you can add onmouseout="myFunction()")
<textarea id="source" cols="70" rows="10" onblur="myFunction()">
say 'h';
</textarea>
<script type="text/javascript">
function myFunction() {
var source = document.getElementById('source').value;
alert(source);
}
</script>
I am trying to read a local file called start.txt
If I reach a point where the first line is nextpage, it'll do something but if isn't it will append to a textarea. However it gives me an error:
Uncaught TypeError: Cannot read property 'inputtext' of undefined (23:44:44:520 | error, javascript)
at (public_html/index.html:12:50)
The file that I am trying to read is in the same folder as the index.html file. I am fairly new to HTML, AJAX and JavaScript so I might possibly just not know what the frak I am doing!
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>
<script type="text/javascript">
var txtFile = new XMLHttpRequest();
var inputarea = document.textareaform.inputtext.value;
txtFile.open("GET", "http://localhost/start.txt", true);
txtFile.onreadystatechange = function() {
// Makes sure the document is ready to parse.
if(txtFile.readyState === 4) {
// Makes sure it's found the file.
if(txtFile.status === 200) {
allText = txtFile.responseText;
// Will separate each line into an array
lines = txtFile.responseText.split("\n");
for(i = 0; i < lines.length; i++) {
var s = lines[i];
if(s.indexOf("nextpage") > -1) {
// Line is there
} else {
// Line is not there
inputarea += s;
}
}
}
}
};
txtfile.send(null);
</script>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="textareaform">
<textarea name="fileoutput" rows="4" cols="20" readonly="readonly">
</textarea>
</form>
<div>TODO write content</div>
</body>
</html>
It's looking for a textarea named "inputtext", and you've named it "fileoutput".
Try renaming your textarea to "inputtext":
<textarea name="inputtext" rows="4" cols="20" readonly="readonly"></textarea>
or
define your variable differently:
var inputarea = document.textareaform.fileoutput.value;
change the var inputarea declartion to this.
var inputArea = document.getElementsByName('fileoutput');
Hope this helps.