In JavaScript, you can use prompt("This text is above the field of the prompt.", "This text is in the field of the prompt.") to get a customized window appearing.
In PythonScript you can trigger the prompt by using input(), but input(“Please enter your name”, “Harry Potter”) doesn't work the way JS does.
So how can I trigger such behaviour?
Edit: Screenshot of what I want.
Here is my simple code, although it isn't necessarily relevant for the question:
HTML
<!DOCTYPE html>
<html lang="de">
<head>
<title>PyScript</title>
<link rel="stylesheet"href="https://pyscript.net/alpha/pyscript.css"/>
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script src="script.py" />
</body>
</html>
PYTHON
print("Enter the elements for comparison like this: Element1, Element2, Element3")
elements_list = input().split(", ")
def swap(list, i, j):
temp = list[i]
list[i] = list[j]
list[j] = temp
for i in range (len(elements_list)-1):
for i in range (len(elements_list)-1):
if input (f"""{elements_list[i]} (type 1) or {elements_list[i+1]} (type 2)?""") == "2":
swap (elements_list, i, i+1)
print("Your order ", elements_list)
To set a default value of input, use the or operator. If the first value is truthy (evaluates to True with bool(...)), it returns the left side, otherwise, it returns the right side.
An empty string, "", is falsy, so it returns whatever's to the right.
The generic way to do this is:
name = input("What is your name?") or "Alex"
print(f"Your name is {name}")
Related
I want to allow a user to select, create a range, and then have javascript remove the underline on the range that the user selects. For example, If I have the code
<u> Hello, my name is Justin, and I have a question </u>
And the user selects "Justin, and I" and hits un-underline, would it be possible to change the HTML to:
<u> Hello, my name is </u>
Justin, and I
<u> have a question </u>
or if the entire sentence is selected, have the entire element deleted and replaced with normal text?
The solution has bugs if selected both underline and normal text at same time, i am trying to fix it.
getSelection() to get selected text.
getRangeAt(0) get selected index in string, remember to +3 because the length of <u> is 3.
Use slice() create new html and replace the old html.
function selected() {
let target = document.getSelection(),
range, res
if (target.toString() === '') return
range = target.getRangeAt(0)
if (range.commonAncestorContainer.parentElement.tagName != 'U') return
res = range.commonAncestorContainer.parentElement.outerHTML
let head = res.slice(0, range.startOffset + 3),
middle = `</u>${target.toString()}<u>`,
tail = res.slice(range.endOffset + 3)
range.commonAncestorContainer.parentElement.outerHTML = head + middle + tail
}
document.onmouseup = selected;
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<u>Hello, my name is Justin, and I have a question</u>
</body>
</html>
I have this assignment for school and it really looks simple because the instructions are given, but I am having trouble solving it. Nothing gets displayed on my web page after pressing the search button.
Here it is:
Write a JavaScript script called "CharacterOccurences.JS” that inputs several lines of text and a search character and uses String method indexOf() to determine the number of occurrences of the character in text.
A) You have to use the external CSS file called "CharacterOccurences.CSS" to set the margin of the paragraph to the value 0 (zero).
B) You have to declare in your HTML form four (04) ids:
a. "searchString" as textarea id in paragraph with 4 rows and 55 columns
b. "characters" as input id in paragraph with text type and size equal 5
c. "searchButton" as input id in paragraph with button type and its value
equal "Search"
d. "output" as id in paragraph is for the final result.
C) The JavaScript file (CharacterOccurences.js) contains three (03) global variables and two (02) functions:
a. Global variables :
i. searchStr to get the id of "searchString"
ii. ch to get the id of "characters"
iii. outResult to get the id of "output"
b. The function getAllDomElement() that
i. Accesses the "searchButton" element and adds the search button using its id by using the existing the function addEventListener(), which takes three (03) arguments: (a) the name of event as a string literal (here is "click"), (b) the function searchOccurrences, and (c) the Boolean value false.
ii. Gets all id elements of "searchString", "characters", "output" using the existing function getElementById()
c. The function searchOccurrences() to search the character we look for and count the number of occurrences of that character.
i. 4 local variables: count, chValue, searchStr, result.
ii. Use the functions: charAt( 0 ), toLowerCase() and indexOf().
iii. If the variable count equal 0 (zero) display the message: the character ch not found. Otherwise display the result.
D) At the end of the JavaScript file, finish with this line to fire the load event when a resource and its dependent resources have finished loading:
window.addEventListener( "load", getAllDomElement, false );
Here is my script in the html and js files:
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Assignment3Q1 </title>
<meta charset = "utf-8">
<script type = "text/javascript" src = "CharacterOccurences.js">
</script>
<link rel = "stylesheet" type = "text/css" href = "CharacterOccurences.css"/>
</head>
<body>
<p> Enter some text: <br>
<textarea id = "searchString" rows = "4" cols = "55"></textarea>
</p>
<p> Enter characters to search for: <br>
<input type = "text" id = "characters" size = "5" />
<input type = "button" id = "searchButton" value = "Search" onclick = "getAllDomElement();"/>
</p>
<p id = "output">
</p>
</body>
searchStr = document.getElementById("searchStr");
ch = document.getElementById("characters");
outResult = document.getElementById("output");
function getAllDomElement()
{
document.getElementById("searchButton").addEventListener("click", searchOccurences, false);
searchStr = document.getElementById("searchStr");
ch = document.getElementById("characters");
outResult = document.getElementById("output");
}
function searchOccurences()
{
var count = 0;
var chValue = ch.chartAt(0).toLowerCase();
var searchStr = searchStr.toLowerCase();
var result;
}
window.addEventListener("load", getAllDomElement, false);
You see that I haven't completed the searchOccurences() function. I attempted to go through a for loop and increment count every time I find an occurrence of the letter entered, but nothing gets displayed when I press Search. It's supposed to look like this:
I am currently doing a school project and i need to stimulate a server side application. What i am substituting it with is "Local Storage" but i have an issue. I am able to have the text in my "Text box" stack on top of each other once user have submitted their question. Once they reload, the data will still be displayed. But i do not know how to stack on top of it AGAIN after they reload. Below is my testing code
<!doctype html>
<html>
<head>
<body onload="display()">
<input type="text" id="Name"></input>
<input type="submit" id="submit" onclick="SavetoStorage()"></input>
<p id ="hoho">
</p>
<script>
var name;
var groupOfName = ["Hello", "Chicken", "Pork","Beef"];
function SavetoStorage() {
var name = document.getElementById("Name").value;
groupOfName[groupOfName.length] = name;
var newone = groupOfName;
document.getElementById("hoho").innerHTML = newone;
localStorage.groupOfName = newone;
}
function display() {
var groupOfName = localStorage.groupOfName;
document.getElementById("hoho").innerHTML = groupOfName;
}
</script>
</head>
</body>
</html>
You need to be dynamically loading the groupOfName variable like so:
var tmp = localStorage.groupOfName; //this is a string
var groupOfName = Array.from(tmp); //turn it into an array
Hopefully this helps to point you in the right direction
You can use the setItem method from localstorage.
It uses 2 parameters:
a key and a value
so you can do something like this:
var inputValue = document.getElementById("Name").value;
localStorage.setItem("name", inputValue);
The above code sets the key "name" and that key holds the inputValue
So now you can retrieve the value by calling another local storage method called getItem:
var retrieveValue = localStorage.getItem("name");
The above code retrieves the item, and what does that item holds? the value from the input, so now you can add it to your html as you wish
So that's the basics but as you only have 1 input the value will be getting overwrited, and LocalStorage doesn't supports arrays but there's a workaround so you can use arrays, it goes something like this:
//this first part converts your array to string
localStorage.setItem("names", JSON.stringify(names));
//The second part returns your item and coverts it to an array again
var storedNames = JSON.parse(localStorage.getItem("names"));
First off, thanks for anyone's help on this. I have an input id #Mailer_Code. I want to submit a specific value based on whether this mailer code value matches the user's value or not, and create 2 different IDs based on whether this value is valid or not.
In general terms:
ID is 1234;
if Mailer_Code is yourock, then ContactID is DWID
if Mailer_Code is not yourock, then ContactID is WWID
I would really appreciate if "yourock" was some sort of comma separated list so the Mailer_Code could be any of the specified values. ie. #Mailer_Code = "yourock, or yourawesome, or supercool, etc." (not case sensitive)
Also, if the #Mailer_Code is anything other than the list of allowed values, it simply returns a #Mailer_Code of "none" and WW1234.
So far I'm here:
if ( $('#Mailer_Code').val = "yourock" ) {
contactSource = "DW";
mailer_true_false = "true";
}
else {
contactSource = "WW";
mailer_true_false = "false";
$("#Mailer_Code").val('0');
}
Any help is much appreciated. Thanks for reading.
The following should get you started.
Note that instead of a comma separated list of valid values I added them to an array. jQuery has a very useful array function inArray that makes checking the values a simple matter.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div>
<span id="Mailer_Code">yourock</span>
<span id="Id">1234</span>
</div>
<span id="ContactId"></span>
<script type="text/javascript">
var arr = [ "yourock", "youareawesome", "youarethebest" ];
var inListPrefix = "DW";
var outListPrefix = "WW";
var mailerCode = $("#Mailer_Code").text();
var pre = "";
if (jQuery.inArray(mailerCode, arr) >= 0)
{
pre = inListPrefix;
}
else
{
pre = outListPrefix;
$("#Mailer_Code").text("none");
}
$("#ContactId").text(pre + $("#Id").text());
</script>
</body>
</html>
I wrote this function which takes in a word as input and puts it in a <b> tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the <b> tag arround it.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
On providing the value and input, e.g. "message" and "This is a test message":
The output is: This is a test <b>message</b>
The desired output is: This is a test message
Even replacing the value with value.bold(), returns the same thing.
EDIT
This is the HTML together with the JS that I m working on:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="knorex"/>
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.
Is it possible there is something wrong with the way I'm taking back what the function is returning to me?
This is what I do:
children[child].nodeValue = output;
You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement
children[child].nodeValue= output;
by the following:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);