fill value of input with input value form another field - javascript

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.

Related

Why does my Input doesn't fill the value attribute when It is written

I have an email input and I'm trying to read the input value but It doen't return a value when It is filled.
<input id="email" name="email" required="" type="email" value=" " class="form-control" />
This is the function I'm trying to execute, saving the Value on a variable to use it later.
var email = document.getElementById("email").value;
I have already tried
var email = document.getElementById("email"); console.log(email.value);
But have no luck
In this snippet, you can see how you can get the value of the input field as it changes. My suspicion is that you are trying to get the input's value before the user has filled it in (it's a common mistake)
//var ch = 0;
var in1 = document.querySelector("input");
var in2 = document.querySelector("input:last-of-type");
in1.addEventListener("change", function(e) {
// ch++;
console.log("changed: " + in1.value);
});
in2.addEventListener("keyup", function(e) {
console.log("changed: " + in2.value);
});
<input type="email" />
<input type="email" />

select forms with GET METHOD

My code below selects forms with both POST and GET methods. But I want to select forms with GET form method attribute only. How can I use selector/filters to retrieve only those form elements that set form method as GET
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
{
const {
document
} = (new JSDOM(data)).window;
var all = document.getElementsByTagName("FORM");
for (var i = 0, max = all.length; i < max; i++) {
var aform = document.getElementsByTagName("FORM")[i];
// log aform.outerHTML
}
}
You can use querySelectorAll to match more complex rules than just the element type.
A type selector can filter by forms, then attribute selectors can examine the method attribute.
You need to be careful because GET is the default value so you need to test for the case where there is no method attribute at all (with a :not() pseudo-class) and where it is set to GET
const get_forms = document.querySelectorAll("form:not([method]), form[method='get']")
console.log(get_forms.length + " matching forms");
<form method="GET"></form>
<form method="POST"></form>
<form></form>
CSS Selectors
Document.querySelectorAll()
let getform = document.querySelectorAll("form[method=GET]")[0].id;
console.log(getform)
let postform = document.querySelectorAll("form[method=POST]")[0].id;
console.log(postform)
let omittedform = document.querySelectorAll("form")[2];
if (!omitted.getAttribute("method")) {
console.log(omitted.id)
}
[...document.querySelectorAll("form")].forEach(form => {
if (!form.getAttribute("method") || form.getAttribute("method") === "GET") {
console.log("Form with id " + form.id + "is GET")
} else if (form.getAttribute("method") === "POST") {
console.log("Form with id " + form.id + "is POST")
}
});
<form method="GET" id="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
<form method="POST" id="post">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
<form id="omitted">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
And as comment suggested, if form method is omitted you would need to check if method attribute exists in HTML, if not, you can treat it as GET.
!omitted.getAttribute("method")
As we don't see your HTML, you would need use examples above to write your own logic suitable for your use case.
Or you can check it all like this:
[...document.querySelectorAll("form")].forEach(form => {
if (!form.getAttribute("method") || form.getAttribute("method") === "GET" ) {
console.log("Form with id " + form.id + "is GET")
} else {
console.log("Form with id " + form.id + "is POST")
}
});
You can do it with javascript variable for which switch between form methods
let formMethod = undefined
let getForms = document.querySelectorAll(`form[method=${formMethod || 'GET'}]`)
formMethod = "POST"
let postForms = let forms = document.querySelectorAll(`form[method=${formMethod || 'GET'}]`)
you can do it also with a function
function findForms(method) {
return document.querySelectorAll(`form[method=${method || 'GET'}]`)
}
let postForms = getForms("POST")
let getForms = getForms("GET")
let firstGetForm = getForms[0]
let firstGetFormId = firstGetForm.id
let secondGetForm = getForms[1]
let secondGetFormId = secondGetForm.id

Cannot use insertAdjacentElement properly

I wanted to have the message "This input field cannot be blank" appearing after each input text and email field. However, I failed to do so. Only one message was appeared after the last input field (i.e. Card Number)
Would you please help me spot out what happened? I tried for 1 hour.
Thank you very much.
//javascript file
const elementAction = {
createMessage: function(insertedElement, value, elementCollection, position ){
const newElement= document.createElement(insertedElement);
newElement.innerHTML= value;
elementAction.insertAlert(position, elementCollection, newElement);
},
insertAlert: function(position, elementCollection, insertedElement){
for(let i=0; i<elementCollection.length; i++){
elementCollection[i].insertAdjacentElement(position, insertedElement);
}
},
get: function(element){
const elementCollection = document.querySelectorAll(element);
return elementCollection;
}
};
const inputFieldCollection = elementAction.get("[type='email'], [type='text']");
elementAction.createMessage('p', 'This input field cannot be blank', inputFieldCollection, 'afterend');
//HTML file
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
<label for="mail">Email:</label>
<input type="email" id="mail" name="user_email">
<label for="cc-num">Card Number:</label>
<input id="cc-num" name="user_cc-num" type="text">

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>

Get value from input and store it to the object 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)
})

Categories