Combining strings in Javascript - javascript

I'm experimenting with Javascript and I created a simple HTML page with two fields, a button, and another field that should be the combination of the first two fields.
However, my Javascript is not working. Here are my files:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h2>My First Web Page</h2>
<p id="first">My First Paragraph.</p>
<p id="second">My Second Paragraph.</p>
<input onclick="myFunction()" type="submit" value="Combine" />
<p id="third">Concatenate first and second.</p>
</body>
</html>
and the Javascript
myFunction(){
var first = document.getElementById("first").value;
var second = document.getElementById("second").value;
var third = first + " " + second;
document.getElementById("third").value = third;
}
Alternatively, I'm testing it on this Codepen template

Use innerText instead of value. And declare function correctly.
function myFunction() {
var first = document.getElementById("first").innerText;
var second = document.getElementById("second").innerText;
var third = first + " " + second;
document.getElementById("third").innerText = third;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h2>My First Web Page</h2>
<p id="first">My First Paragraph.</p>
<p id="second">My Second Paragraph.</p>
<input onclick="myFunction()" type="submit" value="Combine" />
<p id="third">Concatenate first and second.</p>
</body>
</html>

You must declare it as function. And value is not the right property to modify, but you can use 'innerHTML' or example. Here is the updated, working JS.
function myFunction(){
 var first = document.getElementById("first").innerHTML;
 var second = document.getElementById("second").innerHTML;
 var third = first + " " + second;
document.getElementById("third").innerHTML = third;
}

You can use textContent instead:
function myFunction(){
var first = document.getElementById("first").textContent;
var second = document.getElementById("second").textContent;
var third = first + " " + second;
document.getElementById("third").textContent = third;
}

The problem here is that you are setting the value of the paragraph and not the html.
What you should do is use innerHTML instead of value.
Here is a stackoverflow discussion about the difference between value and innerHTML:

Related

How to Title Case a sentence in Javascript

<html>
<head>
<!--Wei Wu Section A-->
<title>This is the 4th extra credit</title>
</head>
<body>
<script type="text/javascript">
function toUpper(stringFromUser){
var arrayOfStrings = [];
arrayOfStrings = stringFromUser.split(" ");
for(i=0;i<arrayOfStrings.length;i++){
//if (char(arrayOfStrings[i][0]) <= 122 && char(arrayOfStrings[i][0]) >= 97){
if (arrayOfStrings[i].charCodeAt(0) <=122 && arrayOfStrings[i].charCodeAt(0) >=97){
arrayOfStrings[i] = arrayOfStrings[i].charAt(0).toUpperCase() + arrayOfStrings[i].slice(1);
}
}
var afterTitle = "";
afterTitle = arrayOfStrings.join(" ");
document.getElementById('afterChange').innerHTML = afterTitle;
}
</script>
<p>Enter a sentence and I will turn it into Title Case!<input id="textInput" value=""></p>
<button onclick="toUpper(textInput.value)">Change case!</button>
<p id="afterChange"></p>
</body>
</html>
Hi thank you in advance for all your help. this is one of the code that I was working on. the purpose of this code is to "Title Case" the first letter of each word in the sentence. My code runs quite well after some work.
But I have one question: On line 14, I was trying to directed assign the uppercase letter to arrayOfString[i][0], it didn't work. Instead, I changed the whole element, AKA the element in the array. Why didn't that work? Thank you very much!
Strings are immutable - you cannot change individual characters in them by assigning to their [] indicies. So, you have to slice them apart and put them back together, as you did.
You can use this code to Title Case
<html>
<head>
<!--Wei Wu Section A-->
<title>This is the 4th extra credit</title>
</head>
<body>
<script type="text/javascript">
function toUpper(stringFromUser){
var afterTitle = toTitleCase(stringFromUser);
document.getElementById('afterChange').innerHTML = afterTitle;
}
function toTitleCase(str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
</script>
<p>Enter a sentence and I will turn it into Title Case!<input id="textInput" value=""></p>
<button onclick="toUpper(textInput.value)">Change case!</button>
<p id="afterChange"></p>
</body>
</html>

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

toExponential() Method not working

toExponential() Method is not working my code.
chrome console is giving this error:
Uncaught TypeError: number.toExponential is not a function.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JS Code Academy</title>
</head>
<body>
<input type="number" id="myInput" value="2.326">
<button id="myButton">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p>
<script type="text/javascript">
document.getElementById("myButton").onclick = function() {
var number = document.getElementById("myInput").value;
var str = number.toExponential(2);
document.getElementById("demo1").innerHTML = str;
document.getElementById("demo2").innerHTML = typeof str;
};
</script>
</body>
</html>
toExponential is a method defined on the number class. So make sure that you are calling it on a number and not a string:
var value = document.getElementById("myInput").value;
var number = parseFloat(value);
if (!isNaN(number)) {
// The string value entered in the textbox was successfully parsed to a number
// we can now calculate the exponential:
var str = number.toExponential(2);
}
If you have <input type="number" id="myNumber" /> , the entry must be just numbers so it will be easier for users to work with it. Darin's code is a good solution.

Javascript display all (elements, tags) from method elementsbyTagName

Im learning JavaScript and i have problem with DOM methods.
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="DOM_Ponovno.js"></script>
</head>
<body>
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
</body>
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
document.write(tmpTag[i].textContent);
}
}
If i follow the tutorial its ok, but i wanted to display all elements by tag name p. I want to display all paragraphs stored in tmpTag.
Someone please explain:
How can ( why cant) display all elements with tag name p ?
How can (why cant) display 3x p tag from variable tmpTag ?
Tried to change to Array with prototype.slice.call method but no success.
You know like Java stuff loop through display/change at index etc..
Thank you :)
Hi and thanx for fast answers.. Sory about the function name it was for testing... I just want to display all elements by tag name p. This code displays only first element and i counter in for loop stops at 1. Why cant i get other 2 paragraph elements ?
Im using document.write like system.out.print in Java to see whats in array. I know if i wanna change i need innerHTML.
If you are wanting to update each paragraph, do not use document write. Try the following:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
tmpTag[i].innerHTML = "Your new updated text to change it to for tag index " + i + "...";
}
}
As #Juhana mentioned, the moment you start your loop you overwrite the document using document.write, so all your p tags get removed from the document and replaced by the text in the first paragraph and then your function fails, as the now-empty objects don't have any textContent property. You could concatenate all the contents and write it once:
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var print = '';
for(var i = 0;i< tmpTag.length;i++) {
print += tmpTag[i].textContent;
}
document.write(print)
}
But actually, just don't use document.write - SO snippets don't even allow it anymore! Here a way with a div as output:
var output = document.getElementById('output');
function changeText() {
var tmpTag = document.getElementsByTagName("p");
for(var i = 0;i< tmpTag.length;i++) {
output.textContent += tmpTag[i].textContent;
}
}
<div>
<p id="demo" >this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
</div>
<div id="output"></div>
I'm not sure what you're trying to do but you can add another div for result with id='result' and append result you want to it, check following example.
Hope this will help.
function changeText() {
var tmpTag = document.getElementsByTagName("p");
var result = document.getElementById('result');
for(var i = 0;i< tmpTag.length;i++) {
result.innerHTML += tmpTag[i].textContent+'<br>';
}
}
<div>
<p id="demo" >
this is the first paragraph</p>
<p> boooooooooooommmmmmmmmmmm</p>
<p> third paragraph </p>
<button onclick="changeText()">click me</button>
<br>
<div id="result" ></div>
</div>

