how do i get the info from a form using javascript? - javascript

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. :)

Related

How to add values from previous input to textarea

I am trying to add values from 2 of my inputs to the text area. I was able to find a solution to grab one of the inputs and hope someone can help me find a way to get another one. Also, is there a way to grab another element from the page for example php echo of student's first name?
Please see the picture
I would like this to say "Hey, student_first_name, my name is last_name from university_name, let's connect.
This is the code I have
<script>
// save the location of the name field
var message_field = document.getElementById('university');
var last_name_field = document.getElementById('last_name');
//add an event listener to activate if the value of the field changes
message_field.addEventListener('change', function() {
// when the field changes run the following code
// copy the text (value)
var name = message_field.value;
// concatenate it with the desired message
var autoFill = 'Hi ' + name + ', thank you for visiting us!';
// and paste it into the message field.
document.getElementById('message').value = autoFill;
})
</script>
<script>
// save the location of the name field
var university = document.getElementById('university_name').value;
var last_name = document.getElementById('last_name').value;
var first_name = document.getElementById('student_first_name').value;
//add an event listener to activate if the value of the field changes
message_field.addEventListener('change', function() {
// when the field changes run the following code
// copy the text (value)
var name = message_field.value;
// concatenate it with the desired message
var autoFill = autoFill + university;
autoFill = autoFill + last_name;
autoFill = autoFill + first_name;
// and paste it into the message field.
document.getElementById('message').value = autoFill;
})
</script>
it's a little bit confuse your HTML code, but i did an HTML code and adjusted your javascript code, I hope this helps you.
PS.: You can always group your inputs and textareas inside a FORM tag
https://www.w3schools.com/html/html_forms.asp
var form = document.getElementById("myForm");
form.addEventListener("input", function () {
var name = document.getElementById('name').value;
var lastName = document.getElementById('last_name').value;
var university = document.getElementById('university').value;
document.getElementById('message').value = 'Hey, ' + name + ', my name is ' + lastName + ' from ' + university + ', let\'s connect'
});
<form id="myForm">
<div>
<input type="text" placeholder="First Name" id="name">
</div>
<div>
<input type="text" placeholder="Last Name" id="last_name">
</div>
<div>
<input type="text" placeholder="University Name" id="university">
</div>
<div>
<input type="text" placeholder="Phone Number" id="phone">
</div>
<div>
<input type="email" placeholder="Email address" id="email">
</div>
<div>
<textarea name="Message" id="message" cols="30" rows="10" placeholder="Message (optional)"></textarea>
</div>
</form>

User input to build URL

I have a bit of experience with HTML but am very new to JavaScript. In essence, I would like for a user input to be part of a URL. For example, we could have something simple such as:
<script>
function get_cityname() {
var cityname = document.getElementById("cn").value;
alert(cityname);
}
</script>
<form>
Enter city name:
<input type = "text" size = "12" id = "cn">
<input type = "submit" onclick = "get_cityname();">
</form>
This will create a textbox where a user inputs their text (city name) and then click the 'submit' button next to it, and an alert should pop up based on the information they provided, just to make sure this works. However, this code only would seem to work (because of the 'onclick' command) to work for one user input. Therefore, I have 2 questions:
How could the above variable be included in a URL string? If it were something simple as:
URLstring = "https://sampleurl" + cityname + "moretext.html"
How could this be expanded if I want to include two or possibly even n number of inputs? For example, if I create more user prompt boxes and want to have the user also be able to input their zipcode, or state abbreviation, for example:
URLstring = "https://sampleurl" + cityname + "moretext" + zipcode + "moretext" + "stateabbreviation.html"
You could do something along these lines (it would be the same for one or more fields):
// Ensures the DOM (html) is loaded before trying to use the elements
window.addEventListener('DOMContentLoaded', function() {
var cnInput = document.getElementById("cn"),
zipInput = document.getElementById("zip"),
form = document.getElementById("myForm");
form.addEventListener('submit', getUrl); // On submit btn click, or pressing Enter
function getUrl(e) {
var cityname = cnInput.value,
zipcode = zipInput.value,
url = "https://sample.com/" + cityname + "/" + zipcode + ".html";
alert(url);
e.preventDefault(); // Prevent the form from redirecting?
}
});
<form id="myForm">
<label>Enter city name: <input type="text" size="12" id="cn"></label>
<label>Enter zip code: <input type="text" size="12" id="zip"></label>
<input type="submit">
</form>
First specify an action attribute for your form. This is where your form will be submitted. Then set your form's method attribute to GET. Finally, add as many fields as you like (I am assuming you are after a GET query such as https:url.com?key1=val1&key2=val2...):
<form method="GET" action="https://sampleurl">
Enter city name:
<input type="text" size="12" id="cn">
Enter zip code:
<input type="text" pattern="[0-9]{5}"
<input type="submit" ">
</form>

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

How to pass input variable from HTML Form

I'm trying to create a code which will take ask the user how many items of X, Y, etc and use Javascript to calculate the total owed and also to print a summary (receipt) of all items purchased. Sorry for noob question, trying to learn code without any formal training. Thanks for all of the help!
<html>
<head>
<title>Cost Calculator</title>
<script language="javascript" type="text/javascript">
function packageTotal(){
//Enter in prices here
var applePrice = 1;
var bookPrice = 2;
x = Number(document.calculator.books.value);
y = Number(document.calculator.apples.value);
var b = applePrice*x + bookPrice*y;
var p = applePrice*x + bookPrice*y + .5;
if (document.getElementById('noBag').checked) {
//Basic package is checked
document.calculator.total.value = b;
} else if (document.getElementById('yesBag').checked) {
//Pro package is checked
document.calculator.total.value = p;
}
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
}
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- Here user will enter the number of Books and Apples -->
Enter Number of Books: <input type="text" name="books">
<br />
Enter the Number of Apples: <input type="text" name="apples">
<br />
<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag
<!-- Here result will be displayed. -->
<input type="button" value="Submit" onclick="packageTotal();">
Your Total Price is: <input type="text" name="total">
</form>
</body>
</html>
It's not clear from the question, but if this is the problem:
//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");
then that would certainly break. document.write only adds to the current document when the document is still loading. If you call it afterwards it will implicitly open a new document to write to, destroying the current page. Generally document.write is a bad thing.
(also there are trivial syntax errors due to missing + concatenation operators)
If you want to write arbitrary text to the page, create a placeholder element:
<div id="message"></div>
and then set its text content:
function setTextContent(element, text) {
element.innerHTML = ''; // remove current content
element.appendChild(document.createTextNode(text));
}
var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');
(There is a textContent property on elements which you can also use instead of the function, but it's not supported on IE<9 which use innerText instead. Simply writing the message directly to innerHTML would also work in this case, but it is a bad habit because it leads to HTML-injection security holes when used with user input.)

Dynamic values in object properties

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.

Categories