Get value from input and store it to the object Javascript - javascript

How I can get value from input and store it to the object?
When button is clicked value from the input - should to be stored in the object.
Thank you a lot in advance
var testObject = { 'name': nameOfbook.value,
'author': nameOfauthor.value,
'year': year.value
};
console.log(testObject);
<input type="text" id="nameOfbook" required="" placeholder="Book name" />
<input type="text" id="nameOfauthor" required="" placeholder="Athor name" />
<input type="text" id="year" required="" placeholder="Add year" />
<button id="addder" type="button">StoreEmail</button>

Here's a working JSfiddle for you.
The relevant JS code is here. Using the id tags on your html elements, I got all of the elements and stored them into variables. Next, I added an event listener on your button, and on click, I push the relevant value of each element into your testObject.
var testObject = [];
const button = document.getElementById("addder");
const name = document.getElementById("nameOfbook");
const author = document.getElementById("nameOfauthor");
const year = document.getElementById("year");
button.addEventListener("click", function() {
testObject.push({
name: name.value,
author: author.value,
year: year.value
})
console.log(testObject)
})
https://jsfiddle.net/991jqomq/

Here's how I did it
HTML:
<form id="new-post">
<label for="post-title">Title:</label>
<input id="post-title" type="text" />
<label for="post-body">Body:</label>
<textarea id="post-body"></textarea>
<button>Post</button>
</form>
JS:
document.getElementById("new-post").addEventListener("submit", function(e) {
e.preventDefault()
const postTitle = document.getElementById("post-title").value
const postBody = document.getElementById("post-body").value
const data = {
title: postTitle,
body: postBody
}
console.log(data)
})

Related

Elements not showing up in array after pushing

I want to add books to a library. After entering info to input and submitting the books array stay empty. I'll post pictures so you can understand better. Also sorry for messy code. I'll clean up after getting it to work.
console.log after adding a book
const books = [];
const submitBook = () => {
const bookName = document.querySelector('#title').value;
const bookAuthor = document.querySelector('#author').value;
const bookYear = document.querySelector('#year').value;
// let book = new Book(bookName.value, bookAuthor.value, bookYear.value);
books.push({
'name':bookName,
'author':bookAuthor,
'year':bookYear
});
alert("Book added.");
}
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" required><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author" required><br>
<label for="year">Year:</label><br>
<input type="number" id="year" name="year" required><br>
<button onclick="submitBook()">Add book</button>
Your code seems to work. I've taken the liberty to simplify you code somewhat. It is generally not a good idea to use inline event handling (onclick=... within html), so moved the handler to the code section. Also added a button to show added books.
let books = [];
let to = null;
const clearAfter = (delay = 2) => setTimeout(() => console.clear(), delay * 1000);
const format = obj => JSON.stringify(obj).split("},{").join("},\n{");
const submitBook = () => {
let book = {};
document.querySelectorAll("input")
.forEach(inp => book[inp.name] = inp.value);
books.push(book);
console.clear();
// console.log here to see the result immediately,
// otherwise there may not be any result yet
console.log(`Added:\n${format(book)}`);
}
document.addEventListener("click", evt => {
if (evt.target.id === "addbook") {
submitBook();
} else if (evt.target.id === "showbooks") {
console.clear();
console.log(`${books.length || "No"} added books\n${
books.length < 1 ? "-" : format(books)}`);
}
// remove the log (to make buttons visible again in the SO-run window)
clearTimeout(to);
to = clearAfter();
});
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" required><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author" required><br>
<label for="year">Year:</label><br>
<input type="number" id="year" name="year" required><br>
<p>
<button id="addbook">Add book</button>
<button id="showbooks">Show books added</button>
</p>

Display error message depending on response from backend

