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
Related
I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)
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"));
My goal is to write content in a textarea and display exactly what I am writing without have to refresh the page each letter that I type shows immediately well it is not working for some reason.
HTML:
<textarea id="Q&A" name="txtarea" rows="4" cols="50"></textarea>
<div id="out"></div>
Js:
function generate() {
var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse(text);
text = writer.render();
document.getElementById("out").innerHTML = text
}
document.getElementById("Q&A").addEventListener("input", function () {
generate(this.value);
});
When I try to update the div with the id of out to what I am typing using JavaScript, it does not work.
I don't know what the commonmark.Parser() does in your code. But the issue i see is, When you are calling the generate method, you are passing the value of the input field. But in your generate method signature, you don't have a parameter to accept that.
Add a parameter to your generate() method to accept the value passed in.
function generate(text) {
//do something else on text with your commonmark
document.getElementById("out").innerHTML = text;
}
Here is a working sample.
and you forgot to pass the argument parsed to the render function:
You had: text = writer.render(); I changed it to text = writer.render(parsed);
I figured it out i forgot to have text pasted in as a argument in the generate function and I forgot to pas parsed into the render function
Here is the final code:
function generate(text) {
var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse(text);
text = writer.render(parsed);
document.getElementById("out").innerHTML = text
}
document.getElementById("Q&A").addEventListener("input", function () {
generate(this.value);
});
I have a jsp file with a scriptlet tag, I am getting the values of .properties file in it .I have a java script tag in which I am storing the value from the dropdown in a variable. On selecting some value in the dropdown I want to compare it with the property in the scriptlet and if it is equal a value from properties file must populate in my textbox. I have tried the following code but it is not working
My scriplet tag
<%
Properties prop = new Properties();
String propFileName = "server. properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "'not found in the classpath");
}
String appName = prop.getProperty("Demo_name");
String link = prop.getProperty("Demo_Links");
String database = prop.getProperty("DemoApps_DataBase");
%>
JavaScript
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex];
var txtbox=document.getElementById('serverLink');
var appName=<%=appName%>;
var links=<%=link%>
alert(appName.value);
if(selectedOption.value==appName.value){
txtbox.value=links.value;
}
}
</script>
Try this code. Is Your selected value is case sensitive?
<script type="text/javascript">
function OnSelectionChange(serverName) {
var selectedOption = serverName.options[serverName.selectedIndex].value;
var txtbox=document.getElementById('serverLink');
var demoName='<%=demoServer%>';
var testName='<%=testingServer%>';
var PNGName='<%=pngServer%>';
var DCPName='<%=dcpServer%>';
var demoLink='<%=demoLink%>';
var testLink='<%=testingLink%>';
var pngLink='<%=pngLink%>';
var dcpLink='<%=dcpLink%>';
if(selectedOption==appName){
txtbox.value=links;
}
if(selectedOption==PNGName){
txtbox.value=pngLink;
}
if(selectedOption==DCPName){
txtbox.value=dcpLink;
}
if(selectedOption==demoName){
txtbox.value=demoLink;
}
}
</script>
Using scriplets populate the values in a hidden field from your scriplet like :
<input id=hiddenPops type="hidden" name="Language" value="English">prop1=value2;prop2=value3</input>
In your javascript get the value of the above field using getElementById(hiddenPops )
Split the value string into array or as desired and you can work with it to match the keys and fetch the corresponding values.
Note: Its a solution but your approach is not great. Try to use modern JS frameworks which could allow you to talk to the server directly or simply use Ajax