JavaScript/HTML: How to display user input into html body? - javascript

heres my html form:
<label>Name:</label><input type ="text" input id="myName" /><br>
<label>Street:</label><input type="text" input id="myStreet" /><br>
<label>City:</label><input type="text" input id="myCity" /><br>
<label>State:</label> <input type="text" input id="myState" /><br>
<label>Zip:</label> <input type="text" input id="myZip" /><br>
<input type="submit" value="Submit" onclick="myAlert()">
</form>
//my myAlertFunc (from external file)
function myAlert(){
var person = new Person(document.getElementById('myName').value, document.getElementById("myStreet").value, document.getElementById("myCity").value, document.getElementById("myState").value, document.getElementById("myZip").value);
alert(person.getFullAddress());
}
//and my getFullAddress proto from my Person class
Person.prototype.getFullAddress = function () {
return ("Hi, my name is" + " " + this.name + "," + " " + "and my address is:" + " " + this.street + "," + this.city + "," + this.state + "," + this.zip);
};
Now, onclick, the myAlertFunc alerts the users input values. How do I display these values in my html body? I know I am supposed to use a element with just an input id and use document.getElementById(); to call that id but i have no idea what to do after that.
Thanks in advance!

The attribute you're looking for is innerHTML: http://www.w3schools.com/jsref/prop_html_innerhtml.asp
So, your code would be something along the lines of:
// alert(person.getFullAddress());
document.getElementById("resultDiv").innerHTML = person.getFullAddress();
Where "resultDiv" is the ID of the element where you want the result to display.
Good luck!

you can set the innerHTML of the element or its value if it's an input

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>

Combining radio buttons and a text field

