I'm trying to brush up on my JS and I want to have it so the user can put in their first and last name and two numbers. When they click the button, I want the text to change to, "Hello Name! Your sum is number!"
My code isn't working, would someone be able to tell me where my issue is?
<html>
<head>
<meta charset="UTF-8">
<title>JS Review</title>
<style>
body{background: #8ADFB6; font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";}
#container{background: white; padding: 30px; width: 760px; margin: 0 auto;}
#output{
padding: 10px; margin: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Using Form Elements with Javascript</h1>
<p>We can utilize user input to create feedback</p>
First Name: <input id="first">
Last Name: <input id="last">
<p></p>
Number 1: <input id="num1">
Number 2: <input id="num2">
<p></p>
<button onClick="Respond()">Respond</button>
<div id="output"></div>
</div>
<script>
function myFunction(){
var a = document.getElementById("first").value;
var b = document.getElementById("last").value;
var c = document.getElementById("num1").value;
var d = document.getElementById("num2").value;
var n= document.getElementById("sum").value;
var n= c + d;
document.getElementById("Respond").innerHTML="Respond";
}
document.getElementById("Respond").innerHTML = "Hello! Your sum is !";
</script>
</body>
</html>
You have quite a few issues.
First, you are trying to do math but are using string values. You can't do that otherwise they are going to concat and make 3 + 1 = 31 instead of 4. You can fix that by parsing the float, now one thing I would recommend is confirming they are numbers so you aren't doing invalid parsing.
if(isNaN(c) || isNaN(d) {
alert('Invalid Input');
}else{
var n= parseFloat(c) + parseFloat(d);
document.getElementById("Respond").innerHTML = "Hello! Your sum is " + n;
}
Next, you are calling function respond but that function doesn't exist. What does exist is myFunction so you have a few options.
Either update this line in your JS to use Respond as the function name:
function myFunction(){
should be:
function Respond(){
Or update your HTML button to use the right function name:
<button onClick="Respond()">Respond</button>
Should be:
<button onClick="myFunction()">Respond</button>
Next, you are looking for an element with the ID respond but that element doesn't exist. Once again you are using the wrong ID. You need to be using output there.
This line:
document.getElementById("Respond").innerHTML = "Hello! Your sum is !";
Should be:
document.getElementById("output").innerHTML = "Hello! Your sum is " + n + "!";
Next, you are trying to get the value of something with the ID of sum but it doesn't exist at all.
Just straight up remove this line:
var n= document.getElementById("sum").value;
Finally, why is your value updater outside of the function call? That updater needs to be inside of the function with what is actually getting the values. If you don't you are never going to be able to update the string.
<html>
<head>
<meta charset="UTF-8">
<title>JS Review</title>
<style>
body{background: #8ADFB6; font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";}
#container{background: white; padding: 30px; width: 760px; margin: 0 auto;}
#output{
padding: 10px; margin: 10px;
}
</style>
</head>
<body>
<div id="container">
<h1>Using Form Elements with Javascript</h1>
<p>We can utilize user input to create feedback</p>
First Name: <input id="first">
Last Name: <input id="last">
<p></p>
Number 1: <input id="num1">
Number 2: <input id="num2">
<p></p>
<button onClick="myFunction()">Respond</button>
<div id="output"></div>
</div>
<script>
function myFunction(){
var a = document.getElementById("first").value;
var b = document.getElementById("last").value;
var c = document.getElementById("num1").value;
var d = document.getElementById("num2").value;
if(isNaN(c) || isNaN(d)) {
alert('Invalid Input');
}else{
var n= parseFloat(c) + parseFloat(d);
document.getElementById("output").innerHTML = "Hello! Your sum is " + n;
}
}
</script>
</body>
</html>
So while I have given you quite a bit here to look at, you really need to take a minute to review your code. You had quite a few issues that could have been resolved if you had just slowed down and read what you were doing.
Your button click handler referenced to a function called Respond() but the actual function you want to reference to is called myFunction() (or vice-versa).
The input values of Number 1 and Number 2 that you have retrieved are strings. You need to parse the input values of Number 1 and Number 2 input elements (convert the strings to integers) to be able to perform mathematical calculations with them.
You must set the innerHTML of #output, not #Respond to the result. You can either use Template Literals with String Interpolation or basic concatenation to combine your result, first name, last name and the "Hello! Your sum is !"string.
--
The concatenation approach would look like this:
"a " + someVariableName + " is a fruit that has vitamin " + someOtherVariable
The template literals and string interpolation approach would look like this:
`a ${someVariableName} is a fruit that has vitamin ${someOtherVariable}`
--
Avoid using inline on* handlers (onclick, oninput, etc) and instead, use an event listener in your JavaScript itself.
Check and run the following Code Snippet where I parsed the values and used string interpolation to output the sentence with the result when the button is clicked:
/* JavaScript */
function myFunction(){
var a = document.getElementById("first").value;
var b = document.getElementById("last").value;
var c = document.getElementById("num1").value;
var d = document.getElementById("num2").value;
var n= parseInt(c) + parseInt(d);
document.getElementById("output").innerHTML = `Hello ${a} ${b}! Your sum is ${n}!`;
}
document.querySelector("button").addEventListener("click", myFunction);
<!-- HTML -->
First Name: <input id="first">
Last Name: <input id="last">
<p></p>
Number 1: <input id="num1">
Number 2: <input id="num2">
<p></p>
<button>Respond</button>
<div id="output"></div>
document.getElementById("num1").value; returns a string.
You need to change it to a number if you want to do math.
parseFloat(document.getElementById("num1").value);
If someone types in a non-number, this will still fail because you need to validate your inputs as part of the process.
Related
Here is a text box and Go! button, when i insert multiline to this text box and press Go button then this change value as <img src="one line">,<img src="second line">,<img src="third line">,... and so on.
But here i want to remove , Comma and use Line Break means simply my result should be as :
<img src="one line">
<img src="second line">
<img src="third line">
My Whole Code is here:
$('#go').click(function() {
var lines = $('#input').val().split(/\r\n|\r|\n/);
var output = [];
var outputText = [];
for (var i = 0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
outputText.push('<img src="' + $.trim(lines[0]) + '">');
}
}
console.log(output);
$('#input').val('' + outputText + '');
})
body {
margin: 25px;
}
#input {
height: 150px;
font-family: "Courier New", Courier, monospace;
}
<textarea id="input" class="u-full-width" placeholder=""></textarea>
<input id="go" class="button-primary" type="submit" value="Go!">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
I tried .(split) in many ways for that but I wasn't able to solve that.
yourtext.split(",").join("\n")
splits yourtext with comma as a separator and joins the resulting array into a string, separating the elements with newline. You can also use replaceAll:
const regex = /,/gi;
console.log(yourtext.replaceAll(regex, 'ferret'));
I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).
I am trying to make a simple code for work to help some coworkers out. Basically I want them to be able to enter in 2 inputs and have a html code output. For example:
input 1= corn
input 2 = delicious
output = <font color="#987654" face="Helvetica, Arial, sans-serif">corn</font>delicious
The current output is simply adding the html styling to the first input. Any advice would be greatly appreciated. Cheers!
<head>
<title></title>
<style>
#prod_name { height: 30px; width:700px; }
#prod_desc { height: 30px; width:700px; padding-top:15px; }
</style>
</head>
<body>
Title: <input id="prod_name"><br />
Description: <input id="prod_desc"><br />
<button id="convert">Convert to HTML</button>
<hr>
<div id="result"></div>
<script>
function convert_it() {
var proname = document.getElementById('prod_name').value;
var descname = document.getElementById('prod_desc').value;
var html = '<font color="#987654" face="Helvetica, Arial, sans-serif">' + proname + '</font> ' + descname;
document.getElementById('result').innerHTML = html;
}
document.getElementById('convert').addEventListener('click', convert_it);
</script>
</body>
Is this what you're looking for?
http://jsfiddle.net/gratiafide/s6vq9tmo/
This literally outputs the HTML string:
<font color="#987654" face="Helvetica, Arial, sans-serif">corn</font> delicious
Here's the JS:
function convert_it() {
var proname = document.getElementById('prod_name').value;
var descname = document.getElementById('prod_desc').value;
var html = '<font color="#987654" face="Helvetica, Arial, sans-serif">' + proname + '</font> ' + descname;
document.getElementById('result').innerText = html;
}
document.getElementById('convert').addEventListener('click', convert_it);
Basically you need to use .innerText instead of .innerHTML
Technology: Asp.Net 4.5 WebForms
I am using the following javascript function to color text in a code block. It actually works if I halt the code with an alert immediately after the function. But the regex rendering doesn't stick. How can I get the results to render after function is completed? Below is a small sample.
CSS
<style type="text/css">
.blue
{
color: blue;
}
.demo
{
background-color: gainsboro;
width: 300px;
height: 100px;
padding: 5px;
}
</style>
JavaScript
<script type="text/javascript">
function Prettyfy() {
var keys = ["Dim", "As", "String"]
for (var i = 0; i < keys.length; i++) {
var value = keys[i];
var str = document.getElementById("demo").innerHTML;
var regexExpression = "(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b";
var regex = new RegExp(regexExpression, "ig");
document.getElementById("demo").innerHTML = str.replace(regex, '<span class="blue">' + value + '</span>');
}
alert(document.getElementById("demo").innerHTML);
}
</script>
HTML
<body>
<form id="form1" runat="server"> <pre id="demo" class="demo">
<code>
dim motor as string
dim reducer as string
</code>
</pre>
<br />
<button onclick="Prettyfy()">Prettyfy Code</button>
</form>
</body>
The problem is very likely to be that your form is causing the page to be repainted by default. Add a "type" attribute to your <button>:
<button type=button onclick="Prettyfy()">
(It's not clear why there's a form at all.)
Goal: User types name into user input field, selects Animate button, and name is printed vertically with each letter containing a drop shadow of each letter. The Javascript library Raphael may be desirable.
Problem: So far what I have is the name being printed vertically twice side by side. Obviously the second column should be the letters as drop shadows, but I don't know how to change the style of them to look like shadows.
My manager gave me one hint: "I had to create a 2nd text line placed underneath the text...and I used the .blur() method on it. If I have to give you another hint I'll be hinting you to the door."
I'm in some real trouble here. If anyone has suggestions, solutions, anything it would be very much appreciated.
<html>
<head>
<script src="raphael-min.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
function animate() {
var txt = document.getElementById("words").value;
var area = txt;
var splittxt = txt.split("");
document.getElementById("letters").innerHTML = "";
document.getElementById("letters2").innerHTML = "";
var i;
for (i = 0; i < splittxt.length; i++) {
document.getElementById("letters").innerHTML = document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
document.getElementById("letters2").innerHTML = document.getElementById("letters2").innerHTML + splittxt[i] + "<br>";
}
//displays how many symbols are in text box and what is in text box
document.getElementById("num").innerHTML= txt.length;
document.getElementById("msg").innerHTML = txt;
r.clear();
// Make our pink rectangle
ellipse = r.ellipse(40, 15, 30, 5).attr({"fill": "#969696", "stroke": "none"});
ellipse.glow({width:10});
}
</script>
<style type="text/css">
#letters
{
background-color:yellow;
width:25px;
float:left;
}
#letters2
{
letter-spacing:0px;
display:block;
-moz-transform: rotate(80deg);
margin-left:90px;
margin-top:80px;
width:25px;
color:#DEDEDE;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input type="button" value="Animate" onclick="animate()" />
<div id='msg'></div>
<div id='num'></div>
<div id='letters'></div>
<div id="letters2"></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px;">
</div>
<div id="elps" style="margin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
</script>
</body>
</html>
Live Long and Prosper.
Do you really need raphael? What I did was simply print out your words onto an element and get the shadow with css's text-shadow. To get the vertical text I added a </br> after each letter.
Take a look at the fiddle: http://jsfiddle.net/joplomacedo/wVGbF/
Here's the code in case you can't see the fiddle:
HTML
Text: <input type="text" id="words" value="" />
<input id="animateBtn" type="button" value="Animate" />
<div class="print"></div>
CSS
.print {
font: 44px/0.8em "Lobster", cursive;
color: gold;
text-shadow: 2px 2px 3px rgba(0, 0, 0, 0.6);
}
JS
var join = Array.prototype.join;
$('#animateBtn').on('click', function() {
var txt = $('#words').val(),
spaced_txt = join.call(txt, "</br>");
$('.print').html(spaced_txt);
});
Here is also the text output function with Raphael:
function draw_text() {
var txt = document.getElementById("words").value;
var posy = txt.length*10;
r.clear();
var attr = {font: "50px Helvetica", opacity: 0.5};
var text = r.text(40, 40+posy, txt).attr(attr).attr({fill: "#0f0"}); // underlayer or "shadow"
text.attr({transform: "r270"}); // rotate 270 degrees
var text2 = r.text(43, 43+posy, txt).attr(attr).attr({fill: "#aa0"}); // text above
text2.attr({transform: "r270"}); // rotate 270 degrees
r.safari();
}
var r = new Raphael("draw-here-raphael");
The full script, based on this example, is here.