Search occurences of a character in the text given by the user - javascript

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:

Related

Clear formatting in range without using document.execCommand('removeFormat')

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>

specific text in prompt for pythonscript

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

Javascript how to assign a data field to a variable

I have this code in my HTML code. I'm trying to assign a field to a variable and then show it in my HTML code. What I'm trying to accomplish is showing in my HTML code just the last four digits of the 'ID' data field, right now shows 8 digits. This is my code:
<body onload="myFunction()">
<script>
function myFunction()
{
var str = ID //'ID' IS A DATA FIELD BUT 'STR' VARIABLE DOESN'T TAKE IT**
var res = str.substring(5, 8);
document.getElementById("javi").innerHTML = res;
}
</script>
And then I call it int the html body
<p id="javi"></p>
var str = document.getElementById('Javi').textContent
should get you the text of your p
from there your substring should work

How can i get my numbers and fortunes to show on this script on button click

looking to have the user click the button and have the fortune be selecting randomly and shown on the screen with random numbers from 1-100 underneath them. but i can't seem to get everything to display. :(
<script type = "text/javascript">
var quotes = new Array(16) // Add your quotes below
quotes[0]="Your talents will be recognized and suitably rewarded.";
quotes[1]="He who hurries cannot walk with dignity.";
quotes[2]="Your success in life must be earned with earnest efforts.";
quotes[3]="You love peace.";
quotes[4]="A friend asks only for your time and not your money.";
quotes[5]="You will soon inherit a piece of land.";
quotes[6]="Your luck is about to change.";
quotes[7]="Things will soon go your way.";
quotes[8]="He who stands on toilet is high on pot.";
quotes[8]="Everybody is ignorant, only on different subjects.";
quotes[9]="Fortune favors the brave.";
quotes[10]="There is nothing permanent except change.";
quotes[11]="You haven't failed until you give up.";
quotes[12]="Your ability to juggle many tasks will take you far.";
quotes[13]="Broke is only temporary; poor is a state of mind.";
quotes[14]="Begin nothing until you have considered how it is finished.";
quotes[15]="A huge fortune at home is not as good as money in use.";
function showFortune() {
var space = (' ') // Spacer for between numbers
var rand_inta = Math.floor(Math.random()*100); // Get first number
var rand_intb = Math.floor(Math.random()*100); // Get second number
var rand_intc = Math.floor(Math.random()*100); // Get third number
var rand_intd = Math.floor(Math.random()*100); // Get fourth number
var rand_inte = Math.floor(Math.random()*100); // Get fifth number
var rand_int = Math.floor(Math.random()*16); // Get a number for picking the quote
document.getElementById(fortuneArea).innerHTML=(quotes[rand_int]); // Put the quote in the box
}
</script>
<form action="">
<input type="button" value="Show my fortune!" onclick= "showFortune();" />
</form>
<div id="fortuneArea"></div>
document.getElementById('fortuneArea').innerHTML=(quotes[rand_int]);
Just add single quotes to id name....

Does not append input strings dynamically on the web page

I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>
In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()

Categories