How do I turn print into <p> - javascript

This is my script:
<script>
import random
import string
def get_random_string(length):
# choose from all lowercase letter
letters = string.printable
result_str = ''.join(random.choice(letters) for i in range(length))
print("Random string of length", length, "is:", result_str)
get_random_string(8)
get_random_string(6)
get_random_string(4)
</script>
I want to turn " print("Random string of length", length, "is:", result_str)" Into text in a paragraph in my website, How do I do so?

I dont really know html.... I need help with that also or just a way
to convert it into js
If you just want to use javascript, in your html file like in your comment, then this is what I think you were trying to do:
function get_random_str(length) {
let result_str = '';
let characters = 'abcdefghijklmnopqrstuvwxyz';
let charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
result_str += characters.charAt(Math.floor(Math.random() *
charactersLength));
}
return result_str;
}
function display_text(elm, str) {
document.getElementById(elm).innerHTML = str;
}
display_text('first', get_random_str(8));
display_text('second', get_random_str(6));
display_text('third', get_random_str(4));
<p id="first">...</p>
<p id="second">...</p>
<p id="third">...</p>
If I misunderstood then my apologies

I found a javascript library that let's you do write basically python instead of javascript; it's called Brython at Brython website. Anyway, I bound your functions to some click event on some buttons. I used JSFiddle to run this sample. Hope it helps.
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.5/brython.min.js">
</script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython#3.10.5/brython_stdlib.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
## https://brython.info/index.html
## Python in place of javascript
from browser import document, alert, console
from browser.widgets.dialog import InfoDialog
import random
import string
def get_random_string(ev):
# choose from all lowercase letter
length = ev.target.id
length = length.replace("button_rand","")
letters = string.printable
result_str = ''.join(random.choice(letters) for i in range(int(length)))
## Inspect your browser page and find console 'tab' at top or bottom...
console.log(result_str)
alert(result_str)
def hello(ev):
alert(ev.target.id)
document["button_alert"].bind("click", hello)
document["button_rand8"].bind("click", get_random_string)
document["button_rand6"].bind("click", get_random_string)
document["button_rand4"].bind("click", get_random_string)
</script>
<button id="button_alert">Say Hello</button>
<button id="button_rand8">Get random 8</button>
<button id="button_rand6">Get random 6</button>
<button id="button_rand4">Get random 4</button>
</body>
</html>

Related

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

JavaScript textarea get numbers of lines (with linebreaks)

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);
}

Concatenate Strings in JavaScript

I Have edited the code, the updated code is below, This code is not able to fetch the keywords meta tag, hence it is not working.
old description: I am trying to concatinate the strings to get the finalUrl, but I am not able to do so becuase of the tags variable. I need to fetch the keywords meta tag of the page and append it to get the finalUrl. Any help?
<script type="text/javascript">
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/details/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = url;
headID.appendChild(newScript);
}
function showGameDetail(feed){
var title = feed.title;
var game_url = feed.pscomurl;
var packart_url = feed.Packart;
$("#bnr-ads-box").html("<img src='"+"http://abc.com/"+packart_url+"'>");
}
loadJSON(finalUrl);
</script>
<div id="bnr-ads-box"></div>
<!DOCTYPE html>
<html>
<head>
<meta id="metaK" name="keywords" content="customizable software for QuickBooks, QuickBooks-integrated, Method customization, CRM accounting, Method for QuickBooks, Method CRM, Method blog, Salesforce automation, Method online platform, QuickBooks customization, web-based platform, industry-specific, customer portal, Method Field Services, Method Manufacturing, ERP" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
document.getElementById("demo").innerHTML=finalUrl;
}
</script>
</body>
</html>
change this
var tags="$('meta[name=keywords]').attr("content");";
to
var tags=$('meta[name=keywords]').attr("content");
also use this code var finalUrl = gameurl + tags + jsn;
What you need is to escape the double quotes inside your tags variable, like so:
var tags="$('meta[name=keywords]').attr(\"content\");";
Cris' solution is also fine, but in some case you will need to have two sets of double quotes inside a string so you will be forced to do escaping correctly.
FYI: Escaping is the process of having special characters getting generated in a string which would otherwise cause issues, for instance in javascript you can't have newlines in a string, like this:
var mystring = 'on
a different line'; // <- this causes a syntax error
So one would do the following:
var mystring = 'on\na different line';
You forgot to include the jquery
<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="hello"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function myFunction()
{
alert("Hello World!");
var tags=$('meta[name=keywords]').attr("content");
var gameurl = "http://xyz/abc/names/";
var jsn = ".json?callback=showGameDetail";
var finalUrl= gameurl.concat(tags).concat(jsn);
alert(finalUrl);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Tough debatable, you can use an array, which can be concatenated by calling join():
var tags = $('meta[name=keywords]').attr("content");
var data = [
"http://xyz/abc/names/",
encodeURIComponent(tags),
".json?callback=showGameDetail"
].join('');
$("#demo").html(data);
Actually the concat method works on strings too (in chrome at least) but the recommended method is using the plus concatenation string operator
You are however missing some stuff
jQuery library - I assume you want that since you have $(...) in the example
encoding of the string from the keywords - I use encodeURIComponent to handle possible newlines and quotes in the keywords
.
<!DOCTYPE html>
<html>
<head>
<title>Create a URL from keywords</title>
<meta name="keywords" content="These are tags" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
function myFunction() {
var tags = $('meta[name=keywords]').attr("content");
var URL ="http://xyz/abc/names/" +
encodeURIComponent(tags) +
".json?callback=showGameDetail";
window.console && console.log(URL);
$("#demo").html(URL);
}
</script>
<body>
<p id="demo">Click the button to join two strings into one new string.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>

deleting random words from html page

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(/ .*$/,"");

how to display only first 10 characters of file name that they upload in the html page

The code to print the file name is
<div id="file">'+filename+'</div>
i want only the first 10 characters of the file name and not the all. what java script function can i use as i cannot use php.
Not sure if you wanted the code for getting the DIV contents as well.
Complete example below:
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="file">I want the first 10 characters</div>
<script>
$(document).ready(function() {
var div = $('#file');
var str = div.text();
var stripped = str .substr(0, 10);
alert(stripped);
});
</script>
</body>
</html>
var str = "this is isdfisdf";
console.log(str.substr(0, 10));
To get the first 10 characters from a string in JavaScript use substr()
var str = str.substr(0,10);
or using substr() in PHP :
$str = substr(str,0,10);

Categories

Resources