Cannot use insertAdjacentElement properly - javascript

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">

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" />

(Javascript) oninput with numbercheck

I'm trying to make a simple inventory systems. But I'm having problem with my oninput event.
I want to make TOTAL GOODS to be "Please input number in GOODS IN " whenever every non number value inserted into GOODS IN. But it seems I can't make it so.
/*MAKE EVERY TABLE CLICKABLE AND SHOW ROW DATA IN INPUT TEXT*/
var tbGoods = document.getElementById('tbGoods');
for (var i = 0; i < tbGoods.rows.length; i++) {
tbGoods.rows[i].onclick = function() {
document.getElementById("idTxt").value = this.cells[1].innerHTML;
document.getElementById("gdTxt").value = this.cells[2].innerHTML;
document.getElementById("qtyTXT").value = this.cells[3].innerHTML;
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
document.getElementById('totalgd').value = result;
};
}
/*MAKE EVERY NUMBER I PUT IN GOODS IN, TO BE CALCULATED WITHOUT SUBMIT BUTTON (ONINPUT)*/
function testmin() {
var qty = parseInt(document.getElementById('qtyTXT').value);
var x = parseInt(document.getElementById('gdin').value);
var result = qty - x;
if (document.getElementById('gdin').value === '') {
document.getElementById('totalgd').value = '0';
} else if (document.getElementById('qtyTXT').value === '') {
document.getElementById('totalgd').value = '0';
} else if (Number.isNaN(document.getElementById('gdin').value)) {
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
} else {
document.getElementById('totalgd').value = result;
}
}
<form method="post">
<label>ID</label>
<input type="text" name="id" id="idTxt" disabled>
<label>GOODS</label>
<input type="text" name="goods" id="gdTxt" disabled>
<label>AVAILABLE QTY</label>
<input type="text" name="qty" id="qtyTXT" disabled>
<label>GOODS IN</label>
<input type="text" name="gdin" id="gdin" oninput="testmin()">
<br>
<br>
<label>Total Goods</label>
<input type="text" name="totalgd" id="totalgd" value="0" disabled>
<br>
<input type="submit" name="submit" value="submit">
</form>
You don't need to code that manually. You can simply set the input type as "number" and your browser will not allow any non-numeric characters to be entered into the field.
Demo (run the snippet and try typing in the box):
<input type="number" id="gdin" name="gdin"/>
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number
Just add type = "number" in the input label for TOTAL GOODS. It should prevent user from entering any alphabet. Except "e"
<input type="number" name="totalgd" id="totalgd" value="0" disabled>
As pointed out, if you want to show an alert or something when an input of alphabet is there in TOTAL GOODS, you can just add
<input type="text" name="totalgd" id="totalgd" value="0" oninput = "checkFunction()" disabled>
and in the function you can check the input for :
function checkFunction() {
let totalGoodsIn = document.getElementById("totalgd").value;
let regExp = /[a-zA-Z]/g;
if(regExp.test(totalGoodsIn))
{
//logic if alphabet is present in TOTAL GOODS
}
else
{
//logic if alphabet is not present in TOTAL GOODS
}
}
if you want GOODS IN to be numeric just change the type of the label accordingly
function validateNumberField() {
var value = $("#numberField").val();
var pattern = /^\d+$/;
var isValid = pattern.test(value);
if(!isValid){
document.getElementById('totalgd').value = 'Please Input Number in Goods In';
}
}
<p>Please enter number :</p>
<input type="number" id="numberField" name="numberField"
oninput="validateNumberField()" />

js - multiple if statements, if condition isnt met the following if statements are not checked

I have the following if statements, but if the first condition is not met the following if statements are not checked. I need them all to be checked.
document.addEventListener('DOMContentLoaded', function() {
if(document.getElementById('firstname').value = "unsolicited"){document.getElementById('firstname').value = "";}
if(document.getElementById('mobile').value = "unsolicited"){document.getElementById('mobile').value = "";}
if(document.getElementById('email').value = "unsolicited#gmail.com"){document.getElementById('email').value = "";}
}, false);
Thanks so much in advance!
Actually you assign a value which you like to check.
You could store the wanted id for checking in an array along with the unwanted value and iterate the array and replace the value with an empty string.
document.addEventListener('DOMContentLoaded', function() {
[['firstname', 'unsolicited'], ['mobile', 'unsolicited'], ['email', 'unsolicited#gmail.com']]
.forEach(([id, value]) => {
const element = document.getElementById(id);
if (!element) return;
if (element.value === value) element.value = '';
});
}, false);
<input placeholder="first name" id="firstname" name="form[firstname]" type="text" value="unsolicited">
<input placeholder="mobile" id="mobile" name="form[mobile]" type="text" value="unsolicited">
<input placeholder="email" id="email" name="form[email]" type="text" value="unsolicited#gmail.com">

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.

issue with setCustomValidity

I am writing a simple if statement to test whether the passwords in each input boxes match. If they both match, no error is given and if they do not match the error "they do not match" is given using .setCustomValidity(). The issue I am having is when the error is given and then the passwords are corrected to match, the error is still given. I'm not sure what i'm doing wrong. Below is my code and a link to a working JSfiddle.
JSfiddle: https://jsfiddle.net/1934foej/
HTML:
<label>
<input id="first" type="text" min="16" max="100" placeholder="New password" autofocus required>
</label>
<label>
<input id="second" type="text" min="16" max="100" placeholder="Repeat password" required>
</label>
<input id="submit" type="submit">
JS:
var firstPasswordInput = document.querySelector('#first');
var secondPasswordInput = document.querySelector('#second');
var submit = document.querySelector('#submit');
submit.onclick = function () {
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
//checks for match
if( firstPassword.value !== secondPassword.value) {
firstPasswordInput.setCustomValidity("they do not match");
}
}
The error you are doing is the customValidity remains "they do not match" because you are not setting it to empty string (which the browser takes it as successful validation), so the input remains with the same state after one unsuccessful validation.
submit.onclick = function() {
// there is no need to redefine these two variables
var firstPassword = firstPasswordInput;
var secondPassword = secondPasswordInput;
if(firstPassword.value !== secondPassword.value) {
firstPassword.setCustomValidity("they do not match");
}
//add this part
else {
firstPassword.setCustomValidity("");
}
}

Categories