I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"
Related
I want to read user input into a form back to them, sort of a confirmation before they send it in. I have some text elements on the page with their corresponding IDs. I would think that I just need to set the variables equal to the values of the input field, but when the function runs it just returns blank.
I have a function that sets the variables to the .value of that form input, but where I might be getting hung up is that there is no default value on the input field, I would think that the value is set after the user inputs something.
Example user inputs "John Doe" into field shouldn't that change the value of that field to "John Doe"?
var Phone;
document.getElementById('confirm-details').onclick = ConfirmDetails()
function ConfirmDetails() {
// Set variable to form input
Phone = document.getElementById("InputPhone").value;
// Change text element to variable
document.getElementById("BookingPhone").innerHTML = Phone;
};
Maybe I'm just confused about the .value attribute but I thought that the value on an input field should be what the user inputted.
This row
document.getElementById('confirm-details').onclick = ConfirmDetails()
should be
document.getElementById('confirm-details').onclick = ConfirmDetails
You don't want that document.getElementById('confirm-details').onclick references the result of the function ConfirmDetails (here void) but the function itself.
Instead of using .value, you need to be using .innerText
Phone = document.getElementById("InputPhone").innerText;
object.oninput = function(){
ConfirmDetails();
};
or, shorthand:
object.oninput = function(){ConfirmDetails()};
You should also use document.getElementById().innerHTML() to get the text
This worked just fine for me. I appreciate all the answers!
<script>
document.getElementById("confirm-details").addEventListener("click", function(){
document.getElementById("BookingName").innerHTML = document.getElementById("InputName").value;
document.getElementById("BookingEmail").innerHTML = document.getElementById("InputEmail").value;
document.getElementById("BookingPhone").innerHTML = document.getElementById("InputPhone").value;
document.getElementById("InputDay").innerHTML = document.getElementById("BookingDay").value;
document.getElementById("InputTime").innerHTML = document.getElementById("BookingTime").value;
document.getElementById("InputService").innerHTML = document.getElementById("BookingService").value;
document.getElementById("InputExtra").innerHTML = document.getElementById("BookingExtra").value;
});
</script>
Here is what I believe you are trying to accomplish:
function confirmDetails() {
// Set variable to form input
var phone = document.getElementById("inputPhone").value;
var confirmMsg = 'is ' + phone + ' correct?' + '<br> <input type="button" value="Yes" onclick="confirmed()"> ';
// Change text element to variable
document.getElementById("bookingPhone").innerHTML = confirmMsg;
};
function confirmed(){
alert('confirmed');
}
<input id="inputPhone" type="text" placeholder="input here">
<input type="button" onclick="confirmDetails()" value="Submit">
<br>
<span id="bookingPhone"></span>
When the button is clicked, it runs the function confirmDetails and sets the variable phone to the user's input. I set variable confirmMsg to the confirm message which reads back the user's input. I used a span with a unique ID and sent the variable confirmMsg to it.
I put the confirm message into a variable to make it more versatile, should you need it elsewhere.
I have an input form which looks like this:
<input type="number" value="0.00" step="0.05">
I found the step function which technically solves my increment problem changing it to 0.05 instead of the default 1. I have however not found a solution where I can change the increment without changing the valid inputs.
The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome.
Thank you very much!
EDIT:
Adding nonvalidateto the html form-tag solved this for me. Now pressing the buttons use the increments I want but when I need to specify more accurately than the steps the form still accepts the values.
<form action="/run" novalidate>
<input type="number" value="0.00" step="0.05">
<input type="submit">
</form>
Using novalidate in the form tag will get rid of the validation for the whole form but keep the increments implemented by step.
Update
"I did add nonvalidate to the form tag. It let's me do what I want as of now but it might not be the best solution."
If you don't want your form "compromised" by novalidate, then have 2 forms:
Form A [No action or method]
All user interaction and calculations are here.
All inputs can be modified without worrying about built-in validation from the form.
Form B [Set action and method optional target]
The submit button resides within
Add a hidden input for each value on Form A you want to submit and ensure each has a name attribute and value.
Any client-side validation should be done here.
With that setup you'll need an event like onbeforesubmit so the values of Form A can transfer over to Form B before it submits to the server. Unfortunately I don't think it exist as a standard, but to emulate it is simple:
formA.onsubmit = b4Submit;
function b4Submit(event) {
hidden_Input_In_FormA.value = number_Input_With_Crazy_Step_In_FormA.value
return true;
}
So this contrived example shows an event handler that gets the value from one form then stores it in the other form. Next it continues by submitting whatever data it has. This is due to the callback returning true, should false be returned, the callback function itself dies and so does the submit event along with it.
The Demo has been updated to do what was just described above. Note: there are no novalidate attributes in use. The second form (Form B or form#tx) is sending text from a hidden input as far as it's concerned. A number like -103.002684109 is not valid if it's from an <input type='number'> but from a text or hidden input, it is just text (although I believe the actual data in most form controls is actually a string not a number).
"The input can take any number but the most common values will be in increments of 0.05. Is there a work-around for this? A solution using JavaScript is also more than welcome."
You can change any attribute you want on any tag AFAIK. Programatically the syntax is simple with Plain JavaScript:
Object.property = "string"
Object: a referenced <element> tag
property: when you reference an standard attribute like a property it's becomes a property.
string: the value must be a string
Here's a basic way of changing a standard attribute programmatically:
var obj = document.querySelector('a');
obj.href = "https://google.com"; //
The following Demo uses:
Document.Forms
HTMLFormElement.elements
HTMLFormControlsCollection
Dot Notation
Demo
Demo can send to a live test server the response is sent to an iframe to view
var ui = document.forms.ui;
var tx = document.forms.tx;
var u = ui.elements;
var x = tx.elements;
var D = u.digit;
var C = x.cache;
var lo = u.min;
var hi = u.max;
var inc = u.step; // I think this what you specificly
var t = u.type;
var chg = u.change;
chg.onclick = chgAttr;
tx.onsubmit = cacheVal;
function chgAttr(e) {
D.min = lo.value;
D.max = hi.value;
D.step = inc.value;
D.type = t.value;
}
function cacheVal(e) {
C.value = D.value;
return true;
}
body {
font: 400 16px/1.5 'Consolas'
}
#digit {
margin-right: 15px;
}
input,
output,
button,
select,
option,
label {
display: inline-block;
font: inherit
}
select {
padding: 3px 5px
}
[type='submit'] {
float: right;
}
<!doctype html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<style></style>
</head>
<body>
<form id='ui' oninput='out.value = digit.value'>
<fieldset>
<legend>Click Button to Change Input</legend>
<input id='digit' min='' max='' step='' type='number'>
<button id='change' type='button'>CHANGE</button>
<output id='out' for='digit'></output>
</fieldset>
<fieldset>
<legend>Attribute Adjustments</legend>
<input id='min' min='-2147483648' max='2147483648' type='number' placeholder='min'>
<input id='max' min='-2147483648' max='2147483648' type='number' placeholder='max'>
<input id='step' type='number' placeholder='step'>
<label for='type'>Type:
<select id='type'>
<option>number</option>
<option>text</option>
<option>range</option>
<option>hidden</option>
<option>color</option>
<option>time</option>
</select>
</label>
</fieldset>
</form>
<form id='tx' action='https://httpbin.org/post' method='post' target='response'>
<input id='cache' name='cache' type='hidden'>
<input type='submit'>
</form>
<iframe src='about:blank' name='response'></iframe>
<script></script>
</body>
</html>
Very new to JavaScript/HTML, help!
I have 2 text boxes and a submit button. I am trying to retrieve the data from each of them using JavaScript and for the time being, simply put them into an alert box.
However, on clicking the button, the alert just reads 'undefined', help!
Here's a code snippet:
function submitApp() {
var authValue = document.getElementsByName("appAuthor").value;
var titleValue = document.getElementsByName("appTitle").value;
alert(authValue);
}
<input type="text" name="appAuthor" size="" maxlength="30" />
<input type="text" name="appTitle" maxlength="30" />
<input type="button" value="Submit my Application!" onclick="submitApp()" />
getElementsByName() returns a list. So you can grab the first item in the list:
document.getElementsByName("appAuthor")[0].value
.getElementsByName() method returns an array-like node list, so you'll need to specify an index in order to retrieve a specific input's value (because the value property only applies to DOM elements, not an entire list).
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
Just add this jQuery to a document.ready section like this:
$(document).ready(function() {
$('#submit').on('submit', function(e) {
e.preventDefault();
submitApp();
});
function submitApp() {
var authValue = document.getElementsByName("appAuthor")[0].value;
var titleValue = document.getElementsByName("appTitle")[0].value;
alert(authValue);
}
});
<input type="submit" id="submit" value="Submit my Application!">
If you want to submit the form remove the e.preventDefault();, but if you just want the value updated keep it in there to prevent form submition.
You could potentially change the button type into a submit-type and do something like this:
$('body').find('form').on('submit', function(e){
e.preventDefault();
var authValue = $('input[name="appAuthor"]').val();
var titleValue = $('input[name="appTitle"]').val();
//...here do whatever you like with that information
//Below empty the input
$('input').val('');
})
Or just interpret the form as an array to make your life easier and clean the code up.
When you use getElementsByName or getElementsByClassName, it returns array of elements, so you should put index to access each element.
authValue = document.getElementsByName("appAuthor")[0].value;
I am new to HTML forms and I was wondering how I can easily (or not) change it's input to a JavaScript variable. Here is my code:
<head>
<title>Begin</title>
<link type="text/css" rel="stylesheet" href="begin.css"/>
</head>
<body>
<form action="begin-create-done.html" method="get">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
<br>
New Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pass">
<br>
Repeat Password: <input type="password" name="rpass">
<input type="submit" value="Submit">
</form>
</body>
</html>
I want each part of the form (e.x. First Name, Last Name, New Username, etc.) to be it's own JavaScript variable. Thank you very much!
Accessing HTML input elements from JavaScript
Assuming you don't have other elements with same names, you can access input values from JavaScript by name as follows:
var firstName = document.getElementsByName("firstname")[0].value;
You now have the value from firstname field in JavaScript variable called firstName. Just keep repeating and you got the other input fields too. You can then proceed and wrap these statements to a function and call it when input data changes. For example:
function formChanged() {
var firstName = ...
var lastName = ...
}
Now register this function call to change / keyup events and you have a function that monitors changing form values:
<input type="text" name="firstname" onkeyup="formChanged()" onchange="formChanged()"/>
Should you prefer a more structured approach, or if you have more than one form on the page, you could:
Create an object that will hold all form values and update them. After that you could simply access them with formValues.inputName.
Store your default values in an array (in the same order as your inputs).
Execute a function that will take care of outputting the default values & updating the object when the values are changed. It takes the form (selected by Id, Class, whatever) and an array of default values as parameters.
// create the object that will hold the input values
var formValues = {};
// store code in the function for a more 'modular' approach
function inputObj(formNR, defaultValues) { // where defaultValues is an array
var inputs = formNR.getElementsByTagName('input');
for ( var i = 0; i < inputs.length; i++) {
if(inputs[i].type === 'text' || inputs[i].type === 'password') {
formValues[inputs[i].name] = defaultValues[i]; // store default in object
}
inputs[i].value = defaultValues[i]; // output default in input
inputs[i].addEventListener('keyup', function() { // update object on change
formValues[this.name] = this.value;
}, false);
}
}
// build a little array with the defaultValues for each input
var defValues =['defaultFirstName','defaultLastName','defaultUser',
'defaultPass','defaultPass'];
// this will push all inputs from the given form in the formValues object.
inputObj(document.forms[0], defValues);
// Access the values like this, eg.
console.log(formValues.firstname); // will return 'defaultFirstName'
See it in action here. Or with CodeView. Note: The code in the example has some additions to show the object's values on the page.
Try to first create a function that grabs the value from the input field:
<script>
function XX()
{
var first2 = document.getElementById("firstname").value;
}
</script>
Then you have to fire it up when the input changes with onchange:
FirstName: <input type="text" id="firstname" name="firstname" onchange="XX()">
I have this input field in html:
<input id="title" type="text" class="" />
A button will allow the user to randomize the value of the input field by calling a js function.
var title = document.getElementById("title");
title.removeAttribute("value");
title.setAttribute("value",random_name);
If the user wants to change the value auto-asigned by my function (aka random_name), he can simply type something else in the input field.
All works fine until now, however if the user changes his mind and clicks the randomize button again, the function is called and "value" attribute is modified, but the user still sees the last thing he typed and not the new random value.
Is there a way to fix this or maybe a workaround?
Just do title.value = random_name
You can set an input's value by element.value = "desired_value". If you use that, it works.
http://jsfiddle.net/f4gVR/2/
<input id="title" type="text" class="" />
<input type="button" class="" onclick="randomValue()" value="Random" />
function randomValue() {
var title = document.getElementById("title");
title.value = Math.random(); // assign random_name to title.value here
}
if it's your random_name bugging out, you should post the code. Try this first. Just replace Math.random() with random_name.
you need to use title.value = random_name; instead of title.setAttribute("value",random_name);
Fiddle: http://jsfiddle.net/4dhKa/