I have four radio buttons, the last being an option for "other." Clicking this radio button reveals a hidden text field so the user can explain further. This is part of a larger form that creates an email based on the options the user chose. Basically, the four radio buttons/other field need to be combined so the user's answer to that section shows up in the email, whether they pick a radio button or type in their own response. Here's my HTML:
<h1>Reason</h1>
<input type="radio" name="reason" class="reason" value="Customer requesting escalation" onclick="document.getElementById('hiddenOtherField').style.display='none'" checked>Customer requesting escalation<br>
<input type="radio" name="reason" class="reason" value="Workaround lost" onclick="document.getElementById('hiddenOtherField').style.display='none'">Workaround lost<br>
<input type="radio" name="reason" class="reason" value="Resolution overdue" onclick="document.getElementById('hiddenOtherField').style.display='none'">Resolution overdue<br>
<input type="radio" name="reason" class="reason" id="otherRadioBtn" onclick="document.getElementById('hiddenOtherField').style.display='block'">Other...<br>
<div id="hiddenOtherField" style="display: none">
<input type="text" name="reason" id="otherFreeTextField" placeholder="Please explain...">
</div><br>
I'm getting the selected value of this "Reason" section from jQuery:
$(".reason:checked").val()
But when "Other" is checked, the value of $(."reason") is "on" instead of whatever they typed. I have no idea why or how or where the word "on" comes from (it's nowhere in my code). I know I'm missing something but I don't know what. How would I make it so if the user selects the "other" radio button, whatever they type into the text field becomes the value for "reason"? I've tried a bunch of different if statements, but it's been hours and nothing is working. Please help! Thanks!
Edit - here is the Javascript code I'm using to display my values. Again, this is all a custom HTML form used to create an email based on the options the user chose. All of the other things here I'm getting the values of are working because they're straightforward.
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + $(".reason:checked").val() + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
I'm using a button at the end of my form to generate the email:
<input type="submit" value="Generate email" onclick="generateEmail()">
If you want to get the input value that the user typed you need to use :
$("#otherFreeTextField").val()
So you have to add a check if the other is checked then the reason will be the value of the input :
var reason = $(".reason:checked").val();
if( $('#otherRadioBtn').is(':checked') ) {
reason = $("#otherFreeTextField").val();
}
As a shortcut you could use :
$('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
In you context the condition should be injected like :
function generateEmail() {
var emailTo = $("#teamName").val();
var emailCC = $("#CC").val();
var emailSubject = $("#ticketNumber").val();
var reason = $('#otherRadioBtn').is(':checked')?$("#otherFreeTextField").val():$(".reason:checked").val();
var emailBody = "Issue: " + $("#issue").val() + "%0A%0ACustomer Contact Information: " + $("#contactInformation").val() + "%0A%0ARequested Action: " + $(".requestedAction:checked").val() + "%0A%0AReason: " + reason + "%0A%0AWorkaround Available? " + $(".workaround:checked").val();
location.href = "mailto:" + emailTo + "?cc=" + emailCC + "&subject=" + emailSubject + "&body=" + emailBody;
};
This is happening because you are checking the status of textbox if visible or not.$(".reason:checked").val(). That's why it's giving on cause it's visible.
Try: $(‘.reason:textbox’).val()

Changing value of text field with jQuery

I have a form input text field, and I want to change the text inside of the text field when the user clicks a button. I can get the specific textfield with jQuery, but cannot change the text with .val(). Is there another way this can be done, or am I doing something wrong.
Here is the text field:
<input type="text" name="textBox" id="Stage 1text" size="20" value="Enter Current Comp." align="center">
Then I use this to identify and change the text field. where in this case stage = "Stage 1" and dance is the string I want to place in the text field.
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
An ID should not have spaces. Stage 1text is an invalid ID
Add an underscore instead of space
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
and try below,
// v--- assuming this will be Stage_1
str = "#" + stage + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);
incase if stage is returned from backend.. then simply replace space with _
str = "#" + stage.replace(/ /g,"_") + 'text';
id attributes should not contain spaces.
You could change your code like so:
<input type="text" name="textBox" id="Stage_1text" size="20" value="Enter Current Comp." align="center">
str = "#" + stage.replace(' ','_') + 'text';
alert(str + '::' + dance); // confirm that strings are correct
jQuery(str).val(dance);

simpler way of grouping numerous variables by value of select?

thanks for looking.
im still learning the more complex javascript and jquery coding so could do with some help as i have no idea about the following or even if its possible!
i need a better/simpler/shorter way of doing the following (please note i have removed the irrelevant validation etc coding):
'
function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
{
//store values
Myform = document.forms.myform;
box1 = Myform.box1.value;
box2 = Myform.box2.value;
box3 = Myform.box3.value;
box4 = Myform.box4.value;
box5 = Myform.box5.value;
s1 = Myform.s1.value;
s2 = Myform.s2.value;
s3 = Myform.s3.value;
s4 = Myform.s4.value;
s5 = Myform.s5.value;
//set as one string
Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;
// next function...
} '
as you can see i have 5 input boxes and relevant selects for each box(each select has 4 options:1,2,3,4.). when a user enters data into a box they choose a relevant option. all boxes and options must be entered then they submit the form.
this data will be emailed to me as the variable stored under storeall. which would be something like 1:1234;2:1324;1:3232;4:5434;2:3211;
so what i hope to do is simplify this data into the following with either a seperate function or the same one: 1:1234-3232;2:1324-3211;4:5434;
is this possible? or have i done it the easiest way?
any comments or help welcomed, thanks again
First, you'll want to group these things into a single element that can be iterated against. So if your HTML looks like:
<form>
<input name="s1" />
<input name="box1" />
<input name="s2" />
<input name="box2" />
...
</form>
Then it's probably better to do something like:
<form>
<div class="set">
<input class="s" name="s1" />
<input class="box" name="box1" />
</div>
<div class="set">
<input class="s" name="s2" />
<input class="box" name="box2" />
</div>
...
</form>
Now you've established some commonality among these elements, instead of just different names/IDs. Each set of inputs is grouped by the .set class, and within each set, you know there's going to be two inputs: one with the .s class, and one with the .box class. Now iterating against them with JQuery is easy:
var str = "";
$("form div.set").each(
function(index, element)
{
currentValueS = $(element).find("input.s").val();
currentValueBox = $(element).find("input.box").val();
str += currentValueS + ":" + currentValueBox + ";";
}
);
This uses JQuery's .each() function. .each() allows you to provide a function to perform on each of the elements that JQuery finds from the indicated selector. Here, your selector is form div.set, which means "all div elements that have the class of .set, and are found anywhere under any form element". For each of these elements, you'll need to find the value of the <input> element with the .s class, and also the value of the <input> element with the .box class. Then you just add those to your growing str variable.
If you want everything in the form, you should use serializeArray :
$('#my_form').submit(function() {
var str = '';
$.each($(this).serializeArray(), function () {
str += this.name + ":" + this.value + ";";
});
sendByMail(str);
return false;
});

how do i get the info from a form using 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. :)

Categories