<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for(let i = 0; i < aR.length; i++){
value += aR[i]['name'] + ": " + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
For some reason my code seems to never reach the third document.getElementById statement. The value for that third statement is supposed to be value not the string hi; I thought the initial problem was with value so I set content-3 as the string "hi" but now I've realized that my script doesn't even run till that point.
Does anyone know what is going on and how to fix it?
as Muhammad Asif said, its aR declare?
for example just add these and will work
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
all the code for example
<div id="content-1"></div>
<div id="content-2"></div>
<div id="content-3"></div>
<script type="text/javascript">
var aR = {
0: { name: "XX", price: "55" },
1: { name: "YY", price: "55" }
};
// Write HTML with JS
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
document.getElementById("content-2").innerHTML = 'hello';
let value = '';
for (let i = 0; i < aR.length; i++) {
value += aR[i]['name'] + ":" + aR[i]['price'] + "<br/>";
}
document.getElementById("content-3").innerHTML = 'hi!';
</script>
by declaring the aR object will run all the code
first of all, only run this line and check whether your script is running or not.
document.getElementById("content-1").innerHTML = '<h1>Title</h1>...and more';
check, is this line is displayed?
second, What is this aR? Did you declare it before?
aR.length;
Related
I'm new to JavaScript and am trying to work through some errors. I've researched sites and made a few changes but still having trouble. Any assistance is appreciated.
The goal is to take selected items on a SharePoint list and click a button that will open an email with list data.
The errors are below:
SCRIPT1002: SCRIPT1002:
HTML1423: Malformed start tag. Attributes should be separated by whitespace.
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
HTML1422: Malformed start tag. A self closing slash should be followed by a U+003E GREATER-THAN SIGN (>).
HTML1423: Malformed start tag. Attributes should be separated by whitespace. Email.aspx (807,105)
HTML1409: Invalid attribute name character. Attribute names should not contain ("),('),(<), or (=).
Here's the latest code...
<script type="text/javascript"> </script>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
<button #click="clickMethod()">Send Email</button>
I recommend splitting out the javascript into separate files. Then you'd just need to do <script src='/my-new-file.js'></script> in the html file instead of mixing and trying to match like what's happening at the moment.
Alternatively if you want to keep it like you have it now, on the first line, removing the closing script tag and move all of the other script tags outside. Like this:
<body><button #click="clickMethod()">Send Email</button>
<script src=".../jquery-1.12.4.js"</script>
<script src=".../jquery.min"</script>
<script src=".../sprestlib.bundle.js"</script>
<script src=".../vue.min.js"</script>
<script src=".../jquery-3.5.1.js"</script>
<script type="text/javascript">
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
sprLib.list('DRLs').items({
listCols: {
iD: {dataName:'ID'},
drlId: {dataName:'Title'},
artifactIdCopy: {dataName:'ArtifactID'},
assessmentId: {dataName:'AssessmentIDCopy'},
dueDate: {dataName:'TaskDueDate'},
AOREmails: {dataName:'AOREmails'},
startDate: {dataName:'Assessment_x0020_ID_x0020_LU_x00'},
teamMemberEmails: {dataName:'TeamMemberEmails'},
artifactLink: {dataName: 'Artifact_x0020_Link'},
drlItemLink: {dataFunc:function(objItem){return 'View DRL'}}
},
queryOrderby: 'Title';
})
.then(findSelectedItems(arrData, items);
.catch(function(errMsg){console.error(errMsg) });
}
function findSelectedItems(spData, selectedItems){
var emailBody = '';
for(var i = 0; i < selectedItems.length; i++){
var itemID = selectedItems[i].id;
for(var j = 0; j < spData.length; j++){
if (spData[i].iD == itemID){
emailBody += "Title: " + spData[i].drlId + "\r\n";
}
}
}
sendMail(emailBody);
}
function sendMail(bodyString) {
var message = encodeURIComponent(bodyString);
//var yourMessage = document.getElementById('AORNames');
var subject = document.getElementById('DRLID').value;
var emails = document.getElementById('AOREMails').value;
var mail = "mailto:" + emails + "?subject=" + subject + "&body=" + message;
window.location.href = mail;
}
</script>
</body>
Just before your function clickMethod you are missing a starting <script> tag. That's why it says malformed start tag. It's missing. Hope that helps.
I have a code, in which I try to achieve needed string("Hey!") by randomizing characters (brute-forcing the string), and to display all steps in a <p>(next step overwrites previous one). The problem is, however, that in the #first, there is only displayed the final step of permutations ("Hey!").
Why doesn't it displays all steps one after one, only the last one? I will appreciate any help on that problem.
Note: in the console, all steps are logged. I also tried outputting string in <p> with timeout; nothing changed.
Example of what has to be: https://i.imgur.com/fNjhjUS.gif
Here's my Javascript code and HTML:
var fline = ["H", "e", "y", "!"];
temp_fline = [" ", " ", " ", " "],
index = 0,
possible = "!abc!defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ!";
while (index < 4)
{
if (fline[index] != temp_fline[index])
temp_fline[index] = possible[Math.round(Math.random() * 57)];
if (fline[index] == temp_fline[index])
++index;
var tempString = "";
for (var i = 0; i < 4; ++i)
tempString += temp_fline[i];
console.log(tempString);
document.getElementById("fline").innerHTML = '> ' + tempString;
}
<html>
<body>
<div id="first">
<br>
<p id="fline"></p>
<br><br><br>
<p id="sline"></p>
<br><br><br>
<p id="tline"></p>
<br><br><br>
<p id="fhline"></p>
</div>
</body>
</html>
Want like that?
var fline = ["L", "i", "k", "e", " ", "t", "h", "i", "s", "?"], count = 0, index = 0, flist = [],
possible = "!abc!?defghijklmnopqrstuvwxyz!ABCDEFGHIJKLMNOPQRSTUVWXYZ! ";
let found = document.getElementById("found");
let checking = document.getElementById("checking");
let timer = setInterval(function ()
{
if (index >= fline.length)
{
console.log(flist);
clearInterval(timer);
checking.innerText = "";
flist = [];
}
else
{
if (fline[index] == possible[count])
{
found.innerText += possible[count];
flist.push(possible[count]);
index++; count = 0;
}
else
{
checking.innerText = possible[count];
count++;
}
}
}, 24);
<div><b id="found"></b><i id="checking"></i></div>
You are overwriting the innerHTML in every iteration of loop rather than adding to it
Try changing
document.getElementById("fline").innerHTML = '> ' + tempString;
To
document.getElementById("fline").innerHTML += '> ' + tempString;
// ^^ concatenate instead of reassign
I have a text file which contains list of dates and respective events, which looks as follows,
txt:
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
At first, I am using a simple split function to split the contents of the text file,
var text=xmlhttp.responseText;
var amber=text.split(':');
In the amber array each date and events are stored simultaneously, what I need to do is access the dates alone and split the day, month and year, I tried using the following code
var stwo="";
for (var i = 0; i < amber.length; i += 2) {
stwo = amber[i].split('-');
}
but when I try to access the contents of stwo[] it shows "undefined", I've also tried declaring stwo like this
stwo=[" "," "];
because I thought stwo wasn't defined as an array, what have I done wrong? Is there any other way I can split the dates?
here is my complete code.,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<title>SAPUI5 EVENT CALENDAR</title>
<script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap" data-sap-ui-libs="sap.m,sap.ui.layout,sap.me"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-theme="sap_bluecrystal"></script>
<script>
jQuery.sap.require("sap.me.Calendar");
jQuery.sap.require("sap.m.RadioButton");
calendar = new sap.me.Calendar({
firstDayOffset : 1
});
var xmlhttp,text;
xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET','C:/Users/Manimaran/Desktop/project/nn.txt',false);
xmlhttp.send();
var text=xmlhttp.responseText;
var amber=text.split(':');
for (var t = 0; t < amber.length; t+=2)
{
calendar.toggleDatesType([amber[t]],sap.me.CalendarEventType.Type07,
true);
//document.write(a[i+1]+"<br>");
}
calendar.toggleDatesType([ "2017/05/15" ],
sap.me.CalendarEventType.Type07,
true);
var msgLabel = new sap.m.Label({
width : "100%"
});
calendar.attachTapOnDate(function(oEvent) {
/* date=oEvent.getParameters().date;
msgLabel.setText(date)*/
});
calendar.attachChangeCurrentDate(function(oEvent) {
var stwo=[" "," "];
for (var i=0;i<amber.length;i+=2)
{
stwo=amber[i].split('-');
}
/*for (var j=1;j<stwo.length;j+=3)
{
switch(stwo[j]){
case '01' : stwo[j]="Jan";
break;
case '02' : stwo[j]="Feb";
break;
case '03' : stwo[j]="Mar";
break;
case '04' : stwo[j]="Apr";
break;
case '05' : stwo[j]="May";
break;
case '06' : stwo[j]="Jun";
break;
case '07' : stwo[j]="Jul";
break;
case '08' : stwo[j]="Aug";
break;
case '09' : stwo[j]="Sep";
break;
case '10' : stwo[j]="Oct";
break;
case '11' : stwo[j]="Nov";
break;
case '12' : stwo[j]="Dec";
break;
default:"gokka makka";
}
}*/
var comp=oEvent.getParameters().currentDate;
var tmp=comp.split(' ');
if(tmp[1]==tmp[1]){
msgLabel.setText(stwo);
alert(stwo[1]);
}else{
alert('error');
}
});
var unselectBtn = new sap.m.Button({
text : "unselect all",
press : function() {
var aDates = calendar.getSelectedDates();
calendar.unselectAllDates();
msgLabel.setText("unselected " + aDates.length + " dates");
alert(text);
}
});
var app = new sap.m.App();
var page = new sap.m.Page({
headerContent : unselectBtn,
content : [ calendar, new sap.m.Label({
width : "100%",
text : "Messages log"
}), msgLabel]
});
// Colgate: weeks start on sunday, and show 2 months
calendar.setSingleRow(false);
calendar.setMonthsToDisplay(1);
// calendar.setWeeksPerRow(1);
calendar.setMonthsPerRow(1);
calendar.setFirstDayOffset(0);
app.addPage(page);
app.placeAt('content');
</script>
</head>
<body class='sapUiBody'>
<div id='content'></div>
<p id="display"></p>
</body>
</html>
You are just assigning the value to stwo every time..
So all the split values before the last one will be lost.
Also the last string in the split(':') would be empty because after the last : there is nothing in the give string.
So finally nothing will be assigned to stwo.
Check this snippet
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo;
console.log(amber);
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "") {
stwo = amber[i].split('-');
}
}
console.log(stwo);
If you can see, even if check for empty strings.. Only the last date will be split and added to the variable stwo.
To store each split value you can use an Array within an Array (MultiDimesional array)
var text = "2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:";
var amber = text.split(':');
var stwo = new Array();
console.log(amber);
var j = 0;
for (var i = 0; i < amber.length; i += 2) {
if (amber[i] != "" && amber[i].indexOf('-') > 1) {
stwo[j] = amber[i].split('-');
j++;
}
}
console.log(stwo);
You parse through each log line like so:
// ES6
const txt = `
2017-05-01: All Day Event:
2017-05-06: Day Event:
2017-05-15: abc Event:
2017-06-05: All Event:
2017-06-03: Al Event:
`
const amber = txt.trim().split('\n');
const logDates = amber.map(line => line.split(':')[0]);
const logDatesSplitted = logDates.map(logDate => logDate.split('-'));
console.log(logDatesSplitted);
// ES5: Fast Splitting by colon
var amber_ = txt.trim().split(':');
var logDates_ = [];
for(var i = 0; i < amber_.length; i += 2) {
if(amber_[i] == "") continue; // filter out last empty log record;
var logDate = amber_[i].trim().split('-');
logDates_.push(logDate);
}
console.log(logDates_);
Checkout this
var test = '2017-05-01: All Day Event:2017-05-06: Day Event:2017-05-15: abc Event:2017-06-05: All Event:2017-06-03: Al Event:';
test = test.replace(/:+$/g,"");
var test1 = test.split(':');
var test2 = [];
for (var i = 0; i < test1.length; i += 2) {
test2.push(test1[i].split('-'));
//console.log(test2);
}
console.log(test2);
In firebug console 10 paragraphs is displayed in the source code of the page, but only the first one contains text.
It looks like the loop inserted the text each time into the same paragraph, overwriting it's value. How to insert the text into each paragraph?
(function(){
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
new_par.id = "new_par";
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Hello" + " " + names[name];
}
}
})();
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
<div id="greeter"></div>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</body>
</html>
The problem is that you are creating ten nodes with the same id, new_par, so you are always getting a reference to the first #new_par when you do
document.getElementById("new_par").innerHTML
The simplest solution will be to use the reference you already have, no need to call getElementById.
new_par.innerHTML = ...
The problem is that each paragraph has the same id. I added a counter variable, to add at the end of id...
(function(){
var counter = 0;
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
var par_id = "new_par" + counter;
new_par.id = par_id;
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById(par_id).innerHTML = "Hello" + " " + names[name];
}
counter++;
}
})();
I'm doing this for a school project but one thing is bugging me, there is a part of the project that requires me to change white space or just " " a space to a number. Here is my code:
I know its messy, I've only been coding for half a year
exclsp is "exclude spaces"
inclsp is "include spaces"
dispwos is "display without spaces"
dispwsp is "display with spaces"
var txt;
var num;
var spce = 0;
function cnt()
{
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked === true)
{
for (var i = 0; i < num; i++) {
if (txt.includes(" "))
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
}
}
document.getElementById("dispwos").innerHTML = num - spce + " characters.";
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="LetterCount.js"></script>
<link rel="stylesheet" type="text/css" href="LetterCount.css"/>
<title>Letter Counter</title>
</head>
<body>
<textarea rows="4" cols="50" placeholder="Input your text here!" id="disp"></textarea><br>
<form name="form1">
<input type="radio" name="button" id="inclsp"> Include spaces</input><br>
<input type="radio" name="button" id="exclsp"> Exclude spaces</input><br>
</form>
<button onclick="cnt()">Click Me!</button><br><br>
<div id="dispwsp"></div>
<div id="dispwos"></div>
</body>
</html>
I think you need to change this line:
if (txt.includes(" "))
to
if (txt[i] == " ")
so that you're actually checking each character rather that attempting to examine the whole string each time.
You could also use a regular expression and do it in one simple line of code and eliminate the loop altogether:
spce = txt.match(/\s/g).length
I don't understand the purpose of the dispwsp dispwos so I just removed them. You only have 1 result you want to display so why put it in different places just make one div for your result, like
<div id="result"></div>
And your JS can be simplified a lot, you don't need to loop through the letters. Here's the fiddle: https://jsfiddle.net/zwzqmd27/
function cnt() {
var inputText = document.getElementById("disp").value;
if (document.getElementById("exclsp").checked) //exclude spaces
{
document.getElementById("result").innerHTML = inputText.split(" ").join("").length + " characters";
}
else //include spaces
{
document.getElementById("result").innerHTML = inputText.length + " characters";
}
}
Possible duplicate of Check if a string has white space
But you can try this.
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
If You want to change a white space in a string to a number..
This could possibly help you ...
str.replace(/\s/g,"9");//any number(that You want)
This piece of code is basically replaces the white space with a number..
As #Micheal said, you can use indexOf() method to check if particular character(s) is present in your text content.
You just need to pass the character or substring(set of characters) to check if it is present.
Example :
var myText = "Sample text";
var substringIndex = myText.indexof(" "); //substringIndex = 6
substringIndex = mytext.indexof("ex");//substringIndex = 8;
substringIndex = mytext.indexof("tt"); // substringIndex =-1;
If substring doesn't matches, it will return -1 as index.
By using index you can say, if particular character(substring) presents if index value is greater than -1.
Note : If u pass set of characters, it will return only the starting index of the first character if entire set matches.
In your case, it would be like
...........
...........
if (txt.indexOf(" ")>-1)
{
// alert("THERES A SPACE HERE");
spce++;
}
else
{
num = num;
}
...............
...............
Just replace script with code bellow..
I do it for you...
var txt;
var num;
var spce = 0;
function cnt()
{
//to clear "dispwsp" and "dispwos" before action in cnt() function
document.getElementById("dispwsp").innerHTML = "";
document.getElementById("dispwos").innerHTML = "";
txt = document.getElementById('disp').value;
num = txt.length;
// includes spaces into the returned number
if (document.getElementById("inclsp").checked == true)
{
document.getElementById("dispwsp").innerHTML = num + " characters.";
}
// excludes spaces from the returned number
if (document.getElementById("exclsp").checked == true)
{
num = 0;
spce = 0;
for (var i = 0; i < txt.length; i++) {
var temp = txt.substring(i, (i+1));
if(temp==" ")
{
spce++;
}else
{
num++;
}
document.getElementById("dispwos").innerHTML = num + " characters and "+ spce +" spces ";
}
}
}