Javascript alert statement with string & int

Im a newbie to Javascript and trying to debug a simple js function..I need to get the value of x through the alert statement but it doesn't display correctly..How to concatenate a string and int as in this case..
<html>
<head>
</head>
<body>
<script>
function displaydate()
{
document.getElementById("test").innerHTML='first line changed';
document.getElementById("test1").innerHTML='second line changed';
var x = 5;
alert("Value of x" + String.valueOf(x));
}
</script>
<p id="test">this is the 1st line</p>
<p id="test1">this is the 2nd line</p>
<button type="button" onclick="displaydate()">clickme!</button>
<body>
</html>
New code:
<html>
<head>
</head>
<body>
<script>
function displaydate()
{
document.getElementById("test").innerHTML='first line changed';
document.getElementById("test1").innerHTML='second line changed';
var x = 5;
alert("Value of x=" + x);
var cars=new Array();
cars[0]='car';
cars[1]='Volvo';
alert("Value of arrary 1 var=' + cars[0]);
//alert("Value of arrary 2 var='+cars[1]);
}
</script>
<p id="test">this is the 1st line</p>
<p id="test1">this is the 2nd line</p>
<button type="button" onclick="displaydate()">clickme!</button>
<body>
</html>
alert("Value of x" + x);
JavaScript is a dynamic language. The conversion is done automatically for you. When you do something like "var x = string + int"
Update
The reason your alert is failing now is because you start the alert with a double quotation mark and end the string piece of the alert with a single quote.
You can just do:
alert("Value of x - " + x);
No need to call valueOf the conversion will be automatic (implicit).

Categories