Button click not logging object output to console in Vue [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 27 days ago.
Improve this question
I'm pretty new to Vue. I am trying to see the output of a function in the console before emitting it to the parent component. But the function doesn't output anything to the console.
Here's my code
AddTask.vue
template>
<form #submit.prevent="onSubmit" class="add-form">
<div class="form-control">
<label>Task</label>
<input type="text" v-model="text" name="text" placeholder="Add Task" />
</div>
<div class="form-control">
<label>Day & Time</label>
<input
type="text"
v-model="day"
name="day"
placeholder="Add Day & Time"
/>
</div>
<div class="form-control form-control-check">
<label>Set Reminder</label>
<input type="checkbox" v-model="reminder" name="reminder" />
</div>
<input type="submit" value="Save Task" class="btn btn-block" />
</form>
</template>
<script>
export default{
name: 'AddTask',
data() {
return {
text: '',
day: '',
reminder: false,
}
},
method: {
onSubmit(e){
e.preventDefault()
if (!this.text) {
alert('Please add a task')
return
}
const newTask = {
id: Math.floor(Math.random() * 100000),
text: this.text,
day: this.day,
reminder: this.reminder,
}
console.log(newTask)
//this.$emit('add-task', newTask)
this.text = ''
this.day = ''
this.reminder = false
}
}
}
</script>
<style scoped>
.add-form {
margin-bottom: 40px;
}
.form-control {
margin: 20px 0;
}
.form-control label {
display: block;
}
.form-control input {
width: 100%;
height: 40px;
margin: 5px;
padding: 3px 7px;
font-size: 17px;
}
.form-control-check {
display: flex;
align-items: center;
justify-content: space-between;
}
.form-control-check label {
flex: 1;
}
.form-control-check input {
flex: 2;
height: 20px;
}
</style>
Please can someone help me figure out what is not right in this code snippet, I would really appreciate.

Just as Rob Louie spotted in the comment, the 's' was missing from the methods. So the code snippet for that segment becomes
<script>
export default{
name: 'AddTask',
data() {
return {
text: '',
day: '',
reminder: false,
}
},
methods: {
onSubmit(e){
e.preventDefault()
if (!this.text) {
alert('Please add a task')
return
}
const newTask = {
id: Math.floor(Math.random() * 100000),
text: this.text,
day: this.day,
reminder: this.reminder,
}
console.log(newTask)
//this.$emit('add-task', newTask)
this.text = ''
this.day = ''
this.reminder = false
}
}
}
</script>

Related

Is there a good way to have it so that when someone clicks a button, say option 3 on a scale of 1-5, that it would change the color of buttons 1-3?

I am coding a survey page for a client and they want it so that if someone selects "3" out of a 5 button question scale that buttons 1-3 have a green backgroun...4 would have 1-4, etc.
Currently, if you click a button from the number scale only the one you click is highlighted green. What I want to have is so that it changes the background color of all buttons leading up to the one clicked (If you click 2 then it would change the 1 and 2 buttons to green).
Any help appreciated
Main code for the survey here (1 button example- the rest follow the same format):
<section class="l-reviews pt-30 pb-15">
<div class="contain">
<div class="row">
<div class="col-md-12">
<div class="reviews-wrapper">
<div class="reviews-top-header">
<p id="">Thank you for taking part. Please complete this survey to let us know how we’re
doing.</p>
<p>Please rate the following on a 1-5 scale (1 = Least, 5 = Most)</p>
</div>
<div class="reviews-body">
<form method='post' name='front_end' action="">
<div class="form-control">
<p>1. Were the payroll process and benefits options explained to you fully?</p>
<div class="input-holder">
<input type='hidden' name='title' value='' />
<input type='hidden' name='email' value='' />
<input type="radio" data='Unsatisfied' name='satisfaction' value='20' id='sat-1' /><label for="sat-1"></label>
<input type="radio" data='Not Very Satisfied' name='satisfaction' value='40' id='sat-2' /><label for="sat-2"></label>
<input type="radio" data='Neutral' name='satisfaction' value='60' id='sat-3' /><label for="sat-3"></label>
<input type="radio" data='Satisfied' name='satisfaction' value='80' id='sat-4' /><label for="sat-4"></label>
<input type="radio" data='Highly Satisfied' name='satisfaction' value='100' id='sat-5' /><label for="sat-5"></label>
<div class="error">
<p>Please select at least one option.</p>
</div>
</div>
</div>
<button type="button" class="send-btn">Submit</button>
<input type="hidden" name="action" value="review" />
</form>
<div class='success-form'>
<h3>Your review was submitted successfully</h3>
</div>
</div>
CSS for one button:
input[type=radio]:not(.regular-radio) {
display: none;
}
#wr-1+label,
#application-rating-1+label,
#goals-rating-1+label,
#refer-rating-1+label,
#sat-1+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/button-1.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
#wr-1:checked+label,
#application-rating-1:checked+label,
#goals-rating-1:checked+label,
#refer-rating-1:checked+label,
#sat-1:checked+label {
background: url('/wp-content/themes/theme52950/images/reviews-faces/1-hover.png');
height: 55px;
width: 109px;
display: inline-block;
padding: 0 0 0 0px;
background-repeat: no-repeat;
}
JavaScript:
<script>
$(document).ready(function() {
console.log(emailsArray);
$('input[type=radio]').click(function() {
avgOne = parseInt($('input[name=satisfaction]:checked').val());
avgTwo = parseInt($('input[name=working_rating]:checked').val());
avgThree = parseInt($('input[name=application_rating]:checked').val())
avgFour = parseInt($('input[name=goals_rating]:checked').val())
avgFive = parseInt($('input[name=refer_rating]:checked').val())
avgOfAll = ((avgOne + avgTwo + avgThree + avgFour + avgFive) / 5);
if (avgOfAll < 80) {
$('.addtl-comments').show();
} else {
$('.addtl-comments').hide();
}
})
if (checkOne && checkTwo && checkThree && checkFour && checkFive && addtlComments && checkEmailExist && emailNotDupe) {
$('.reviews-body form').submit();
const portalId = '3112753';
const formId = '23212b77-0a27-4833-93a9-766bdf8c3a9b';
const url = 'https://api.hsforms.com/submissions/v3/integration/submit/' + portalId + '/' + formId;
const body = {
context: {
pageUri: window.location.href,
pageName: $(document).find("title").text()
},
fields: [{
name: 'email',
value: getUrlParameter('email')
}, {
name: 'how_satisfied_are_you_with_the_overall_experience_in_working_with_',
value: document.querySelector('input[name="satisfaction"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_working_with_your_recruiter_',
value: document.querySelector('input[name="working_rating"]:checked').getAttribute('data')
}, {
name: 'how_would_you_rate_the_application_process_',
value: document.querySelector('input[name="application_rating"]:checked').getAttribute('data')
}, {
name: 'how_satisfied_were_you_with_communication_throughout_your_interview_process_',
value: document.querySelector('input[name="goals_rating"]:checked').getAttribute('data')
}, {
name: 'how_likely_would_you_be_to_recommend_to_other_candidates_',
value: document.querySelector('input[name="refer_rating"]:checked').getAttribute('data')
}]
};
Any help appreciated.
A minimal reproducable example would have been sufficient. Just for fun: here's an idea for you:
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.scoreid) {
const score = +evt.target.dataset.scoreid;
const stars = document.querySelectorAll(`[data-scoreid]`)
.forEach((el, i) =>
el.classList[i <= score ? `add` : `remove`](`starred`));
const rateEl = evt.target.closest(`#rate`);
rateEl.classList.remove(`single`, `score`);
rateEl.classList.add(score + 1 === 1 ? `single` : `scored`);
rateEl.dataset.score = score + 1;
}
}
document.body.insertAdjacentHTML(
`beforeEnd`,
`<div id="rate" date-score="0" data-single="0">
${[...Array(5)].map((v, i) => `<span data-scoreid="${i}"></span>`)
.join(``)}
</div>`);
#rate {
font-size: 2rem;
}
#rate.scored:after {
content: 'you scored 'attr(data-score)' stars' ;
color: green;
}
#rate.single:after {
content: 'you scored 'attr(data-score)' star' ;
color: green;
}
#rate span {
cursor: pointer;
}
#rate span:before {
content: '\2606'
}
#rate span.starred:before {
content: '\2605';
color: green;
}

