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).
Related
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:
<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>
I'm using JS in brackets, and I'm having some problems. First, the alert property doesn't work. Is this just because of brackets live preview? Second, it doesn't tell me when I've made errors )I entered in nonsensical commands, and there was no errors at all. Also, when I named a variable starting with a number, no error message! These are just problems I noticed in the last 5 minutes. Please help! Here's my code:
<html>
<head>
<script>
document.write("Hello world");
var someText = " years old";
var years = 35;
alert(years + sometext);
</script>
</head>
<body>
</body>
</html>
You declare your variable as someText but then refer to it as sometext in your alert:
<html>
<head>
<script>
document.write("Hello world");
var someText = " years old";
var years = 35;
alert(years + someText); // <--
</script>
</head>
<body></body>
</html>
I want to write a script that multiplies any number in a text field with itself by the push of a button and gives the result as an alert.
I'm completely new to Javascript (and have to write my first exam later today).
The syntax is killing me, sometimes so similar to Java, but than again not.
Here's what I came up with so far:
<!DOCTYPE html>
<html>
<head>
<script>
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
You'll want to make sure you parse the input value as it will be a string when you query for it. To operate on it using multiplication, you need a number. You'll usually want to pass 10 as the second radix parameter as there are different implementations of parseInt
function myMultiply() {
var x = parseInt($('#num1').val(), 10);
var y = x*x;
alert(x + " times " + x + " equals " + y);
return false;
}
You cant multiply string it will be concatenated, parse value to int using parseInt first
parseInt
function myMultiply()
{
var x= parseInt($('#num1').val(), 10);
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
try replacing var y=x*x; with var y=Number(x)*Number(x);
Along with other answers indicating you should parseInt it should be noted that you aren't currently including jQuery (which gives you access to the $(".element") notation).
jQuery is a very common javascript library that saves a lot of time for very common Javascript tasks (selectors, events etc). You'll see the $() notation in many tutorials and to use it you need to include jQuery.
This will work:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function myMultiply()
{
var x= parseInt( $('#num1').val(), 10 );
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1" />
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
Your code is fine. You are simply missing the jquery include.
Add <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> right above your other script and everything works unchanged.
Javascript will parse strings and convert them to numbers automatically when it sees that you are trying to multiply. "4" * "2" is 8, not "44" or "42" or any other magical combination. You have a syntax error by referring to $ without actually including jQuery as a required script, so the function ends up being undefined.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
I'm learning JavaScript and I'm wondering why something like:
document.getElementById('partofid'+variable+number) doesn't work?
Here are samples and JSfiddle link, I want "next" button to remove displayed item and show the next one.
HTML:
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
JS:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+counter+1);
alert(nextDiv); // why does it return null
alert('div-'+counter+1); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
Try using parseInt:
var nextDiv = document.getElementById('div-'+parseInt(counter+1,10));
The parseInt function converts its first argument to a string, parses it, and returns an integer.The second arguement is radix which is "base", as in a number system.
Demo
What's going on here is Javascript has some strange rules about types and the + operator.
string + anything means convert anything to string, then concatenate them together. So "foo" + "bar" == "foobar"... and "div" + 1 == "div1".
The the next step, addition is done left to right, so "div" + 1 + 1 goes to "div" + 1 == "div1".
"div1" + 1... remember, convert to string then put together, so we get "div1"+ 1 == "div11".
I would put parenthesis around your arithmetic. "div" + (1+1) would do the right hand side thing first, so (1+1) == 2 as you expect, then "div" + 2 == "div2", so that's what you expect.
As to the alert thing, your first one is looking at the result of the element lookup, and the second one is looking at the string itself. So the first is null because the element lookup didn't find anything.
This code results in string concatenation. E.g. if counter is 1, then you will get div-11
'div-'+counter+1
This is because addition is resolved from right to left.
Then you try to retrieve element with id div-11, but you don't have html element with such an id. That's why the function getElementById returns null.
To solve the problem first add counter to 1 and then join it with div, like this 'div-'+(counter+1)
Because counter+1 = 11 => id = div-11 is not exist. Try this:
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+Number(counter+1));
alert(nextDiv); // why does it return null
alert('div-'+Number(counter+1)); // while this doesn't?
nextQuestion.style.display = "block";
counter++;
},true);
it does work and does exactly what you asked it to do but since you do not have a div-11 there is nothing found so the evaluation returns null.
if you want div-2 then simply use order of operations to sum the counter to the number:
Fiddle
Here is your answer:
<html>
<head>
<script>
function load()
{
var counter = 1;
var button = document.getElementById('next');
button.addEventListener("click",function(){
var currentDiv = document.getElementById('div-'+counter);
currentDiv.remove();
var nextDiv = document.getElementById('div-'+(counter+1));
//alert(nextDiv); // why does it return null
//alert('div-'+(counter+1)); // while this doesn't?
nextDiv.style.display = "block";
counter++;
},true);
}
</script>
</head>
<body onload="load()">
<div id="div-1"> 1 </div>
<div id="div-2" style="display: none"> 2 </div>
<div id="div-3" style="display: none"> 3 </div>
<div id="div-4" style="display: none"> 4 </div>
<a id="next" href="#">next</a>
</body>
<html>
To solve this kind of returning "null" values by getElementById("").
you can use script inside the body instead of head it will return the html element.
const m=document.getElementById('one')
const m1=document.getElementById('demo')
console.log(m1);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="demo">sample text</p>
<script src="script.js"></script>
</body>
</html>