JavaScript - How can I 'translate' the input to something different - javascript

I'm trying to make a program where if you for example type in "less" in the textarea the output should show "<". What is the best way to do this?
This is how far I've gotten:
<!doctype html>
<html lang="en">
<head>
<title>Group 7 - Deckcode to JavaScript</title>
</head>
<body>
<h1>Group 7 - Deckcode to JavaScript</h1>
<p>Input your deckode below:</p>
<textarea id="myTextarea"></textarea>
<button type="button" onclick="myFunction()">Translate</button>
<p id="demo"></p>
<script>
function myFunction() {
var input
if (myTextarea == "less") {
console.log("<");
}
}
</script>
</script>
</body>
</html>

You're trying to fish values out of the DOM incorrectly. Use document.getElementById to locate the element in the DOM, and take its value for the value you require.
function myFunction() {
var textAreaValue = document.getElementById("myTextarea").value;
if (textAreaValue == "less") {
console.log("<");
}
}

I suggest using an object like this:
var translations = {};
translations["less"] = "<";
translations["greater"] = ">";
And then in your function you do like this:
function myFunction() {
var value = document.getElementById("myTextarea").value;
console.log(translations[value] ? translations[value] : "No translation found");
}
It would also be easy to add more translations e.g. based on data from a database or similar.

as and alternative to IF-condition, you can use
if (textAreaValue.indexOf("less") > -1) {
console.log("<");
}
so if the text area contains "less" text then the console prints "<"
indexOf method

Related

How do I select text between two characters in Javascript?

So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))

What language is this and how do I run it?

I'm doing one of those codding maze challenges and I got stuck as I decoded a base64 image which contained a code block that i need to use to progress though, I'm not sure how to use it.(I know nothing about frontend languages so I assume its some form of js or api call)
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
Seems like javascript.
You can embed in a simple html and try it.
NOTE: Supply valid parameters to run the function properly...
<!DOCTYPE html>
<html>
<head>
<script>
function otherFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
function solutionChecker(url, queryParams, method, headers){
var a = headers[queryParams.b];
var altwo = a < 2;
if(!alttwo){
headers.clue="output";
}
return a == c && method === "PATCH";
}
</script>
</head>
<body>
<h2>JavaScript in Head</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="solutionChecker('someUrl',params,'METOD',headers)">Try it</button>
</body>
</html>

If.. Then in javascript

I want to change the font size of a text depending on the current font size.
Algorithm:
On clicking the text,
If font size = 35, change it to 12
else if font size = 12, change it to 35
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
if (document.getElementById('demo').style.fontSize='35px') {
document.getElementById('demo').style.fontSize='12px'
} else if(document.getElementById('demo').style.fontSize='12px') {
document.getElementById('demo').style.fontSize='35x'
}
}
</script>
It changed it 12, but never changes back to 35. What did I miss here?
You have assignment in the if statement. You need to use not =, but == or better ===.
Also one note, if the font-size is defined in the css, it may return to you an empty string for the first time. In this case you need to use window.getComputedStyle to get the font-size.
function myFunction() {
const element = document.getElementById('demo');
console.log(element.style.fontSize);
const fontSize = window.getComputedStyle(element, null).getPropertyValue('font-size');
if (fontSize === '35px') {
element.style.fontSize = '12px';
} else if(fontSize === '12px') {
element.style.fontSize = '35px';
}
}
p#demo {
font-size: 12px;
}
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
You're using = in if statement like if(a=b). When this code will run javascript engine will assign b to a. And that's why it will always execute the same code inside the if(a=b) block. That's how, this would be translated in machine language. If you want a comparison b/w a and b, you should use a==b or a===b. This will make the required block to get executed bases on the condition specified.
you are using '=' instead of '==' and another important thing - you should store fontsize in a variable and then do the comparision.
The optimized code will be -
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
var element= document.getElementById('demo'),
fontSize=element.style.fontSize;
if (fontSize === '35px') {
element.style.fontSize='12px'
} else if(fontSize ==='12px') {
element.style.fontSize='35x'
}
}
</script>
</body>
</html>
Instead of comparison of font size you are assigning size.
document.getElementById('demo').style.fontSize='35px'
You should change it to following :
document.getElementById('demo').style.fontSize=='35px'
Same For both conditions.
Three Mistakes from your end. First one is you don't have any style tag in your html mark-up. Second one is conditional operator == you entered as =. Last mistake is typo 35x should be 35px in the second condition like below.
<p id="demo" style="font-size:35px;" onclick="myFunction()">Click me.</p>
if (document.getElementById('demo').style.fontSize=='35px') {
document.getElementById('demo').style.fontSize='12px';
} else if(document.getElementById('demo').style.fontSize=='12px') {
document.getElementById('demo').style.fontSize='35px';
}
DEMO
Try This :
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
var el = document.getElementById('demo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
if (fontSize==16) {
document.getElementById('demo').style.fontSize='12px';
} else if(fontSize==12) {
document.getElementById('demo').style.fontSize='35px';
}
}
</script>
</body>
</html>
It is exactly what Suren Srapyan has said, but here is the correct code:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>
<script>
function myFunction() {
if (document.getElementById('demo').style.fontSize === '35px') {
document.getElementById('demo').style.fontSize='12px'
} else if(document.getElementById('demo').style.fontSize ==='12px') {
document.getElementById('demo').style.fontSize='35x'
}
}
</script>
</body>
</html>

Jquery .get not retrieving file

i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>

Maintain div scroll position on postback with html/javascript

Is there a way to maintain the div scroll position on a postback, without using asp? So far I've only found solutions using asp.
http://blogs.x2line.com/al/articles/156.aspx
<!doctype html>
<html>
<head>
<title></title>
<script language="javascript">
// function saves scroll position
function fScroll(val)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = val.scrollTop;
}
// function moves scroll position to saved value
function fScrollMove(what)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(what).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="fScrollMove('div_scroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br>
<div id="div_scroll" onscroll="fScroll(this);" style="overflow:auto;height:100px;width:100px;">
.. VERY LONG TEXT GOES HERE
</div>
</form>
</body>
</html>
Maybe this javascript code works for you
function loadScroll ()
{
var m = /[&?]qs\=(\d+)/.exec (document.location);
if (m != null)
myDiv.scrollTop = parseInt (m[1]);
}
function saveScroll ()
{
var form = document.getElementById ("myForm");
var sep = (form.action.indexOf ("?") == -1) ? "?" : "&";
form.action += sep + "qs=" + myDiv.scrollTop;
}
Now, you can watch for the "submit" event to save the position in the "action" attribute:
document.getElementById ("myForm").addEventListener ("submit", saveScroll, false);
And in your BODY tag...
<body onload="loadScroll ();">
....
</body>
I can't test the code right now, but I think you get the idea.

Categories

Resources