Add new element to an array of objects and show in HTML

I have an array of objects that is going to be filled with new objects from filling a form and calling addEventListener on submit.
I tried to push the new object inside the event listener but looks that it's only working inside the scope of the function.
Is there another way to add this new object into the array?
Here is my code:
const empleados = [{
nombre: "Kevin",
apellido: "Malone",
edad: 30,
},
{
nombre: "Pam",
apellido: "Beesley",
edad: 69,
},
{
nombre: "Jim",
apellido: "Halpert",
edad: 40,
},
];
const form = document.querySelector("form");
const table = document.querySelector(".table");
form.addEventListener("submit", (e) => {
e.preventDefault();
let nuevoEmpleado = {
nombre: form.name.value,
apellido: form.lastname.value,
edad: form.age.value,
};
empleados.push(nuevoEmpleado);
form.reset();
});
empleados.forEach((chabon) => {
let html = `<div class="table">
<div class="empleado"><span class="name">Nombre: ${chabon.nombre}</span> <span class="apellido">Apellido: ${chabon.apellido}</span> <span class="edad">Edad: ${chabon.edad}</span></div>
</div>`;
table.innerHTML += html;
});
form {
display: flex;
flex-direction: column;
}
button {
width: 30%;
}
.table {
display: flex;
flex-direction: column;
border: 1px solid purple;
}
<div>
<form action="">
<span>Nombre</span><input type="text" class="name" name="name">
<span>Apellido</span><input type="text" class="lastname" name="lastname">
<span>Edad</span><input type="text" class="age" name="age">
<button>Agregar</button>
</form>
<div class="table">
<div class="empleado"><span class="name"></span><span class="edad"></span></div>
</div>
</div>
Actually, your current function IS pushing the new object (nuevoEmpleado) to the array, you are only not seeing it because you are not updating the DOM/HTML or not even logging the array afte pushing new objects.
So, create a function that prints the empleados to your table. Call this function on initialization and every time that a new empleado is added.
See below code, and the comments inside it
const empleados = [{
nombre: "Kevin",
apellido: "Malone",
edad: 30,
},
{
nombre: "Pam",
apellido: "Beesley",
edad: 69,
},
{
nombre: "Jim",
apellido: "Halpert",
edad: 40,
},
];
const form = document.querySelector("form");
const table = document.querySelector(".table");
form.addEventListener("submit", (e) => {
e.preventDefault();
let nuevoEmpleado = {
nombre: form.name.value,
apellido: form.lastname.value,
edad: form.age.value,
};
empleados.push(nuevoEmpleado);
form.reset();
//"re-print" the empleados, calling the function that does it
printEmpleados();
});
//HERE: new function that "prints" the empleados to the table
printEmpleados = function() {
//clear the table HTML before fill it again
table.innerHTML = "";
empleados.forEach((chabon) => {
let html = `<div class="table">
<div class="empleado"><span class="name">Nombre: ${chabon.nombre}</span> <span class="apellido">Apellido: ${chabon.apellido}</span> <span class="edad">Edad: ${chabon.edad}</span></div>
</div>`;
table.innerHTML += html;
});
}
//call at startup to start showing
printEmpleados();
form {
display: flex;
flex-direction: column;
}
button {
width: 30%;
}
.table {
display: flex;
flex-direction: column;
border: 1px solid purple;
}
<div>
<form action="">
<span>Nombre</span><input type="text" class="name" name="name">
<span>Apellido</span><input type="text" class="lastname" name="lastname">
<span>Edad</span><input type="text" class="age" name="age">
<button>Agregar</button>
</form>
<div class="table">
<div class="empleado"><span class="name"></span><span class="edad"></span></div>
</div>
</div>
Your problem is not that there is no update in the array, because it clearly works.
Just add console.log(empleados); right after empleados.push(nuevoEmpleado);
Your problem is that you do not see any update in your HTML. And that's because you don't update the table after that.

