The Javascript code is working but I don't know how I can make it work in HTML. I want to link it to an external Javascript file.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
console.log(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
HTML code:
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
I believe you want to print or display the output of that function on the web page.
If that's the case. There are various ways to accomplish this.
Before I go any further, I'd want to point out that you are, in fact, printing something, which is what you intended for your function.
But you can't see it since it's printed in the console.
You may view this by using the F12 key after loading your website.
The console will then appear, and the needed output will be printed.
And here's one method for displaying your output in an HTML page.
You just have to replace your console.log() with the document.write().
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
document.write(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
Here is another method to achieve this.
You can add an html element and change the content of that particular element by using document.getElementById("id name of the element").innerHTML.
Here is the code snippet.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
const largest_word = find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']);
document.getElementById("demo").innerHTML =largest_word
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="findLongestWord.js"></script>
</body>
</html>
Related
So, I want to make a program that will be able to get user data(a ton of bug names separated by commas), go through, get data for each one, then display all of that data in a table. I have been through rewriting this like 5 times and still nothing happens. Anyone know what is wrong with this code?
My html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 align="center">Bugs</h1>
<p>In the area below, type in each of the insects you want information
about, seperate them with a comma.</p>
<textarea id="insects"></textarea>
<br>
<button type="button" id="go">Find out!</button>
<br>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
document.getElementById('go').onclick = function() {
var input = document.getElementById('insects').value;
var splitted = input.split(',');
for (i = 0; i<splitted.length; i++) {
var bug1 = splitted[i];
var part1 = // I need to assign it to bug1 without any whitespace
var finish = part1.toLowerCase();
find1(bug1);
}
}
function find1(bug) {
var xmlDocument = $.parseXML("externalfile:drive-77136639a78ffb21e72c7c4dfe7f7bb73604aeb3/root/Bugs/bugs.xml");
var pain = $(xmlDocument).find("value[type='" + bug + "'] pain").text();
alert(pain); <!-- This is to see if it works -->
}
</script>
</body>
Here is my XML code(btw the XML file is called bugs.xml and yes they are in the same exact folder in My Drive/Bugs:
<?xml version="1.0" encoding="UTF-8"?>
<bugs>
<bug type="blisterbeetle">
<name>Blister Beetle</name>
<pain>55</pain>
<conservation></conservation>
<habitat></habitat>
<rarity></rarity>
<class></class>
<order></order>
<family></family>
<species></species>
<dangerous></dangerous>
<external></external>
</bug>
</bugs>
I have a textarea and I want to know how many lines there are. Now I have searched but I only see this solution:
mytextarea.value.split("\n").length
Well, that works but that's not what I want.
For example my textarea is like this:
When I type this:
123456789abcdefghijkl
sasasasakasasask;as
When I use split("\n").value I get 2 which is correct but if I put this in:
123456789abcdefghijklsasasasasasasasasas
I get the result 1 which isn't correct:
The result should be 2 because there are 2 lines however the line breaks are not created with \n.
Anyone an idea how you can calculate the number of lines INCLUDING the line breaks without \n?
The end of each line, hit Enter . when you hit Enter ,insert \n to line.
<html>
<head>
</head>
<body>
<textarea id="myTxt"></textarea>
<button id ="btn" onclick="myLine()">Try</button>
<p id="x"></p>
<script>
function myLine() {
var txt = document.getElementById("myTxt");
var x = document.getElementById("x");
x.innerHTML =txt.value.split("\n").length;
}
</script>
</body>
</html>
Got it!
static lineCaculator() {
let dummy = document.createElement('div');
dummy.style.font = AutoTextareaResizer.computedStyle.call(this, 'font');
dummy.style.width = AutoTextareaResizer.computedStyle.call(this, 'width');
dummy.style.wordWrap = 'break-word';
dummy.innerHTML = this.value;
document.body.appendChild(dummy);
let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) / this.realLineHeight;
document.body.removeChild(dummy);
return Math.max(1, lines);
}
There are several similar questions, so I hope this is a unique problem. None of the proposed solutions on those similar questions have solved my issue. Humble apologies from this beginner if I messed up somehow.
I have an empty div on my page with I am loading using javascript with strings from an array. Currently, I have a script running on a button which reloads the entire page. I would like for that button to just reload the div with items from my javascript array.
Here is my code:
<html>
<head>
<link rel="stylesheet" href="obliqueStyle.css">
<style></style>
</head>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<body>
<div id="wrapper">
<div id="strategyBox"></div>
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
</div>
<script src="os.js"></script>
</body>
Here is a snippet of my array and the JS (coming from the os.js file referenced in index.html) I am using to load the div initially/on refresh:
var obliqueStrategy = ["Abandon normal instruments",
"Accept advice",
"Accretion",
"A line has two sides"];
var randomStrategy = obliqueStrategy[Math.floor(Math.random() * obliqueStrategy.length)];
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
I've tried calling the same javascript as a function in script in the html like this:
<div id="button">
<a class="againbutton" onclick="buttonReload()">Again</a>
<script>
var buttonReload = function() {
document.getElementById("strategyBox").innerHTML = '<p id="strategyText">' + randomStrategy + '</p>';
}
</script>
</div>
I've tried using the jQuery AJAX load function like this:
<script>
$(function() {
$("#againbutton").on("click", function() {
$("#strategyBox").load("index.html")
return false;
})
})
</script>
I've played around with variations of the above and tried a couple other things that I'm forgetting exactly how and what I did, so I can't include them. I've really hit a wall on this even though it seems profoundly simple.
Thanks in advance for any help.
Here's one method: http://jsfiddle.net/kxqcws07/
HTML
<div id="wrapper">
<div id="strategyBox"><p id="strategyText"></p></div>
<div>
<input type="button" class="againbutton" value="Again">
</div>
</div>
Javascript
//wrapping your logic in a namespace helps reduce the chances of naming collisions of functions and variables between different imported js files
var localNameSpace = function() {
//private array containing our strings to randomly select
var obliqueStrategy = [
"Abandon normal instruments"
, "Accept advice"
, "Accretion"
, "A line has two sides"
];
var api = {
//bindButtonAction binds the generateRandomStrategy function to the click event of the againbutton
bindButtonAction: function() {
$('#wrapper .againbutton').click(api.generateRandomStrategy);
}
, generateRandomStrategy: function() {
//get the position of one of the string randomly
//Math.random() returns a float value < 1 so multiplying it by 100 gets us a range of (0.* - 99.*)
//then we Math.floor() that to get rid of the float value and keep just the integer part
//finally we modulus it with the length of the string array
//if you are unfamiliar with modulus, what it does is gives you the remainder of a division. for instance 10 / 3 gives you 3 with a remainder of 1, so 10 % 3 would be just 1.
//what this does for us is keeps the random offset of our within the bounds of the array length (0 to length -1)
var randomOffset = Math.floor(Math.random() * 100) % obliqueStrategy.length;
//finally once we have the offset, we set the html to the string at the position in the array
$('#wrapper #strategyBox #strategyText').html( obliqueStrategy[randomOffset] );
}
};
return api;
}();
$(document).ready(function() {
//here we call the bind action so the button will work, but we also explicitly call the generateRandomStrategy function so the page will preload with a random string at the start
localNameSpace.bindButtonAction();
localNameSpace.generateRandomStrategy();
});
I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>
I created a javascript program that prints element from my array one by one when you click on the title "click here" , my problem here is that tried to implement a function that deletes a random word from the html page when you click on the words printed previously but it printing other words instead, how can i create a function that removes words printed previously ?
<!DOCTYPE html>
<html>
<head>
<title>function JavaScript</title>
<script >
var k = 0;
var ph = ["red ","blue","black","green","yellow"];
function text(){
if(k < ph.length ){
document.getElementById("test").innerText+=" "+ ph[k];
k++;
}
}
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
</script>
</head>
<body>
<h1 onclick="text();">Click here</h1>
<span id="test" onclick="deleteWord();"></span>
</body>
</html>
function deleteWord(){
var number = Math.floor(Math.random() * 5);
document.getElementById("test").innerText+=" "+ ph[number];
}
Your problem is that the += operator appends " "+ ph[number] after the current value of the string.
To replace instead, use the = operator to assign a new value. since you want to delete, just use an empty string.
document.getElementById("test").innerText = "";
As a side note it is unusual to store multiple spaces in your string. If you are trying to move the contents around, you should probably consider setting the padding-left CSS property instead.
edit: if you don't want to lose the entire contents of the element, you can replace the last part of the string:
document.getElementById("test").innerText.replace(/ .*$/,"");