This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Get the Value of Radiobutton Using JS
(3 answers)
Closed 3 months ago.
So im working on creating a form on javascript, and one of the form criteria is selecting your favorite carbohydrate.
I want to display the selected option on the console, and i tried to create a function for it, but for some reasn when i log it, it says undefined.
My html:
<form>
<label for="firstName">First Name</label><br>
<input type="text" id="firstName" name="fname" required><br><br>
<label for="lastName">Last Name</label><br>
<input type="text" id="lastName" name="lname"><br><br>
<label for="email">Email</label><br>
<input type="email" id="email" name="email" required><br><br>
<label for="comment">Comment</label><br>
<textarea name="comment" id="comment" rows="6" cols="50"></textarea><br>
<p>My favorite Carbohydrate is:</p>
<input type="radio" id="pasta" name="favCarb" value="pasta" required>
<label for="pasta">Pasta</label><br>
<input type="radio" id="rice" name="favCarb" value="rice" required>
<label for="rice">Rice</label><br>
<input type="radio" id="potatoes" name="favCarb" value="potatoes" required>
<label for="potatoes">Potatoes</label><br>
<br><input onclick="submitData" type="submit" id="submitButton" value="Submit">
</form>
My Javascript:
let firstName = document.getElementById("firstName");
let lastName = document.getElementById("lastName");
let email = document.getElementById("email");
let comment = document.getElementById("comment");
let pasta = document.getElementById("pasta");
let rice = document.getElementById("rice");
let potatoes = document.getElementById("potatoes");
let faveCarb = document.getElementsByName("favCarb").value;
let submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", submitData);
function submitData(){
console.log(
"First Name: " + firstName.value +
" Last Name: " + lastName.value +
" Email: " + email.value +
" Comment: " + comment.value +
" Favorite Carb: " + faveCarb.value
)
};
Thanks for the help!
i tried using the .value method, but it logged "undefined" into the console
Related
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id ="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id ="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id ="submit" ><br>
</form>
<p id="sum"></p>
<div id="sumoftotal"></div>
<body>
<script language="JavaScript">
document.getElementById("submit").onclick=function (){
let firstName = document.getElementById("First-name").value;
let lastName= document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total =parseInt(num1) + parseInt(num2);
document.getElementById("sum").innerHTML=(`${firstName} ${lastName} ${total }`)
}
</script>
</body>
my problem can be numbered:
number 1: when I press the submit button, input values show up, BUT when I want to insert a different data, the previous one disappear. I studied about it, because whatever comes in the function scope become local we cannot apply it outside, BUT I don't know how to change it.
number 2: I want to have the sum of total weights I insert at the end of my list, I know we can do this by loop, BUT I need something simpler and more preliminary because I am a novice and it would be a big jump for the time being.
all in all, I would be happy if anyone could help me.
Here is the primary and most basic approach.
var data = document.getElementById('data');
var weightElement = document.getElementById('total-weight');
document.getElementById("submit").onclick = function() {
/* Getting data */
let firstName = document.getElementById("First-name").value;
let lastName = document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total = parseInt(num1) + parseInt(num2);
/* Appending element */
data.innerHTML = data.innerHTML + `First Name - ${firstName}, Last Name - ${lastName}, Weight - ${total} <br/>`;
weightElement.innerHTML = parseInt(weightElement.innerHTML) + total;
}
<body>
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id="submit"><br>
</form>
<div id="data"></div>
<div>Total weight = <span id="total-weight">0</span></div>
</body>
I am trying to take form information, enter them into an info array and then print out that array to a paragraph within a string concatenation.
Here's my HTML:
<body>
<input type="text" id="name" placeholder="Enter first name">
<input type="text" id="lName" placeholder="Enter last name">
<input type="text" id="age" placeholder="Enter age">
<input type="text" id="email" placeholder="Enter email address">
<button>Add Info</button>
<article>
<div>
<p>8</p>
</div>
</article>
<p id="future"></p>
<main>
</body>
Here's my Javascript:
const btn = document.querySelector('button');
const paras = document.querySelectorAll('p');
btn.addEventListener("click", function(){
const name = document.getElementById("#name");
const lName = document.querySelector("#lname");
const age = document.querySelector("#age");
const email = document.querySelector("#email");
let info = [name + " " + lName + " , you are " + age + "!" + " But by your next birthday, you will
inherit $10 million dollars! We will email you your fortune to: " + email + "."];
document.querySelector("#future").innerHTML = info;})
I get:
null [object HTMLInputElement] , you are [object HTMLInputElement]! But by your next birthday, you will inherit $10 million dollars! We will email you your fortune to: null.
There are several problems:
getElementById expects only the id as argument, without #. (querySelector need this, because it takes a css-selector as argument).
There's a typo in this selector: const lName = document.querySelector("#lname"): #lName instead of #lname.
You printed the input-elements, not their values. Use .value for that.
const btn = document.querySelector('button');
const paras = document.querySelectorAll('p');
btn.addEventListener("click", function() {
const name = document.getElementById("name");
const lName = document.querySelector("#lName");
const age = document.querySelector("#age");
const email = document.querySelector("#email");
let info = [name.value + " " + lName.value + " , you are " + age.value + "!" + " But by your next birthday, you will inherit $10 million dollars!We will email you your fortune to: " + email.value + "."];
document.querySelector("#future").innerHTML = info;
})
<body>
<input type="text" id="name" placeholder="Enter first name">
<input type="text" id="lName" placeholder="Enter last name">
<input type="text" id="age" placeholder="Enter age">
<input type="text" id="email" placeholder="Enter email address">
<button>Add Info</button>
<article>
<div>
<p>8</p>
</div>
</article>
<p id="future"></p>
</body>
I'm performing some validation checks on some inputs from the user. I was wondering how do I check that the email entered by the user contains an # symbol and a '.' as well as characters before and after the # symbol. Thanks in advance for answering.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function showInput() {
var comment = document.getElementById("com").value;
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var dateOfVisit = document.getElementById("date").value;
var firstError = document.getElementById('firstNameError');
var lastError = document.getElementById('lastNameError');
var displayEl = document.getElementById('displayname');
if (!first) {
firstError.setAttribute('style', 'display: block; color: red');
} else {
firstError.setAttribute('style', 'display: none;');
}
if (!last) {
lastError.setAttribute('style', 'display: block; color: red');
} else {
lastError.setAttribute('style', 'display: none;');
}
displayEl.innerHTML =
first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
}
</script>
<title>Great Pyramid of Giza</title>
</head>
<body>
<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
First Name:<br>
<input type = "text" name="firstname" id="fname"><br>
<span style="display: none;" id="firstNameError">First name is required!</span>
Last Name:<br>
<input type = "text" name="lastname" id="lname"><br>
<span style="display: none;" id="lastNameError">Last name is required!</span>
Email Address:<br>
<input type = "text" name="email"><br>
Date of Visit:<br>
<input type = "text" name="date" id="date"><br>
Comment:<br>
<input type = "text" name="comment" size="70" id="com"><br>
</form>
<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>
</body>
</html>
You can create a email input and validate against that instead of using any regex...
function isEmail(email) {
var input = document.createElement('input')
input.type = 'email'
input.value = email
return input.validity.valid
}
console.log(isEmail('admin#example.com'))
console.log(isEmail('#example.com'))
But why bother??? just use <input type="email"> and skip all javascript nonsens
<form>
<input type="text" name="firstname" required autocomplete="given-name">
<input type="text" name="lastname" required autocomplete="family-name">
<input type="email" name="email" autocomplete="email">
<input type="date" min="2018-04-21" name="date">
<textarea name="comment"></textarea>
<input type="submit">
</form>
ps, use form.onsubmit instead of btn.onclick (way better)
read more about constraint validation and inputs
This question already has answers here:
Display HTML form values in same page after submit using Ajax [closed]
(7 answers)
Closed 5 years ago.
I am trying to display what is typed and submitted in my form, on the same page. I got the first entry "name" to display, but can't get the rest to show up. I am using JQuery validator. I feel like it's something simple I am missing here. Thanks!
Script:
$(function() {
$("#signup").validate();
$("#signup").submit(function(e) {
e.preventDefault();
var display =
$("#name").val();
$("#theage").val();
$("#theemail").val();
$("#result").html(display);
});
});
Html:
<div>
<form id="signup">
<label for="name" class="label">Enter your name</label>
<input type="text" name="name" id="name" title="Required" class="required">
<label for="theage" class="label">Enter your age</label>
<input type="text" name="theage" id="theage" title="Required" class="required digits">
<label for="theemail" class="label">Enter your email</label>
<input type="text" name="theemail" id="theemail" title="Please enter a valid email address" class="required email">
<input type='submit' value='Submit' name="submit" id='submitme'>
</form>
<p> Your name: </p>
<p> Age: </p>
<p> Email: </p>
<p id="result"></p>
</div>
You need to concatenate the form values. Right now, you're only adding the name to your display var.
var display =
$("#name").val(); // statement ends here because of semicolon
$("#theage").val();
$("#theemail").val();
needs to change to
var display =
$("#name").val() + " " +
$("#theage").val() + " " +
$("#theemail").val();
The error is not throwing in console, you were missing plugins.
$(function() {
$("#signup").validate();
$("#signup").submit(function(e) {
e.preventDefault();
var display =
$("#name").val();
$("#theage").val();
$("#theemail").val();
$("#result").html(display);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<div>
<form id="signup">
<label for="name" class="label">Enter your name</label>
<input type="text" name="name" id="name" title="Required" class="required">
<label for="theage" class="label">Enter your age</label>
<input type="text" name="theage" id="theage" title="Required" class="required digits">
<label for="theemail" class="label">Enter your email</label>
<input type="text" name="theemail" id="theemail" title="Please enter a valid email address" class="required email">
<input type='submit' value='Submit' name="submit" id='submitme'>
</form>
<p> Your name: </p>
<p> Age: </p>
<p> Email: </p>
<p id="result"></p>
</div>
To display the values entered on the form you could use the following:
$(function() {
$("#signup").validate();
$("#signup").submit(function(e) {
e.preventDefault();
var display = "<p>Your name: " + $("#name").val() + "</p><p>Your age: " + $("#theage").val() + "</p><p>Your email: " + $("#theemail").val() + "</p>";
$("#result").html(display);
});
});
I believe your problem is because you are only adding $("#name").val() to the display variable, You need to concatenate them.
var display = $("#name").val() + " " +
$("#theage").val() + " " +
$("#theemail").val();
Here's an example:
var result =
"Hello "; // semi colon ends the assignment
"world"; // this is doing nothing
$('#result1').html(result);
var result2 =
"Hello " +
"world";
$('#result2').html(result2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
1:
<div id="result1"></div>
<br> 2:
<div id="result2"></div>
I have a form that has several fields. The first field is called subject. What I want to do is disable the ability for the user to type in the field, but it still show, and the text they enter into three other fields show up with spaces between the variables in the first field. Example: In this scenario: "Second_Field: John" "Third_Field: Doe" "Forth_Field: New part" then on first field, subject, it will show: John Doe New Part
Thanks for any help.
You can try the following:
<!-- HTML -->
<input type="text" id="subject" disabled="disabled">
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
// JavaScript
var fields = [];
for (var i = 1; i <= 3; i++) {
fields.push(document.getElementById("field" + i).value);
}
document.getElementById("subject").value = fields.join(" ");
Try this:
<script>
function UpdateText()
{
document.getElementById("subject").value =document.getElementById("Field1").value + " " + document.getElementById("Field2").value + " " + document.getElementById("Field3").value;
}
</script>
<input type="text" id="subject" disabled="disabled"/>
<input type="text" id="Field1" onchange="UpdateText()";/>
<input type="text" id="Field2" onchange="UpdateText()";/>
<input type="text" id="Field3" onchange="UpdateText()";/>
HTML:
<form>
<p><input id="subject" name="subject" disabled size="60"></p>
<p><input id="Second_Field" class="part">
<input id="Third_Field" class="part">
<input id="Fourth_Field" class="part"></p>
</form>
JavaScript:
var updateSubject = function() {
var outArray = [];
for (var i=0;i<parts.length;i++) {
if (parts[i].value !== '' ) {
outArray.push(parts[i].value);
}
}
document.getElementById('subject').value = outArray.join(' ');
};
var parts = document.getElementsByClassName('part');
for (var i=0;i<parts.length;i++) {
parts[i].onkeydown = updateSubject;
}