Test

Getting HTML form values

How can I get the value of an HTML form to pass to JavaScript? Is this correct? My script takes two arguments one from textbox, one from the dropdown box.

  Credit Card Validation:  
Card Type:

@laurentngu the question is does he mean «a value of an HTML form», meaning one value out of the many values, or does he mean the «value of the entire HTML form», meaning all of the values in one big «serialized» value

Node that while in 2010 the answer here was fairly involved, ever since Object.entries landed in JS, stackoverflow.com/a/66407161/740553 has been the real answer to the «getting all form values» interpretation of this question.

19 Answers 19

var nameValue = document.getElementById("uniqueID").value; 

@shorty876: Did you test it yourself? o_0 That would be a pretty good way of determining whether or not you did it right.

Yeah, but it just returns a true/false and im not sure how to determine if the function was even called. Thus you can help.

@bluejayke there are other javascript methods that get data from HTML tags, such as getElementsByClassName . «name» is just a generic attribute placeholder in this case.

If you want to retrieve the form values (such as those that would be sent using an HTTP POST) you can use:

function getData(form) < var formData = new FormData(form); // iterate through entries. for (var pair of formData.entries()) < console.log(pair[0] + ": " + pair[1]); >// . or output as an object console.log(Object.fromEntries(formData)); > document.getElementById("myForm").addEventListener("submit", function (e) < e.preventDefault(); getData(e.target); >); 

Alternatively you could use the below less recommended options:

Читайте также:  Программа обучения языку python

Your first example FormData itself doesn’t do anything.. you still need to get the values from the form.

I believe that is incorrect. If when initialising the FormData you specify a form element then it will correctly retrieve the values. codepen.io/kevinfarrugia/pen/Wommgd

The FormData object is not itself the values though. You still need to call and iterate through FormData.entries() in order to retrieve the values. Additionally, FormData.entries() is not available in Safari, Explorer, or Edge. developer.mozilla.org/en-US/docs/Web/API/FormData

Correct in regards to browser compatibility, however there are polyfills. Regarding iterating through formData.entries() , it depends what you are looking for. If you are looking for the value of a single field you could use formData.get(name) . Reference: get().

This is the answer I came here for. The question of the post is ‘Getting HTML form values’- values being plural. The current top answer only grabs a single input value, I want to know how to grab the entire form and then parse out the values. This should be the top answer.

I think this is the most elegant solution

@Radek Example: const loginForm = document.getElementById(«login-form»); loginForm.addEventListener(«submit», handleSubmit);

@DedaDev depends what you mean by a «thing» it is valid to have inputs with the same name e.g. for checkboxes and I would expect these to be collected as an array instead of just returning the last field with that name. I think perhaps the example I posted using [] is more of an old PHP convention but doesn’t really change the point. stackoverflow.com/questions/452066/…

Here is an example from W3Schools:

function myFunction() < var elements = document.getElementById("myForm").elements; var obj =<>; for(var i = 0 ; i < elements.length ; i++)< var item = elements.item(i); obj[item.name] = item.value; >document.getElementById("demo").innerHTML = JSON.stringify(obj); > 

Just a warning, if anyone wants to get the selected values of other types of inputs such as radio buttons or checkboxes, this won’t do what you want.

@bluejayke The code will cycle through all of the radio button inputs, and will save the ‘value’ of the LAST radio button against obj , regardless of which one is selected. The issue is demonstrated here (choose ‘Option 1’) w3schools.com/code/tryit.asp?filename=GEZXJXBBI7AW

document.forms will contain an array of forms on your page. You can loop through these forms to find the specific form you desire.

var form = false; var length = document.forms.length; for(var i = 0; i < length; i++) < if(form.id == "wanted_id") < form = document.forms[i]; >> 

Each form has an elements array which you can then loop through to find the data that you want. You should also be able to access them by name

var wanted_value = form.someFieldName.value; jsFunction(wanted_value); 

