I can't seem to make this work. Beginer here. I want to display in the console the values of first and last name. html
`<form id="form1" onsubmit="getFormValue()">
First name: <input type="text" name="fname" value="David" /><br />
Last name: <input type="text" name="lname" value="Beckham" /><br />
<input type="submit" value="Submit" />
</form>``
Js
`function getFormValue() {
const firstName = document.getElementsByName("fname").value;
const lastName = document.getElementsByName("lname").value;
console.log(firstName lastName);
}`
Nothing apears in the Console. Thank you
CodePudding user response:
A better approach would be to add an event handler rather than using an inline function. There are enough resources to guide you on that so I will not address it here. The answer below addresses your specific question.
To start with you need to pass the event
and the prevent the browser executing the form submit by using the preventDefault
function. You should also use getElementById
rather than getElementsByName
. getElementsByName
returns a NodeList
instead of the element itself.
I have added a working example below. I do not recommend the approach, however I am adding it as a minimal working example to answer your question.
<html>
<body>
<form id="form1" onsubmit="getFormValue(event)">
First name: <input type="text" id="fname" name="fname" value="David" /><br />
Last name: <input type="text" id="lname" name="lname" value="Beckham" /><br />
<input type="submit" value="Submit" />
</form>
<script>
function getFormValue(e) {
e.preventDefault();
const firstName = document.getElementById("fname").value;
const lastName = document.getElementById("lname").value;
console.log(firstName lastName);
}
</script>
</body>
CodePudding user response:
Check the following code
function getFormValue(ev) {
// DISABLE DEFAULT FORM SUBMIT ACTION
ev.preventDefault();
// PICK THE FORM REFERENCE
const form = document.getElementById('form1');
// GET ALL ELMENTS LIKE INPUT AND SELECT, YOU CAN ADD MANY MORE
const allInputs = form.querySelectorAll('input,select');
let formObj = {};
// GET THE VALUES OF EACH FIELD
allInputs.forEach(e => {
// ALL KEY DEPENDS ON THE NAME IN THE ELEMENT
const key = e.getAttribute('name');
if(key){
formObj[key] = e.value;
}
});
console.log(formObj);
}