want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.
Related
var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?
I'm trying to write a function that will show an Alert Box for all the data entered by the user in the form. I must do it only in simple javascript (sorry no jQuery). My HTML is as follows:
<form method="POST">
<label class="form">Name: </label><input type="text" name="name" id="name"><br>
<label class="form">Address: </label><input type="text" name="address" id="address"><br>
<label class="form">Email: </label><input type="text" name="email" id="email"><br>
<button id="submit" type="submit" value="submit" onclick="showAlert()">
Submit
</button>
</form>
My javascript:
function showAlert() {
var userInputs = document.getElementsByTagName("input");
for (var i=0; i < userInputs.length; i++) {
alert(userInputs.value + " ");
//Basically my idea would be to implement a loop for as many input fields,
//run through all of them, then display ONE SINGLE alert box containing all the
//data entered by the user. But I'm having trouble with how to implement the loop.
}
}
How do I implement the loop?
I have written another function that achieves the same effect but it involved writing a long, tedious list of variables for each input field and I don't want to do that since it's messy:
function alternateShowAlert() {
var name = document.getElementById('name').value;
var address = document.getElementById('address').value;
var email = document.getElementById('email'.value;
alert(name + " " + address + " " + email)
//This function, although it works fine, will be too long and tedious if I have
//more input fields such as age, city, state, country, gender, etc. I want to put
//it in a loop format but how do I do this?
}
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var alertBody = "";
for (var i=0; i < userInputs.length; i++) {
alertBody += userInputs[i].value + " ";
}
alert(alertBody);
}
document.getElementsByTagName() returns an array, so you need to access the elements of the array using their index: userInputs[i].
Or you can use Array.prototype.forEach. See the example below.
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var alertBody = "";
Array.prototype.forEach.call(userInputs, function(element) {
alertBody += element.value + " ";
});
alert(alertBody);
}
You have the logic: you need the loop to collect all info, but should show only one alert, so instead of alert'ing inside the loop, you need to do it after:
function showAlert() {
var userInputs = document.getElementsByTagName("input");
var infos = ""; // Create a string for the content
for (var i=0; i < userInputs.length; i++) {
infos += userInputs[i].value + " "; // Add the info from user input
}
alert(infos); // Show one alert at the end
}
Martin is getting you part of the way there, but I think you'll trip up at getting the values. Document.getElementsByTagName
returns an HTML collection best treated as an array.
So user inputs.value would probably need to be something like userinputs[i].value for Martin's code to work
You can do it in one single line, without any loop:
function Show() {
alert([].slice.call(document.querySelectorAll("input[type='text']")).map(function(x) { return x.id + ": " + x.value; }).join("\n"));
}
Name: <input type="text" id="name" /><br />
Address: <input type="text" id="address" /><br />
Email: <input type="text" id="email" /><br />
<button type="button" onclick="Show();">Show</button>
The method querySelectorAllis supported by all modern browsers (IE 9+) and is the plain JS equivalent to jQuery selectors. However, it returns a node list which should be converted to plain array in order for us to use the desired .map() method to get all the values easily.
I`m learning and training js oop right now but I have an issue. I want to pass a value to property from a constructor by input value.For example if the user want to make his own character , he has to input name , age ,etc etc... but my code fails.Here's my js and html code.I've searched for the answer in the stackoverflow but couldn't find any answers to my question.
JS
document.addEventListener("DOMContentLoaded", function() {
var button = document.getElementById('action');
var nameInput = document.getElementById('charName').value;
var ageInput = document.getElementById('age').value;
var par = document.getElementById('result');
function Person(name,age){
this.name = name;
this.age = age;
}
var first = new Person(nameInput,ageInput);
button.addEventListener('click',function(){
par.innerHTML = first.name + ' ' + first.age;
});
});
HTML:
<h1>Javascript Found</h1>
<button id="action">Action</button>
<div id="holder">
<p>
Give a name:<input type="text" id="charName" placeholder="Enter a name">
</p>
<p>
Enter age: <input type="text" id="age" placeholder="Enter a number(0-100)">
</p>
<p id="result"></p>
</div>
I would assume that the click listener is executed correctly, but the values of first.name and first.age are ''. You can verify that by putting a console.log(first) in the click listener.
So why is that? At the time your DOMContentLoaded listener triggers, both your inputs are empty (value == ''). Now, you copy these values into an instance of Person. Next, you wait for clicked events which are triggered at some point but the value of name and age in your instance were not updated so they are still "". So you set par.innerHTML = ' '.
What you need to do is, you have to read the values of your inputs again and update the variables in your instance before you set par.innerHTML.
You need to grab the value from the input on click not before that otherwise it will use the old value which would be an empty string.
I changed the code so nameInput and ageInput refer to the elements and the value is then fetch inside the Person class and first is created on click.
See JSFiddle to see it working.
var button = document.getElementById('action');
var nameInput = document.getElementById('charName');
var ageInput = document.getElementById('age');
var par = document.getElementById('result');
function Person(name,age){
this.name = name.value;
this.age = age.value;
}
button.addEventListener('click',function(){
var first = new Person(nameInput, ageInput);
console.log(first);
par.innerHTML = first.name + ' ' + first.age;
});
i have a form which user enters some data, could be checkboxes, radio buttons, textfields, etc
when user click submit button, i want to refresh the page with whatever data that was entered
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
</head>
<body id="ref">
<form>
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
</form>
<input type="button" onclick="c()" value="submit">
<script type="text/javascript">
function c()
{
var o = document.getElementById('ref');
o.innerHTML = '';
var n = document.createElement('p');
var nam = document.getElementById('name');
n.innerHTML = "Your name is: " + nam;
o.appendChild(n);
var a = document.createElement('p');
var ag = document.getElementById('age');
a.innerHTML = "Your age is: " + ag;
o.appendChild(a);
//how do i get the info from the form? because both nam and ag are coming up null
}
</script>
</body>
</html>
my guess this is not working is because the page refreshes then tries to fetch the element by id which is not there anymore.. whats the correct way of doing this??
You're confusing objects with their properties. Here, you're getting the HTMLInputElement instance for the "age" field:
var ag = document.getElementById('age');
But here you're using that object as though it were a simple value:
a.innerHTML = "Your age is: " + ag;
The HTMLInputElement object has a value field you can use for that:
a.innerHTML = "Your age is: " + ag.value;
Separately, you're completely destroying the page by doing this:
var o = document.getElementById('ref');
o.innerHTML = '';
...because you've given the body element the ID "ref". Completely replacing the body element completely replaces the body element, so you can't rely on objects that only exist as subordinates of that element.
The usual thing is to have an element to fill in, and (optionally) to remove the elements you no longer need. For instance (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
<div id="result">
</div>
(Note I moved the button into the form for convenience.)
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result = document.getElementById("result");
form.parentNode.removeChild(form);
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
}
There, when the button is pressed, I remove the form and fill in the "result" div.
You could add the "result" div dynamically if you wanted (live copy):
HTML:
<form id="theForm">
Please enter your name:<input type="text" id="name" />
Please enter your age:<input type="text" id="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.getElementById("theForm"),
nameField = document.getElementById("name"),
ageField = document.getElementById("age"),
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
You can access the fields using a briefer and somewhat more natural syntax if you change your id values to name values instead (live copy):
HTML:
<form name="theForm">
Please enter your name:<input type="text" name="name" />
Please enter your age:<input type="text" name="age" />
<input type="button" onclick="c()" value="submit">
</form>
JavaScript:
function c() {
var form = document.theForm,
nameField = form.name,
ageField = form.age,
result;
result = document.createElement("div");
result.innerHTML =
"Your name is " + nameField.value +
" and your age is " + ageField.value;
form.parentNode.insertBefore(result, form);
form.parentNode.removeChild(form);
}
Further reading:
DOM2 Core (well-supported by most modern browsers)
DOM2 HTML
DOM3 Core (increasingly supported)
If you want to update your html using java-script only , you may use ".value" attribute of the input;
var a = document.createElement('p').value;
var ag = document.getElementById('age').value;
Usually the Form information is processed using server-side code , this is done by specifying the action attribute of the form:
<form action="processuserinfo.aspx">
...
</form>
I'm pretty sure this isn't doable javascript alone. You'll need to use a server-side language like php. Try to google php forms, and you should get some good results. :)
I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga
A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};
First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B
JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}
i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>