@ArturKlesun I would guess it’s because at the time a decade ago I started to type the answer, the OP hadn’t updated, so I wrote the for loop to handle most situations. I think back then I was also ensuring browser compatibility with IE7 because we didn’t have the far better landscape we have today.

Let us assume we want to retrieve the input of name formula . This can be done by passing the event in the onsubmit field. We can then use FormData to retrieve the values of this exact form by referencing the SubmitEvent object.

The JavaScript code above will then print the value of the input to the console.

If you want to iterate the values, i.e., get all the values, then see https://developer.mozilla.org/en-US/docs/Web/API/FormData#Methods

My 5 cents here, using form.elements which allows you to query each field by it’s name , not only by iteration:

const form = document.querySelector('form[name="valform"]'); const ccValidation = form.elements['cctextbox'].value; const ccType = form.elements['cardtype'].value; 

I should note that, the element name is case sensitive. form.elements[‘cardtype’].value and form.elements[‘CardType’].value aren’t the same.

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector))) console.log('Output of getFormData:') console.log(getFormData('#myTargetForm'))

Get Form Data as Javascript Object

Define this function in your Javascript:

getFormData = (selector) => Object.fromEntries(new FormData(document.querySelector(selector))) 

Then just call with any selector e.g.: getFormData(‘#myTargetForm’)

Expanding on Atrur Klesun’s idea. you can just access it by its name if you use getElementById to reach the form. In one line:

document.getElementById('form_id').elements['select_name'].value; 

I used it like so for radio buttons and worked fine. I guess it’s the same here.

This is the answer of your question.

You can pass the values of the form fields to the function by using this.>.value .

And also changed input submit to button submit. Called the function from form.

  Credit Card Validation:  
Card Type:
const element = document.getElementByID('#form') const data = new FormData(element) const form = Array.from(data.entries()) /* form = [ ["title", "a"] ["text", "b"] ["email", "c"] ] */ for (const [name, value] of form) < console.log(< name, value >) /*   */ > 

Please try to change the code as below:

 
< e.preventDefault(); e.stopPropagation(); const elements = Array.from(e.currentTarget); const state = elements.reduce((acc, el) => < if (el.name) < acc[el.name] = el.value; >return acc; >, <>); console.log(state); // >> >

Several easy-to-use form serializers with good documentation.

It’s easy with one for-of loop you can get all field values even checkboxes values also.

In your HTML you should bind a handlSubmit() on your forms onsubmit event

in your javascript your code should apply the following logic no matter what name your assigned to your fields.

const handleSubmit = (event)=> < event.preventDefault(); const formData = new FormData(event.target); formObj = <>; for (const [fieldName] of formData) < const fieldValue = formData.getAll(fieldName); formObj[fieldName] = fieldValue.length == 1 ? fieldValue.toString() : fieldValue >console.log('formObj',formObj) > 

Quick solution to serialize a form without any libraries

function serializeIt(form) < return ( Array.apply(0, form.elements).map(x =>( (obj => ( x.type == "radio" || x.type == "checkbox" ) ? x.checked ? obj : null : obj )( < [x.name]:x.value >) ) ).filter(x => x) ); > function whenSubmitted(e)

Some answers above didn’t cater for forms with multiple fields with the same name e.g.multiple so I made this quickly. It expects field with the same name that you want to collect as an array to end in [] as a convention but could be updated to handle other scenarios.

function getFormValues(form) < const formData = new FormData(form); return Array.from(formData.entries()).reduce((prev, [inputName, val]) =>< return < . prev, [inputName]: inputName.endsWith('[]') ? prev[inputName] ? [. prev[inputName], val] : [val] : val, >; >, <>); > // alternative if you don't like reducers and nested ternary statements function getFormValues(form) < const formData = new FormData(form); const values = <>; for (const [inputName, val] of formData.entries()) < if (inputName.endsWith('[]')) < values[inputName] = values[inputName] ? [. values[inputName], val] : [val]; >else < values[inputName] = val; >> return values; > // then attach this to form submit function onSubmit(e) < e.preventDefault(); const values = getFormValues(e.target); // etc. >

values gives something like

Источник

Passing a form value to a JavaScript Function

I have read through lots of postings here and around the net, and I even have books covering this subjective, but I just can’t get it to work. I just can’t get the Function to pick up the value of the «RadioDrink» variable. I have tried all sorts of combinations Using DOM methods like below and here using a collection (this) and (form) with no luck. Any help would be appreciated.

      Tea 
Coffee
Soup
Milk Sugar

6 Answers 6

This will give the value of «Soup» checkbox:

document.forms["Drinks"]["RadioDrink"][0].checked 

you need to do this in a different way. first of all your DOM is showing undefined value. you can add different ids to the radio buttons. you can do it like below

       Tea 
Coffee
Soup
Milk Sugar
document.forms.Drinks.RadioDrink 

returns an array-like reference to all three inputs with that name, it doesn’t return a reference to the currently selected one. So you can’t just test the value property.

The easiest to explain way to achieve what you want to do is to give the radio buttons unique ids:

And then directly select the one you want to test:

if (document.getElementById("RadioDrinkSoup").checked) < alert("It's soup OK!"); return true; // soup >else < alert("OK"); return false; // not soup >

Источник

Input text form value from HTML into Javascript function

Beginner question, I am currently learning JS and I’m trying to write a function that will take a text input from a simple html form. I can’t figure out how to pass the text input into the function. This is what I am currently trying:

4 Answers 4

 var myColor = document.getElementById("textbox").value; 

Inside the findColor function:

I’m with David’s answer. You are using a form and you need to prevent default submission event like below by pasing a event parameter to the function as shown in the below code.

function findColor(e) < // e is a event parameter passed e.preventDefault(); var myColor = document.getElementById("textbox").value; switch(myColor)< case "Blue": document.write("just like the sky!"); break case "Red": document.write("Just like wine!"); break default: document.write("Suit yourself then. "); >return false; > 

As you can see I’m passing event like this findColor(event) in html

read about the document.write here and see a demo here the author explained it very neatly as

The use of document.write where native DOM alternatives such as document.createElement are more appropriate. document.write has been grossly misused over the years and has quite a few disadvantages including that if it’s executed after the page has been loaded it can actually overwrite the page we’re on, whilst document.createElement does not. We can see here for a live example of this in action. It also doesn’t work with XHTML which is another reason opting for more DOM-friendly methods such as document.createElement is favorable.

Or to pass it to the function do this:

 function findColor(myColor) < switch(myColor)< case "Blue": document.write("just like the sky!"); break case "Red": document.write("Just like wine!"); break default: document.write("Suit yourself then. "); >> 

This would work, its an example of how to pass something to a function, which was the question. Its an alternative to the other answers with the intention of helping a JavaScript beginner.

not trying to ruffle your feathers 🙂 I changed it from would to could work as I wasnt sure about hardcoding the onclick value. If I was going to post this sample I would do it as onclick=»findColor(document.getElementById(‘textbox’).value);» so it worked based on the input. But also I wouldn’t use onclick at all . But also I would use jquery so that will probably upset people anyway haha

No worries, your way is better, and Andrews is even better, it was just a simply example of how to pass data to a function. Jquery is deffo better

when the browser reads your html page it interprets the javascript section thus defining your findColor function and executing the line

var myColor = document.getElementById("textbox").value; 

Therefor myColor receives the initial value of your textbox element. By the time the page is fully loaded and you enter a value in the textbox the myColor assignment is already done. To make sure that the assignment is done at the right time, after clicking submit, aka when the findColor functiom is called, you have the two options mentioned above: Make the assignemt the first statement in your findColor function OR make it a parameter to the findColor function

There is a second flaw in this example. A form’s submit triggers reloading of an HTML page. Therefore you never see the result of your findColor function. A better way to play with Javascript is to tie functions to buttons. See the revised html below.

    
Colour
what I think of this color

Источник

Оцените статью