here is my code. I would like to print the variable 'fName' and the text prior into the div (with the ID 'feedback').
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello" + fName;
}
</script>
Any help would be appreciated.
Just use the variables you have defined:
<script>
function myFunction() {
var first = document.getElementById("fName").value;
var last = document.getElementById("lName").value;
document.getElementById("feedback").innerHTML += "Hello " + first + " " + last;
}
</script>
Related
So this is externally linked, that works fine. But when I run it in the browser, it does not show anything. Is there anything wrong with this code?
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write( +linktag+ );
}
numberthree(linktag)
There are two extra + to remove in the document.write of the 'numberthree' function, i.e.:
var myheading = "This is my webpage!";
var text = "This JavaScript file makes use of Variables";
var linktag = "http://www.google.com/";
var begineffect = "<strong>";
var endeffect = "</strong>";
var linebreak = "<br />";
function numberone(myheading) {
document.write("<h2>" +myheading+ "</h2>");
}
numberone(myheading)
function numbertwo(text) {
document.write("<strong>" +text+ "</strong>");
}
numbertwo(text)
function numberthree(linktag) {
document.write(linktag);
}
numberthree(linktag)
I wrote a function that creates new Input fields based on the number of input fields needed. That code is below.
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Guest " + (i+1)));
var input = document.createElement("input");
input.id = "Guest" + i;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i.value);
It creates a new Id for each input field. In the function below,depending on the number you set for i, the function creates a generated message.
function sendInput ()
{
var guestNames = document.getElementById("Guest").value
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
document.getElementById('output').innerHTML = output.repeat(i);
}
The problem is it is not collecting the data for guestNames. I am pretty new to JS but have searched and cannot find a solution to my problem. Any feedback wouls be helpful.
IDs are difficult to work with in a dynamic environment, classes are generally the simplest solution. This code will convert your inputs to have classes, then loop through them and collect the names.
So change:
input.id = "Guest" + i;
to
input.setAttribute("class","guest");
And change
var guestNames = document.getElementById("Guest").value
to:
var guests = document.querySelectorAll(".guest");
var guestNames = [];
guests.forEach(function(el){
guestNames.push(el.value);
});
guestNames = guestNames.join(",");
If you are wanting a message for EACH guest, then you would use the below function:
function sendInput ()
{
var personName = document.getElementById("people").value;
var eventType = document.getElementById("event").value;
var date = document.getElementById("date").value;
var guests = document.querySelectorAll(".guest");
var guestNames = [];
document.getElementById('output').innerHTML = "";
guests.forEach(function(el){
document.getElementById('output').innerHTML += "Dear " + el.value + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
});
}
You try to get node by id var guestNames = document.getElementById("Guest").value
But all nodes have a different id, like a Guest0,Guest1 etc. I am trying to write my own code, but your snippet isn't full. I hope I helped you.
As far as I can see, when you try to fetch the guest name
var guestNames = document.getElementById("Guest").value
you won't get any element for two reasons because there's no element with id "Guest". In fact you generate them in the form "GuestN"
`input.id = "Guest" + i;`
You probably want to add a parameter i to sendInput () function, so that internally you can concatenate it to Guest as you did above and get the correct element with getElementById().
Your code is incomplete (as far as I can tell).
You do not specify the following elements anywhere:
'container', 'guest', 'people', 'event', 'data' or 'output'
I assume they should be defined somewhere in the HTML section (not provided)
To be able to create the variable displays, you need to define the 'container' you wish to initialize it before it is used in the for() loop that follows.
Example: var container = document.getElementById('container');
Within the loop, console.log(i.value) is invalid as i is not an element that has been assigne a value to display. It is a counter of the for() loop.
The function of sendInput(), I assume, is to collect the information from the user for each "Guest#" created by the first loop of your code. However you try to collect from "Guest" which has not been defined. For a number of 5, the collections should be for "Guest1", "Guest2", "Guest3", "Guest4", "Guest5". "Guest" only can not be found anywhere in your loop creation. Same goes for 'people, 'event' and 'date' which are referenced for value collection, but there are no elements named as such.
Not exactly sure why you are mixing DOM creation techniques (???).
You create the number of element for the guest, but then output the results with .innerHTML. You should use the DOM creation method, but I have used your code as you indicated you are a beginner.
Here is some (partially) corrected code that you can continue on with.
<!DOCTYPE html><html lang="en"><head><title> Test Page </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!-- link rel="stylesheet" href="common.css" media="screen" -->
<style>
</style>
</head><body>
<input type="text" value="5/28/2020" id="date">
<pre id='container'></pre>
<button id="report">Report</button>
<pre id='output'></pre>
<script>
console.clear();
function init() {
var number = 5;
var container = document.getElementById('container');
for (i=0;i<number;i++) {
var value = "Guest " + (i+1)+' ';
container.appendChild(document.createTextNode(value));
var input = document.createElement("input");
input.id = "Guest" + i;
input.value = value;
container.appendChild(input);
container.appendChild(document.createElement("br"));
console.log(i); // .value);
}
document.getElementById('report').addEventListener('click',sendInput);
} init();
function sendInput () {
var date = document.getElementById("date").value,
output = document.getElementById('output'),
info = '';
var guestNames = [...document.querySelectorAll('#container input')]; // alert(guestNames.length);
for (let i=0; i<guestNames.length; i++) {
info = `Dear ${guestNames[i].value}:\nYou have been invited to XXX's EVENT on ${date}\nThank you for coming!!\n\n`;
output.innerHTML += info;
}
// var guestNames = document.getElementById("Guest").value
// var personName = document.getElementById("people").value;
// var eventType = document.getElementById("event").value;
// var output = "Dear " + guestNames + " You have been invited to " + personName + "'s " + eventType + " on " + date + " Thank you for coming!!";
// output = `Dear ${guestNames}:\nYou have been invided to XXX's EVENT on ${date}\nThank you for coming!!`;
// document.getElementById('output').innerHTML = output.repeat(i);
}
</script>
</body></html>
I'm working on a weather api and I'm having trouble toggling between Celsius and Fahrenheit.
I used a separate function to get the location as well as call from the API.
I also added an onclick function within this second function. I can get it to toggle to one temperature but not back.
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = function toggleTemp() {
if(buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonId.innerText = "Convert to Celsius";
}
}
}
I used innerText because I thought it was the easiest way to toggle back and forth between temp. I can get the weather to convert to Celsius, but the else statement is not working. Fyi, I was not able to get the button text to change using the tag name which is why I resorted to using an id in the button click function. I'm still pretty new at Javascript. Any help would be appreciated.
You need to update the buttonText variable when you toggle the text of buttonId.
buttonId.onclick = function toggleTemp() {
if (buttonText == "Convert to Celsius") {
x.innerHTML = weatherC;
buttonText = buttonId.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = weatherF;
buttonText = buttonId.innerText = "Convert to Celsius";
}
}
Your variable x is undefined. In the future, try to avoid using the innerHTML property, which can break event listeners and be slow to render.
Neither buttonText nor x are defined in the scope of your onclick function, which might be why nothing happens. Have you checked the console for errors?
function getTemp(data) {
// API variables
var temp1 = data.main.temp;
var weatherUrl = data.weather[0].icon;
var tempInC = Math.round(temp1); // Temp in Celsius
var tempInF = Math.round(temp1 * 9/5 +32)
// Inner HTML variables
var weatherF = "The weather is " + tempInF + " ℉ <br>" +
"<img src='" + weatherUrl + "'/>";
var weatherC = "The weather is " + tempInC + " ℃ <br>" +
"<img src='" + weatherUrl + "'/>";
// Button DOM variables
var x = ...; // Declare x for the function scope here
var buttonText = document.getElementsByTagName("button")[0].innerText;
var buttonId = document.getElementById('btn');
x.innerHTML = weatherF;
buttonId.onclick = (function (x, wC, wF, btn) {
return function () {
// Change DOM
if(btn.innerText == "Convert to Celsius") {
x.innerHTML = wC;
btn.innerText = "Convert to Fahrenheit";
} else {
x.innerHTML = wF;
btn.innerText = "Convert to Celsius";
}
};
})(x, weatherC, weatherF, document.getElementsByTagName("button")[0])
}
Need to dynamically select JSON key from the JSON Object itself.
var text =
'{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';
var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0].lName;
<div id="demo"></div>
Output Obtained: "lastName undefined".
Desired Output: "lastName Doe"
You need to change the code like follows
var text = '{"employees":[' +
'{"firstName":"lastName","lastName":"Doe" }]}';
obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;
document.getElementById("demo").innerHTML =
firstName + " " + obj.employees[0][lName];
Here is the working code:http://jsfiddle.net/NJMyD/5349/
I have to create:
1 <input type="text">
1 <textarea>
1 <div>
1 <button>
I have to fill the div with the textarea's content but if the content contains the input's string, I have to color it with <span>.
For example:
If the input contains "is" and the textarea contains "this is a beautiful day", I should put the following text in the div "this is a beautiful day" and color every time that the "is" string appears.
I should use indexOf() and a loop.
I have this:
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
if (x > -1)
If you absolutely have to use indexOf
while(b.indexOf(a) != -1) {
b = b.replace(a, '[X]');
}
while(b.indexOf('[X]') != -1) {
b = b.replace('[X]', '<span style="color:yellow;">' + a + '</span>');
}
$("#targetDiv").html(b);
You can also do this with RegExp
var a = $("#inp1").val();
var b = $("#txt").val();
var re = new RegExp(a, 'g');
var divContent = b.replace(re, '<span style="color:yellow;">' + a + '</span>');
$("#targetDiv").html(divContent);
Here is a fiddle with the indexOf
http://jsfiddle.net/eva3ttuL/1/
Here is the code to find and change color of all searched word
$(document).ready(function () {
$("#here").on("keydown keyup", function () {
var mytext = $(this).val();
var find = $("#find").val();
mytext=mytext.replace(new RegExp(find,"g"), "<span class='me'>"+find+"</span>");
$("#output").html(mytext);
});
})
.me{color: #00f;
background-color: #EFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="find" type="text" /><br/>
<textarea id="here"></textarea><br/>
<div id="output"></div>
Use JavaScript substring to split the string inside textarea and form a paragraph with the highlighted text.
HTML code:
<input id="inp1" type="text"/><br>
<textarea id="txt" col="10" row="5"></textarea><br>
<div id="fillarea">
click on check
</div>
<button id="check">check</button>
CSS for highlighting:
.highlight{
background-color:yellow;
}
jQuery code:
$('#check').on('click',function(){
var a = $("#inp1").val();
var b = $("#txt").val();
var x = b.indexOf(a);
var first = b.substring(0,x);
var middle = b.substring(x,x+a.length);
var last = b.substring(x+a.length,b.length);
var to_print = '<p>' + first + '<span class="highlight">' + middle + '</span> ' + last + '</p>';
$('#fillarea').empty();
$('#fillarea').append(to_print);
});
Demo fiddle here
It helps you jsfiddle
$('.submit').click(function(){
var content = $('.textarea').val();
var ans = content.replace($('.input').val(), "<span style='color:red;'>"+$('.input').val()+"</span>");
$('.text').html(ans);
});
var input = $("#inp1").val();
var text = $("#txt").val();
var div = $("#div");
div.val(text.replace(new RegExp(input,'g'), makeSpan(input)));
function makeSpan(str) {
return '<span style="background-color:red">' + str + '</span>';
}
Just try this
<html>
<title></title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var a = "is";
var b = "this is beautiful";
var x = b.indexOf(a);
if (x > -1) {
var re = new RegExp(a, 'g');
res = b.replace(re, "<span style='color:red'>"+a+"</span>" );
$("#result").html(res);
}
})
</script>
</head>
<body>
<div id="result"></div>
</body>
You can use IndexOf Javascript function
var str1 = "ABCDEFGHIJK";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}