I'have a form which has date of birth filed. I want to show error message when I get response back from my php script. My php is script working fine, I'm getting response when there are multiple element as an array. like this.
[{code: 0, message: "Please fill valid date of birth."}, {code: 1, message: ""}]
This is my HTML
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
I want show error message only on the element which has a response 0. At the moment error message showing on all element even some element has response code 1. I want to validate the each field separately and error message should be shown on the element which has code:0.
Here is my JS code
//GET JSON from Validation.php and extract the nodes
var response = xmlhttp.responseText;
var parseJson = JSON.parse(response);
var resultCode = parseJson.code;
var resultMessage = parseJson.message;
console.log(parseJson);
var element = document.getElementById('stepbirth');
element.classList.toggle("disabled", parseJson.some(resp => !resp.code))
//Show Validation Message
parseJson.map(response => {
var items = document.getElementsByClassName("stepbirthVal"),i, len;
for (i = 0, len = items.length; i < len; i++) {
items[i].innerHTML = response.message;
}
});
Till toggle class my code is working fine, only error message is not showing how I want. It should only on a element which has response code 0.
You need a forEach in plain JS
Since the message is empty when it is "1", we should take advantage of that and fill the span with that empty string
const parseJson = [{
code: 0,
message: "Please fill valid date of birth."
}, {
code: 1,
message: "OK" // or blank
}]
const items = document.querySelectorAll(".stepbirthVal");
parseJson.forEach((response, i) => items[i].innerHTML = response.code === 0 ? response.message : "");
// OR just
// parseJson.forEach((response, i) => items[i].innerHTML = response.message);
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
<hr/>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
jQuery:
const parseJson = [{
code: 0,
message: "Please fill valid date of birth."
}, {
code: 1,
message: ""
}]
const $items = $(".stepbirthVal");
$.each(parseJson,(i,response) => $items.eq(i).html(response.message))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span><hr/>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
Based on your html and response structure I'd advise you to iterate over your response and for those with message only use code as array element index. Smth like this:
const respMock = [{
code: 0,
message: "Please fill valid date of birth."
}, {
code: 1,
message: ""
}];
const inputs = $('.date_of_birth');
respMock.forEach(function(resp) {
if (resp.message) {
let errorSpan = $(inputs[resp.code]).next();
errorSpan.text(resp.message);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>
<input class="date_of_birth" name="date[]" type="text" value="" />
<span class="stepbirthVal"></span>

How to place values from html inputs into a javascript array of objects

I have three inputs which will be given by the user and i want these 3 inputs to make up objects in an array in my javascript file, i.e, the values for these 3 inputs will make up each object in thearray, everytime the user inputs the 3 values and clicks enter, a new object with those 3 values as properties should be added into the array. How do i achieve this?
I have tried to get the values, and onclick to push them into the array but i keep get a "Cannot access 'arr_items' before initialization
at addName"
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
let i = 0;
function addValues() {
arr_items[i].name.push(input2.value);
arr_items[i].weight.push(input3.value);
arr_items[i].value.push(input4.value);
i++;
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<button onclick="addValues()" id="name">Enter</button>
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
</div>
I expect everytime the user inputs the 3 values and clicks enter, a new object with those 3 values as properties should be added into the array.
You are trying to call the property name, weight etc on the array element using .. This is wrong. Try do:
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
let i = 0;
function addValues() {
arr_items[i] = {
name: input2.value,
weight: input3.value,
value: input4.value
};
i++;
console.log(arr_items)
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<button onclick="addValues()" id="name">Enter</button>
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
</div>
You were doing it wrongly try this:
const arrayItems = new Array();
function addValues(){
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
let inputs = {
input1 : input2.value,
input3 : input3.value,
input4 : input4.value
}
arrayItems.push(inputs);
console.log(arrayItems);
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" placeholder="enter item name">
<input id="itemWeight" type="number" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" placeholder="enter item value">
<button onclick="addValues()" id="name">Enter</button>
</div>
You can just push to array again and again without counter. Like so:
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
const arr_items = [];
function addValues() {
arr_items.push({name: input2.value, weight: input3.value, value: input4.value});
console.log(arr_items);
}
Here is a small chunk of code, that I stripped down, that takes every input field, within a parent, that has a name attribute and uses those name attribute values as the keys in an object.
If uses the value of the input fields as the values in the object.
This allows the output object to change based on which input fields are in the parent element. If the input element does not have a name then it is not included.
This code can be reused and it always hands back the object needed.
const getEls = srcEl => {
const subs = [...srcEl.querySelectorAll('[name]')];
return subs.reduce((acc, sub) => {
acc[sub.getAttribute('name')] = sub.value;
sub.value = '';
return acc;
}, {});
subs[0].focus();
}
let results = [];
function doIt() {
const srcEl = document.getElementById('container');
const values = getEls(srcEl);
results.push(values);
console.log(JSON.stringify(values,0,20));
}
const btn = document.getElementById('submit');
btn.addEventListener('click', doIt);
const resultsBtn = document.getElementById('show');
resultsBtn.addEventListener('click', () => {
console.log(JSON.stringify(results,0,2));
});
<div id="container">
<p>Items Information:</p>
<input id="itemName" name="name" type="text" placeholder="enter item name"/><br/>
<input id="itemWeight" name="weight" type="number" placeholder="enter item weight(kg)"/><br/>
<input id="itemValue" name="value" type="number" placeholder="enter item value"/><br/>
<button id="submit">Enter</button>
<hr/>
<button id="show">Results</button>
</div>
There are two main aspects to note in the answer. One is that the array should be declared as a variable (not a constant), the other is that you should move the input var code into the function.
I added an alert so that you can see the outcome (wasn't sure if you wanted to allow them to be added without weight etc? This would cause confusion in your storage/retrieval of data.. so I moved the enter button)
Hope this helps
var arr_items = [];
function addValues() {
let input2 = document.getElementById("itemName");
let input3 = document.getElementById("itemWeight");
let input4 = document.getElementById("itemValue");
var item2 = input2.value + " " + input3.value + " " + input4.value;
arr_items.push(item2);
alert( [arr_items]);
}
<div>
<p>Items Information:</p>
<input id="itemName" type="text" name="item" placeholder="enter item name">
<input id="itemWeight" type="number" name="item" placeholder="enter item weight(kg)">
<input id="itemValue" type="number" name="item" placeholder="enter item value">
<button id="name" onclick="addValues()">Enter</button>
</div>

How to create an email body from static input text?

I want to create a text input form on a static page and convert that to an email body using the mailto option. For example, the following with take the input from the text box
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
and in the email body will display as
Hello ABC,
The details are:
First Name: Mickey
Last Name: Mouse
Thanks,
XYZ
I've taken the time to round up a few answers for you. I hope that you take the time to read through each of the links provided.
First you want to get your form data as an object:
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
I've used destructuring assignment to set defaults for some constants to use in the mailto:
const {
recipientName = "ABC", recipientAddress = "abc#123.yes",
subject = "Some mailz for youz", senderName = "XYZ",
firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))
We also need some linebreaks in our email body:
const lineBreak = "%0D%0A"
And finally template literals to construct our href for mailto:
const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`
Here's the snippet so you can see it all working together:
const formToJSON = elements => [].reduce.call(elements, (data, element) => {
data[element.name] = element.value;
return data;
}, {});
const {
recipientName = "ABC", recipientAddress = "abc#123.yes",
subject = "Some mailz for youz", senderName = "XYZ",
firstname = "first", lastname = "last"
} = formToJSON(document.querySelectorAll("form input:not([type='submit'])"))
const lineBreak = "%0D%0A"
const mailTo = `mailto:${recipientAddress}?subject=${subject}&body=Hello ABC,${lineBreak}
I am your father.${lineBreak}${lineBreak}
The details are:${lineBreak}${lineBreak}
First Name: ${firstname}${lineBreak}
Last Name: ${lastname}${lineBreak}${lineBreak}
Thanks,${lineBreak}
${senderName}`
const link = document.createElement("a")
link.textContent = "Send some mailz yaaaal"
link.href = mailTo
document.body.appendChild(link)
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>

fill value of input with input value form another field

I would like to fill the input value for host_name with the value that is entered into the first_name and last_name fields so the full name will appear in the host_name field. These fields are on the same page. Jquery or pure JS.
<label for="first_name">First Name</label
<input id="first_name" type="text" name="first_name">
<label for="last_name">Last Name</label
<input id="last_name" type="text" name="first_name">
<label for="host_name">Host Name</label
<input id="host_name" type="text" name="host_name">
let firstName = document.getElementById("first_name");
let lastName = document.getElementById("last_name");
let hostName = document.getElementById("host_name");
firstName.addEventListener("change", (event) => {
hostName.setAttribute("value", event.target.value);
});
lastName.addEventListener("change", (event) => {
let firstValue = hostName.getAttribute("value");
let lastValue = event.target.value;
hostName.setAttribute("value", firstValue + " " + lastValue);
});
I hope this is what you're looking for.

Categories