I am just starting out but I am stuck in what many will likely find to be a simple problem. I am trying to have multiple inputs concatenate after a button is pressed at the end.
Here is the code I tried but only "fname" shows up after I click the button instead of the value that was input into the space. What am I missing?
<!DOCTYPE html>
<html lang="en">
<body>
<p> Please enter your First Name: <input type="text" id="fname"></p>
<p> Please enter your Last Name: <input type="text" id="lname"></p>
<p> Please enter your User ID: <input type="text" id="uid"></p>
<p> Please enter your date of birth: <input type="date" id="bday"></p>
<button onclick="getEls()">Click Here<br>
When Done</button>
<script>
function getEls() {
document.getElementById("answer");
answer.innerHTML = (Hello + "fname" + " " + "lname" + your user id is " uid" + and your birthday is + "bday".);
}
</script>
<p id=answer>
<p>
</body>
</html>
I don't know if I understand well your question but is that what you want?
function getEls() {
var answer = document.getElementById("answer");
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var uid = document.getElementById("uid").value;
var bday = document.getElementById("bday").value;
answer.innerHTML = ("Hello " + fname + " " + lname + " your user id is " + uid + " and your birthday is " + bday + ".");
}
<!DOCTYPE html>
<html lang="en">
<body>
<p>
Please enter your First Name:
<input type="text" id="fname">
</p>
<p>
Please enter your Last Name:
<input type="text" id="lname">
</p>
<p>
Please enter your User ID:
<input type="text" id="uid">
</p>
<p>
Please enter your date of birth:
<input type="date" id="bday">
</p>
<button onclick="getEls()">
Click Here<br>
When Done
</button>
<p id=answer>
<p>
</body>
</html>
If you have any questions please tell me in the comment
Your errors were a combination of typos (which would be a valid close reason), and a misunderstanding of how to use HTML <input> elements, and their values, in a String.
First, we'll look at the mistakes:
function getEls() {
// here, you retrieve an element correctly but don't
// assign it to a variable, and you do nothing with it;
// this is valid JavaScript, and not necessarily an error,
// but it's entirely pointless:
document.getElementById("answer");
// the reason that this works is the legacy of a terrible
// decision by Microsoft - years ago - to make any element
// with an id an automatic global variable, with the variable-
// name being the (unique) id of that element. This is
// a common implementation, but not listed in the spec so
// it may change in future; don't rely on the behaviour (and
// ideally don't use global variables):
answer.innerHTML =
// here you have hard-coded String components to which
// you want to interpolate/concatenate your supplied
// variables; unfortunately (for reasons unknown) you chose
// to leave the String unquoted (so, in JavaScript, these
// become undeclared variables), and you've quoted the
// variable names (and a lone white-space):
(Hello + "fname" + " " + "lname" + your user id is " uid" + and your birthday is + "bday".);
// Also, you seem to have a '+' operator missing, which
// contributes to the 'missing ) in parenthetical' error.
}
To correct this:
<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>
<button onclick="getEls()">Click Here<br>
When Done</button>
<script>
function getEls() {
let answer = document.getElementById("answer"),
fname = document.getElementById('fname'),
uid = document.getElementById('uid'),
bday = document.getElementById('bday');
answer.innerHTML = ("Hello" + fname.value + " " + lname.value + "your user id is " + uid.value + " and your birthday is " + bday.value + ". ");
}
</script>
<p id=answer></p>
JS Fiddle demo.
Now, while that works, we're going to refine it towards code that's more DRY (don't repeat yourself), and also towards unobtrusive JavaScript, which moves the event-handling out of the HTML:
// using a simple named function, using Arrow syntax, to retrieve an element
// via its assigned 'id' attribute-value (this is optional, but personally I
// don't like typing 'document.getElementById(...)' more than once):
const dGEBI = (id) => document.getElementById(id),
// your function, declared as a constant (on the assumption you're
// unlikely to redefine the function through the lifetime of your
// page):
getEls = function () {
// we retrieve the various elements, and assign them to
// variables:
let answer = dGEBI('answer'),
// we retrieve the <input> elements, and cache their values:
fname = dGEBI('fname').value,
lname = dGEBI('lname').value,
uid = dGEBI('uid').value,
bday = dGEBI('bday').value;
// here we use a template-literal to construct the String; this is
// delimited by backticks; and we can directly interpolate JavaScript
// variables or the results of JavaScript expressions into the String,
// by wrapping them with curly-braces ('{...}') and prefixing with a '$'
// character:'
answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
}
// here we use document.querySelector() to retrieve the first (if any) element matching
// the supplied CSS selector; and then use EventTarget.addEventListener() to bind
// the getEls() function (note the deliberate lack of parentheses) as the event-handler
// for the 'click' event:
document.querySelector('button').addEventListener('click', getEls);
<p>Please enter your First Name: <input type="text" id="fname"></p>
<p>Please enter your Last Name: <input type="text" id="lname"></p>
<p>Please enter your User ID: <input type="text" id="uid"></p>
<p>Please enter your date of birth: <input type="date" id="bday"></p>
<button>Click Here<br>When Done</button>
<p id=answer></p>
JS Fiddle demo.
Next, We'll take a look at your HTML; and use <label> elements:
const dGEBI = (id) => document.getElementById(id),
getEls = function() {
let answer = dGEBI('answer'),
fname = dGEBI('fname').value,
lname = dGEBI('lname').value,
uid = dGEBI('uid').value,
bday = dGEBI('bday').value;
answer.innerHTML = `Hello ${fname} ${lname}, your user id is: ${uid}, and your birthday is: ${bday}. `
}
document.querySelector('button').addEventListener('click', getEls);
label {
display: block;
}
label:last-of-type {
display: revert;
}
<!-- Here, we've replaced the <p> elements with <label> elements; this
allows the user to click the text of the <label> to focus the
associated <input> element: -->
<label>Please enter your First Name: <input type="text" id="fname"></label>
<label>Please enter your Last Name: <input type="text" id="lname"></label>
<label>Please enter your User ID: <input type="text" id="uid"></label>
<!-- I've taken a different approach here, and used the 'for' attribute to
associate the <input> and <label>; for this approach the 'for' attribute
must contain the exact 'id' attribute-value of the relevant <input>: -->
<label for="bday">Please enter your date of birth: </label> <input type="date" id="bday">
<button>Click Here<br>When Done</button>
<p id=answer></p>
JS Fiddle demo.
References:
HTML:
<input>.
<label>.
JavaScript:
Arrow functions.
document.getElementById().
document.querySelector().
EventTarget.addEventListener().
HTMLInputElement.
HTMLLabelElement.
Template-literals.
Related
I can imagine that the answer is simple, can someone look over my code. It's supposed to be two input boxes with a popup saying (Welcome "first-name" "last-name")
function welcomeTheUsar() {
// Some code borrowed and rewritten from UNKNOWN's lessons
let firstName = document.getElementById("first-name").value;
let lastName = document.getElementById("last-name").value;
let fullName = "first-name" + "last-name".value;
console.log(fullName);
alert("Welcome " + "fullname");
}
<!-- Make my name in alternating colors for each of the letters-->
<h1>Cora</h1>
<div id="welcomeTheUsar">
<!--This is the welcome div for the user, code also borrowed and moddified from UNKNOWN's lessons-->
<input placeholder="Enter First Name" id="first-name">
<input placeholder="Enter Last Name" id="last-name">
<button onclick="welcomeTheUsar()">Greetings</button>
</div>
you don't user variable names inside strings like this "variableName", it will be just interpreted as plain text.
It should be like this:
<script>
function welcomeTheUsar() {
// Some code borrowed and rewritten from UNKNOWN's lessons
let firstName = document.getElementById("first-name").value;
let lastName= document.getElementById("last-name").value;
let fullName= `${firstName} ${lastName}`;
console.log(fullName);
alert("Welcome "+fullName);
}
</script>
<!-- Make my name in alternating colors for each of the letters-->
<h1>Cora</h1>
<body>
<div id="welcomeTheUsar">
<!--This is the welcome div for the user, code also borrowed and moddified from UNKNOWN's lessons-->
<input placeholder="Enter First Name" id="first-name">
<input placeholder="Enter Last Name" id="last-name">
<button onclick="welcomeTheUsar()">Greetings</button>
</div>
The anwer should be:
function welcomeTheUsar() {
// Some code borrowed and rewritten from UNKNOWN's lessons
let firstName = document.getElementById("first-name").value;
let lastName= document.getElementById("last-name").value;
let fullName=firstName+ " " + lastName;
console.log(fullName);
alert("Welcome "+ fullName);
}
You are not using the given variables but text strings that looks like the variables.
This one will not work, since it's just text, and you try to get the value of a string "last-name".value, which you cant.
let fullName="first-name"+"last-name".value;
This one will just show "Welcome fullname"
alert("Welcome "+"fullname");
When you use quotation around something, it seen as a text and not a variable.
function welcomeTheUsar() {
const
firstName = document.getElementById("first-name").value,
lastName = document.getElementById("last-name").value;
alert(`Welcome ${firstName} ${lastName}`);
}
<div id="welcomeTheUsar">
<input placeholder="Enter First Name" id="first-name">
<input placeholder="Enter Last Name" id="last-name">
<button onclick="welcomeTheUsar()">Greetings</button>
</div>
<input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." name="subject" pattern=".+?(?:[\s'].+?){2,}" autofocus required title="" />
I have a problem with this, it is inserting when i insert repeating words like
college college college
and i also wanto to have a question format it is possible?
also open for java script suggestions even i already have
This works pretty good (when user pastes, inserts anything):
Code Snippet:
<!DOCTYPE HTML>
<html>
<body>
<input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here..." name="subject" pattern=".+?(?:[\s'].+?){2,}" autofocus required title="" />
<button id="toggleduplicates">Toggle allowing duplicates</button>
<script>
// I added this to allow duplicates
let allowDuplicates = false;
var element = document.getElementById("btn-input"),
togglebtn = document.getElementById("toggleduplicates");
function handler(e){
if(!allowDuplicates){
var userInput = element.value,
allWords = userInput.split(" "),
searchedWords = [];
// Search thru all words (Indicating words by splitting the input in spaces, as done in the "allWords" variable)
for(i = 0; i < allWords.length; i++){
// If the current word (allWords[i]) already is in the searchedWords array
if(searchedWords.includes(allWords[i]))
element.value = element.value.replace(allWords[i] + " ", "");
// Adds the word to the list of used words
searchedWords.push(allWords[i]);
}}}
// Execute the function "handler" when the input field is updated
element.addEventListener("input", handler);
function toggleHandler(){
// Setting the allow duplicates boolean to the value that is not currently (true -> false / false -> true)
allowDuplicates = !allowDuplicates;
// Updates the input, in case it would include duplicates
handler();
alert("You may now " + (!allowDuplicates ? "NOT ":"") + "use duplicate words.");
}
// Execute the function "toggleHandler" when the button is clicked
togglebtn.addEventListener("click", toggleHandler);
</script>
</body>
</html>
I've looked around for an answer to my question, but all the solutions I have found do not take into account that spaces also work as input.
I have a join function, and the button shouldn't be enabled if a user only enters space. It should need actual text. Anyone has a solution to this?
Here's my function:
$("#join").click(function(){
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
$("#login").detach();
$("#UsersOnline").show();
$("#msg").show();
$("#messaging").show();
$("#msg").focus();
ready = true;
}
you could use jquery trim()
var name = $.trim($("#name").val());
https://api.jquery.com/jQuery.trim/
EDIT:
As #David Thomas pointed out, we can also use String.prototype.trim()
var name = $("#name").val().trim();
function updateResult() {
var before = $("#name").val().replace(/\s/g,'SPACE');
var name = $("#name").val().trim();
$('#result').text('Before:' + before + "\nAfter:" + name);
}
$(document).ready(function(){
updateResult();
$('body').on('keyup','#name',function(){
updateResult();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>By default value i left left a space for the name</p>
Name : <input type="text" id="name" value=" "><br>
<br>
Value of name : <pre id="result">empty</pre>
Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>
I need to display the answer from the form in a story. The story must be displayed below the form only after the form is successfully submitted (not an alert), and with the form remaining on the page (not a new page). I am able to insert the form values into the story, but need help with displaying the story after form is submitted. I cannot use anything but html and javascript. I think this can be done with innerHTML.
<head><title>Questions</title>
<script type = "text/javascript" src="quiz1.js">
</script>
</head><body>
<h1>Tell Me About Yourself</h1>
<form name = "the_form" action = "" method = "post"
onSubmit = "var the_result = checkMandatory(); return the_result;">
Full Name:<input type = "text" name = "name" id = "name" /><br/>
Favourite Animal:<input type = "text" name = "animal" id = "animal"><br/>
Favourite Food:<input type = "text" name = "favFood" id = "favFood"><br/>
Favourite Destination:<input type = "text" name = "destination" id = "desitnation"><br/>
Least Favourite Food:<input type = "text" name = "leastFav" id = "leastFav"><br/>
Happiest Moment:<input type = "text" name = "moment" id = "moment"><br/>
Adjective that describes you:<input type = "text" name = "adjective" id = "adjective"><br/>
<br>
<input type="button" value="Submit" onClick = "checkMandatory(); return false;"/><br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>
function checkMandatory()
{
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0))
{
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0,name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
document.write("The young person's name was "+firstName+". "+firstName+" loved to ride
"+animal+
" almost every day. "+firstName+"'s second happiest moment, only next to "+moment+", was in
"+destination+", where "+favFood+
" was served for breakfast, lunch and dinner. It was only when "+firstName+" was told that
"+favFood+
" is actually made from "+animal+", that it instantly became "+firstName+"'s least
favourite food, even worse than "+leastFav+
", and that made "+firstName+" feel very "+adjective+" indeed.")
//document.getElementById('storyDiv').innerHTML = document.getElementById('name').value;
//document.getElementById(‘storyDiv’).innerHTML="The boy's name was "+firstName;
//document.write(‘storyDiv’).innerHTML="The boy's name was " + firstName;
}
}
You can achieve this by posting your form using ajax.
Don't call writethetext(); in your submit button
I'll use jQuery in my solution:
$(function() {
$("form").on("submit", function(e) {
var data = JSON.stringify($("form").serializeArray());
e.preventDefault();
$.post("yourserver/path/", data, function(result) {
writethetext(result);
});
});
});
function checkMandatory() {
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0)) {
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0, name.indexOf(" "));
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
}
}
function writethetext() {
document.getElementById(‘storyDiv’).innerHTML =
("There once was a boy named" + name;)
var firstName = name.substring(0, name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
}
function writethetext(text) {
document.getElementById(‘storyDiv’).innerHTML = text;
}
}
<html>
<head>
<title>Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="quiz1.js">
</script>
</head>
<body>
<h1>Tell Me About Yourself</h1>
<form name="the_form" action="" method="post" onSubmit="var the_result = checkMandatory(); return the_result;">
Full Name:
<input type="text" name="name" id="name" />
<br/>Favourite Animal:
<input type="text" name="animal" id="animal">
<br/>Favourite Food:
<input type="text" name="favFood" id="favFood">
<br/>Favourite Destination:
<input type="text" name="destination" id="desitnation">
<br/>Least Favourite Food:
<input type="text" name="leastFav" id="leastFav">
<br/>Happiest Moment:
<input type="text" name="moment" id="moment">
<br/>Adjective that describes you:
<input type="text" name="adjective" id="adjective">
<br/>
<br>
<input type="button" value="Submit" onClick="checkMandatory();
return false;" />
<br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>