How to call a function when textfield value change in Javascript?

I want to change width of a textfield when user enters more than 17 characters in that textfield using Javascript (if possible) otherwise by any other means.
I wrote a code to do the same, but it only changes width when user click outside the textfield after entering more than 17 characters. I want it to change width automatically when user enters more than 17 characters :
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onchange="widen()" value="" required>
</form>
onchange gets activated when the input looses focus, that's why it works when you click outside. On the other hand oninput will be triggered immediately when the value changes:
const nametf = document.getElementById('nametf');
function widen() {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<html>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" oninput="widen()" value="" required>
</form>
</html>
You need to pass a self-reference to the function using this. I would also change on-change to on-key-up, because on-change waits for you to move focus away from the field.
onkeyup="widen(this)"
Then you need to parameterize the function with your variable "nametf"
function widen(nametf) {
// ...
}
Example
function widen(nametf) {
var value = nametf.value;
if (value.length > 17) {
nametf.style.width = '300px';
} else {
nametf.style.width = '200px';
}
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" onkeyup="widen(this)" value="" required>
</form>
A better approach would be to use em units to expand the text are based on the current value.
initExpandingFields();
function initExpandingFields() {
Array.from(document.querySelectorAll('.expanding-field')).forEach(field => {
field.addEventListener('keyup', onFieldChange);
});
}
function onFieldChange(e) {
let field = e.target,
len = field.value.length;
field.style.width = (len * 0.667) + 'em';
}
#nametf {
width: 200px;
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" class="expanding-field" name="name1" id="nametf" value="" required>
</form>
Try this:
var nametf = document.getElementById("nametf");
nametf.addEventListener("input", function(){
if(nametf.value.length > 17) {
nametf.size = "30";
} else {
nametf.size = "20";
}
});
#nametf {
height: 20px;
padding: 5px 10px;
}
<title>TEXTFIELD TEST</title>
<form method="get" action="wwhome.php">
<input type="text" name="name1" id="nametf" size="20" value="" required>
</form>

Using Checkboxes to contol an Input.value (With an annoying twist.)

I've been researching for a few days methods of controlling UI with checkboxes and with the help of some members on Stack' I've come really quite far. But my balding doesn't quite stop yet. I've been trying to further tweak my code snippet, by including a numeric value alongside my UI controller. (This value will be of use later inside the web-java applet.)
For example, when a checkbox is checked var total is ammended from 0 to 30. If a Checkbox is unchecked the value returns to '0'.
(Main Build JS Fiddle),
(Checkbox Example).
The second fiddle allows the use of data attributes, however these will need to be injected into the HTML via, JS. As like before I have 'NO' access to the CSS or HTML source files.
(Original Post)
- This post is a follow on from another question asked here on stack, due to the nature of the question changing, and the comments getting fairly confusing I was asked to open a new thread.
Below I'll post two snippets, one is of the original build, built with the aid of user #acontell. The other is an example of the type of result I am after, built with the aid of, user #Rajesh. Link to (Example Source).
The Base Build
// Control UI...
(function(domElements, cbState) {
// Number increment
var total = 0 + ' mm';
document.getElementById('adjvar').value = total;
function clickCallback() {
toggleElements(this.className);
}
function toggleElements(className, initialShow) {
var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
checkBox = document.getElementById('checkboxopt' + checkNumber),
division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;
division.style.display = isShown ? 'block' : 'none';
checkBox.checked = isShown;
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// increment count...
var val = 30;
total += (+val * (checkBox.checked ? 1 : -1));
document.getElementById('adjvar').value = total + ' mm';
document.getElementsByClassName('adjvar').value = checkBox.checked ? val : 0 + ' mm';
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
}
domElements
.filter(function(el) {
return el.className.indexOf('editoropt') !== -1;
})
.forEach(function(el, index) {
el.addEventListener('click', clickCallback, false);
toggleElements(el.className, cbState[index]);
});
})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
// inject style
function ctSe() {
var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.log(head)
console.log(style)
console.log(css)
};
ctSe();
.editoraccvar {
width: 300px;
background: #f0f;
padding: .5em;
}
.editoropt {
width: 300px;
background: #0f0;
padding: .5em;
}
.editoraccvar1 {
width: 300px;
background: #0ff;
padding: .5em;
}
.editoropt1 {
width: 300px;
background: #ff0;
padding: .5em;
}
textarea {
display: block;
width: 95%;
resize: none;
padding: .5em;
}
<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field field-summernote editoraccvar ">
<label for="accvar1">Ground Floor Info</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<!-- Secondary Division -->
<div class="seq-box-form-field field-summernote editoraccvar1 ">
<label for="accvar1">First Floor</label>
<div class="clearfix"></div>
<textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
<input type="hidden" name="accvar1" id="accvar1" value="" />
</div>
<!-- Secondary Checkbox -->
<div class="seq-box-form-field editoropt1 ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
<input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<input name="adjvar" id="adjvar" readonly>
The Example
(function() {
var total = 0;
function calculate(index) {
var el = document.getElementsByClassName('checkbox-input')[index];
var val = el.getAttribute("data-value");
total += (+val * (el.checked ? 1 : -1));
document.getElementById('pnvar').value = total;
document.getElementsByClassName('pnvar')[index].value = el.checked ? val : 0;
}
function registerEvents() {
var cbs = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(cbs, function(cb, i) {
cb.addEventListener("click", function() {
calculate(i);
});
});
document.getElementById('pnvar').addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
})
}
window.addEventListener('load', function() {
registerEvents();
calculate(0)
})
})()
.editoropt {
font-family: Calibri, sans-serif;
width: 160px;
background: #f8f8ff;
padding: .5em;
border: solid 1px #ddd;
}
#checkboxopt {
float: left;
margin-right: 1em;
margin-top: 4px;
}
#checkboxopt1 {
float: left;
margin-right: 1em;
margin-top: 4px;
}
.pnvar {
width: 95%;
}
input:-moz-read-only {
/* For Firefox */
background-color: transparent;
border: none;
border-width: 0px;
}
input:read-only {
background-color: transparent;
border: none;
border-width: 0px;
}
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Default 80mm </span>
<input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" checked />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1">
<span style="padding-right: 10px; vertical-align: 1px;">Add 30mm </span>
<input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true" />
<input type="hidden" name="opt2" id="opt2" value="true" />
</label>
</div>
<div class="editoropt">
<input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text">
<input name="adjvar" class="pnvar" id="adjvar" readonly value="0">
<input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">
</div>
As I mentioned in my previous post, I'm not a JS Whizz and I'm just finding my feet, however I am abitious to learn and further my knowledge. Any assistance would be greatly appreciated.
Note : All tags, classes and names, must remain the same for consistancy with another application.
I might be mistaken but I think that this two lines of code:
// Default Checked...
if (document.getElementById('checkboxopt').checked) {
// do nothing
} else {
document.getElementById('checkboxopt').click();
}
Could be avoided if you passed [true, false] as the initial states of the checkboxes:
([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);
I might be wrong, you might be doing something else or the state of the page could require that click, I don't know.
Going back to the issue, if you want to increase/decrease by 30 when the checkbox is checked/unchecked, you could do as follows:
Create a function that retrieves the value of the input an updates it with a quantity added to it. The value of the input is a string of the form 'x mm' so a bit of tinkering is necessary to get the integer part of the value.
function updateInputValue(n) {
var actual = +document.getElementById('adjvar').value.split(' mm')[0] || 0;
document.getElementById('adjvar').value = (actual + n) + ' mm';
}
Inside toggleElement call this function in order to update the input value.
var increment = isShown ? 30 : -30;
updateInputValue(initialShow === undefined ? increment : +initialShow * 30);
It gets a bit complicated because you have to control the initial state of the inputs, but it's not that hard: if it's the initial state, initialShow is different from undefined so we transform the value (it's a boolean) into a number a multiply it by 30 (when it's checked, it'd be 1 * 30, when it's unchecked it'd be 0 * 30). When it's not the initial state, we increment/decrement depending on whether it's checked or not.
And here's the fiddle (I also commented out the part that clicked the checkbox). Hope it helps.

Javascript TypeError: document.getElementById(...) is null [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here is my html code:
<form name="searchForm" action="javascript:;" method="post" />
<p>
<label for="search">Search the site:</label>
<input type="text" id="search" name="search" value="xhr" />
<input type="submit" value="Search" />
</p>
</form>
In the header, I included my JavaScript file with the following specific code:
window.onload = function () {
getValues = function (id) {
var i, values = [], form = document.getElementById(id);
for (i = 0; i < form.length ;i++) {
values.push( form.elements[i].value );
}
return values;
}
}
I've tried to access the function with console.log(getValues("searchForm") ); but instead in my Firefox console, I received the following error: TypeError: form is null.
Can anyone suggest why this doesn't work?
You're using name attribute's value, not id. So either you need to change name to id or use
form = document.getElementsByName(id)[0];
Also note that if you use the above code, it will return NodeList so you need to use index to get the desired element.
To get all the values of a form:
"use strict";
var findValuesIn = function(form) {
var fields = form.querySelectorAll('input,textarea,select'),
values = {},
i;
for (i in fields) {
values[ fields[i].name ] = fields[i].value;
}
return values;
}
document.getElementById('obtainValues').addEventListener('click',function(){
var ourForm = document.getElementById('f');
var vals = findValuesIn(ourForm);
// debug
document.getElementById('debug').innerHTML = JSON.stringify(vals);
});
input, select, textarea {
float: left;
}
button {
float: left;
clear: both;
margin: 1em;
}
label {
float: left;
clear: left;
width: 10em;
}
output {
display: block;
clear: both;
margin: 1em;
padding: .5em;
border: 1px solid gray;
background-color: #eee;
}
<form name="f" id="f">
<label for="name">Name</label>
<input type="text" name="name" />
<label for="search">Search</label>
<input type="search" name="search" />
<label for="favouriteColour">Favourite Colour</label>
<select name="favouriteColour">
<option>red</option>
<option>blue</option>
<option>yellow</option>
</select>
<button id="obtainValues">obtain values</button>
</form>
<output id="debug" form="f"></output>

Categories

Resources