Check the value of an element and take action - javascript

I would like a function that checks if some fields of the form have been filled out and if true it would execute a code of mine, if false it would do nothing.
In short, I would like to know how I check the fields, the code that will be executed, I already have it ready.
HTML of the fields I want to check if they have been filled out:
<!-- verifica select -->
<div class="form-group pmd-textfield col-md-4">
<label for="InqueritoCircunscricaoPolicial" class="control-label cssPerguntas espacamentoLabels">
<strong>1.1</strong> Circunscrição policial
</label>
<select asp-for="InqueritoModel.COD_INQUERITO_CIRCUNSCRICAO_POLICIAL "
asp-items="Model.ListCircunscricao"
id="InqueritoCircunscricaoPolicial"
class="select-codigo"
onchange="mostrarOutroDeCombo(this, 'DSC_OUTRO_INQUERITO_CIRCUNSCRICAO_POLICIAL')">
<option value="">Selecione a circunscrição</option>
</select>
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="NumeroDaOcorrencia" class="control-label cssPerguntas espacamentoLabels">
<strong>1.3</strong> Número da ocorrência
</label>
<input class="form-control" id="NumeroDaOcorrencia" maxlength="1000" placeholder="N° da ocorrência"
asp-for="InqueritoModel.NumeroDaOcorrencia"
type="text">
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="DataDaInstauracao" class="control-label cssPerguntas espacamentoLabels">
<strong>1.9</strong> Data da instauração
</label>
<input class="form-control" id="DataDaInstauracao" min="1900-01-01"
asp-for="InqueritoModel.DataDaInstauracao"
type="date">
</div>
My attempt:
function progressBarInq() {
let progressBar0 = document.getElementById("InqProgress0");
let progressBar25 = document.getElementById("InqProgress25");
let progressBar50 = document.getElementById("InqProgress50");
let progressBar75 = document.getElementById("InqProgress75");
let progressBar100 = document.getElementById("InqProgress100");
//25%
let verInq1 = document.getElementById("InqueritoCircunscricaoPolicial");
//50%
let verInq5 = document.getElementById("NumeroDoIP");
//75%
let verInq8 = document.getElementById("DataDoRelatorio");
//100%
let verInq11 = document.getElementById("NumeroDoProcesso");
if (verInq1.value && verInq5.value && verInq8.value && verInq11.value) {
progressBar0.style.display = "none";
progressBar25.style.display = "block";
progressBar50.style.display = "none";
progressBar75.style.display = "none";
progressBar100.style.display = "none";
}
progressBarInq();

verifyonClick = () => {
var first = document.getElementById("InqueritoCircunscricaoPolicial")
var second = document.getElementById("NumeroDaOcorrencia")
var third = document.getElementById("DataDaInstauracao")
if(first.value && second.value && third.value)
alert("Value exist in every input")
else
alert("Please enter value in all fields")
}
<!-- verifica select -->
<div class="form-group pmd-textfield col-md-4">
<label for="InqueritoCircunscricaoPolicial" class="control-label cssPerguntas espacamentoLabels">
<strong>1.1</strong> Circunscrição policial
</label>
<select asp-for="InqueritoModel.COD_INQUERITO_CIRCUNSCRICAO_POLICIAL "
asp-items="Model.ListCircunscricao"
id="InqueritoCircunscricaoPolicial"
class="select-codigo"
onchange="mostrarOutroDeCombo(this, 'DSC_OUTRO_INQUERITO_CIRCUNSCRICAO_POLICIAL')">
<option value="">Selecione a circunscrição</option>
</select>
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="NumeroDaOcorrencia" class="control-label cssPerguntas espacamentoLabels">
<strong>1.3</strong> Número da ocorrência
</label>
<input class="form-control" id="NumeroDaOcorrencia" maxlength="1000" placeholder="N° da ocorrência"
asp-for="InqueritoModel.NumeroDaOcorrencia"
type="text">
</div>
<!-- verifica input -->
<div class="form-group pmd-textfield col-sm-3">
<label for="DataDaInstauracao" class="control-label cssPerguntas espacamentoLabels">
<strong>1.9</strong> Data da instauração
</label>
<input class="form-control" id="DataDaInstauracao" min="1900-01-01"
asp-for="InqueritoModel.DataDaInstauracao"
type="date">
</div>
<div>
<button onclick="verifyonClick()"> submit </button>
</div>

Related

Why my equations are not running in this function?

Im having travel with te following function so when the value of tipoCompra == 'Nacional' the costUSD is going to be just the value of costUSD and disable the other fields, but if the value of tipoCompra == 'Exterior' the value of costUSD shall be auto completed with simple equations within other input fields.
function CalcularNacionalizacion(){
var tipoCompra = document.getElementById('tipoCompra').value;
var fob = document.getElementById('fob');
var nacFactor = document.getElementById('nacFactor');
var Nacionalizacion = document.getElementById('costNacionalizacion');
if (tipoCompra == 'Nacional'){
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
var totalUSD = document.getElemenById('costUSD').value;
} else {
fob.disabled = '';
nacFactor.disabled = '';
Nacionalizacion.disabled = '';
var fob = document.getElementById('fob').value;
var nacFactor = document.getElementById('nacFactor').value;
var Nacionalizacion = parseFloat(fob) * parseFloat(nacFactor);
document.getElementById('costNacionalizacion').value = Nacionalizacion;
var totalUSD = parseFloat(fob) + parseFloat(Nacionalizacion);
document.getElementById('costUSD').value = totalUSD;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" onchange="CalcularNacionalizacion();" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" required>
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" onchange="CalcularNacionalizacion();" onkeyup="CalcularNacionalizacion();" class="form-control" required>
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" onchange="ToCalcularNacionalizaciondas();" onkeyup="CalcularNacionalizacion();" required>
</div>
If you choose the option 'Exterior' you can see that my equations are not running.
I do some refactoring in your code so that it would work
const tipoCompra = document.querySelector('#tipoCompra');
const fob = document.querySelector('#fob');
const nacFactor = document.querySelector('#nacFactor');
const Nacionalizacion = document.querySelector('#costNacionalizacion');
const costUSD = document.querySelector('#costUSD');
const elements = [tipoCompra, fob, nacFactor, Nacionalizacion, costUSD];
elements.forEach((i) => {
i.addEventListener('change', CalcularNacionalizacion);
});
function CalcularNacionalizacion(e) {
if (tipoCompra.value === 'Nacional') {
fob.disabled = true;
nacFactor.disabled = true;
Nacionalizacion.disabled = true;
costUSD.value = costUSD.value;
} else {
fob.disabled = false;
nacFactor.disabled = false;
Nacionalizacion.disabled = false;
const fobValue = Number(fob.value);
const nacFacotrValue = Number(nacFactor.value);
const NacionalizacionValue = fobValue * nacFacotrValue;
Nacionalizacion.value = NacionalizacionValue;
const totalUSDValue = fobValue + NacionalizacionValue;
costUSD.value = totalUSDValue;
}
}
<div class="form-group col-md-2">
<label for="">Tipo de Compra</label>
<select name="" id="tipoCompra" class="form-control" required>
<option value="">Tipo de compra </option>
<option value="Nacional">Nacional</option>
<option value="Exterior">Exterior</option>
</select>
</div>
<div class="form-group col-md-2">
<label for="fob">Costo Fob</label>
<input type="number" step="00.01" id="fob" name="fob" class="form-control" disabled="true" required />
</div>
<div class="form-group col-md-2">
<label for="nacFactor">Factor de Nacionalizacion</label>
<input type="number" step="00.01" id="nacFactor" name="nacFactor" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costNacionalizacion">Costo Nacionalizacion</label>
<input type="number" step="00.01" id="costNacionalizacion" name="costNacionalizacion" class="form-control" required />
</div>
<div class="form-group col-md-2">
<label for="costUSD">Costo total en USD-O</label>
<input type="number" step="00.01" name="costUSD" class="form-control" id="costUSD" required />
</div>

How to clear javascript validation error messages with the reset button

I have a simple form page, where there are several form validations. So far, the RESET button only clears the text field values.
But I need the validation messages to clear when the RESET button is pressed.
So far I have seen jQuery methods, but have no idea of implementing it as I am still learning.. Are there any other methods to do this without jQuery..?
Any help would be highly appreciated.
Here's my code...
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
<script>
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
</script>
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
</html>
Don't reset them manual by repeating code. Define a custom reset function which iterates over error messages and empty all of them:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
Also don't put any script tag in your head tag. Read more here
Full code:
function resetForm() {
var elems = document.querySelectorAll(".text-danger");
elems.forEach(itm => {
document.getElementById(itm.id).innerHTML = ''
})
}
function validation() {
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if (formFname.length == 0) {
document.getElementById("fnameMessage").innerHTML = "<em>You did not enter your first name</em>"
}
//Validate last name
if (formLname.length == 0) {
document.getElementById("lnameMessage").innerHTML = "<em>You did not enter your last name</em>"
}
//Validate email
if (formEmail.length == 0) {
document.getElementById("emailMessage").innerHTML = "<em>You did not enter your email</em>"
} else {
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (regex.test(formEmail) === false) {
document.getElementById("emailMessage").innerHTML = "<em>Please enter a valid email</em>"
}
}
//Validate phone
if (formNumber.length == 0) {
document.getElementById("phoneMessage").innerHTML = "<em>You did not enter your phone number</em>"
} else if (formNumber.length != 10) {
document.getElementById("phoneMessage").innerHTML = "<em>Phone Number must be exactly 10 digits</em>"
return false;
} else
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="author" content="Koshila">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Contact|Frittery</title>
<link rel="stylesheet" href="about.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css" integrity="sha384-VCmXjywReHh4PwowAiWNagnWcLhlEJLA5buUprzK8rxFgeH0kww/aWY76TfkUoSX" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>General Enquiry Form</h2>
<form method="POST" action="#">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname">
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname">
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email">
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button onclick="validation(); return false;" class="btn btn-primary">Submit</button>
<button class="btn btn-secondary" onclick="resetForm(); return false;">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js" integrity="sha384-XEerZL0cuoUbHE4nZReLT7nx9gQrQreJekYhJD9WNWhH8nEW+0c5qq7aIo2Wl30J" crossorigin="anonymous"></script>
</body>
<button type="reset" class="btn btn-secondary" onclick="clearErrors();">Reset</button>
function clearErrors() {
document.getElementById("emailMessage").innerHTML = "";
// ... repeat for other messages
}
You need to call the eraseText function separately like mentioned below
function eraseText() {
document.getElementById("fnameMessage").innerHTML = "";
document.getElementById("lnameMessage").innerHTML = "";
document.getElementById("emailMessage").innerHTML = "";
document.getElementById("phoneMessage").innerHTML = "";
}
<button onClick="eraseText()" type="reset" class="btn btn- secondary">Reset</button>
As the error/validation messages are displayed within span elements of the same class text-danger you can easily query the DOM using querySelectorAll to return a nodelist and then iterate through that collection and set the span text content to an empty string.
Note that I added a name to the form and used that name within the anonymous function in the event handler. With a name assigned to the form also means that you can identify elements simply by doing something like this:
const form=document.forms.enquiry;
const formFname=form.fname;
const formLname=form.lname;
etc etc
document.querySelector('button[type="reset"]').addEventListener('click',e=>{
e.preventDefault();
document.querySelectorAll('.text-danger').forEach(span=>span.textContent='')
document.forms.enquiry.reset()
})
function validation()
{
var formFname = document.getElementById("fname").value;
var formLname = document.getElementById("lname").value;
var formEmail = document.getElementById("email").value;
var formNumber = document.getElementById("pnumber").value;
//Validate first name
if(formFname.length ==0)
{
document.getElementById("fnameMessage").innerHTML ="<em>You did not enter your first name</em>"
}
//Validate last name
if(formLname.length ==0)
{
document.getElementById("lnameMessage").innerHTML ="<em>You did not enter your last name</em>"
}
//Validate email
if(formEmail.length ==0)
{
document.getElementById("emailMessage").innerHTML ="<em>You did not enter your email</em>"
}
else
{
var regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(regex.test(formEmail)===false)
{
document.getElementById("emailMessage").innerHTML ="<em>Please enter a valid email</em>"
}
}
//Validate phone
if(formNumber.length ==0)
{
document.getElementById("phoneMessage").innerHTML ="<em>You did not enter your phone number</em>"
}
else if(formNumber.length !=10)
{
document.getElementById("phoneMessage").innerHTML ="<em>Phone Number must be exactly 10 digits</em>"
return false;
}
else
return true;
}
<div class="container">
<h2>General Enquiry Form</h2>
<form name='enquiry' method="POST" action="#" onsubmit="validation(); return false;">
<div class="form-group row">
<label class="col-form-label col-sm-2" for="fname">First Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="fname" name="fname" >
</div>
<div class="col-sm-4">
<span id="fnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="lname">Last Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" id="lname" name="lname" >
</div>
<div class="col-sm-4">
<span id="lnameMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="email">Email</label>
<div class="col-sm-6">
<input class="form-control" type="email" id="email" name="email" >
</div>
<div class="col-sm-4">
<span id="emailMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="pnumber">Phone</label>
<div class="col-sm-6">
<input class="form-control" type="tel" id="pnumber" name="pnumber">
</div>
<div class="col-sm-4">
<span id="phoneMessage" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-sm-2" for="message">Message</label>
<div class="col-sm-10">
<textarea class="form-control" id="message" name="message" style="height: 200px;"></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-2 ">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-secondary">Reset</button>
</div>
</div>
</form>
</div>
take a look for my code
html code:
<div class="tech-news__search__container">
<div class="tech-news__search">
<input
id="subscribeInput"
type="text"
class="tech-news__search-input"
placeholder="example#gmail.com"
>
<button class="tech-news__search-button" id="subscribeButton">Subscribe</button>
</div>
<div class="resultBlock">
<p class="listOfSubscribers" id="listOfSubscribers"></p>
<div id="result"></div>
<div id="deleteAll"></div>
</div>
</div>
js code:
let node = null
let deleteAll
function renderItems() {
const items = getItem()
if (items.length) {
const listOfSubscribers = document.getElementById('listOfSubscribers')
listOfSubscribers.innerHTML = 'Subscribers'
items.map(item => {
node = document.createElement("LI");
let textnode = document.createTextNode(item);
node.appendChild(textnode);
document.getElementById("result").appendChild(node);
})
deleteAll = document.getElementById('deleteAll')
deleteAll.innerHTML = 'Delete All'
deleteAll.addEventListener('click', deleteItems)
}
}
renderItems()
function deleteItems() {
sessionStorage.removeItem('subscribers')
window.location.reload()
}

My on change jQuery event is not working properly

The value of InterMap and interDetailMap are coming from the backend. I have tried many ways to get the selected option but my JQuery change event isn't working.
I think there might be some issue with the sequence of script tags or maybe jquery tags but I cannot understand what's going wrong.
What I want to implement is that when I select Broker then my intermediary name field values will come from the backend and when I select Outsource then my name dropdown should convert into text input field and all the other fields should convert into empty text fields.
$('#intermediary_type').on('change', function() {
var selectedType = $(this).children("option:selected").text();
//var selectedType = document.getElementById("intermediary_type");
console.log(selectedType);
//var interMap = ${interMap};
document.getElementById("intermediary_name").innerHTML = "";
//var nameList = interMap[selectedType.value];
//const select="--Select--";
if (selectedType == "Broker") {
var drop = "<select class='form-control' id='intermediary_name' name='intermediary_name'></select>"
$("#intermediary_name").replaceWith(drop);
$("#intermediary_name").append("<option value=''> --Select---- </option>");
for (var i = 0; i < nameList.length; i++) {
$("#intermediary_name").append("<option value='" + nameList[i] + "'>" + nameList[i] + "</option>");
}
document.getElementById("int_spoc_name").value = "";
document.getElementById("int_emailid").value = "";
document.getElementById("int_phonenumber").value = "";
document.getElementById("int_address").value = "";
$("#intermediary_name").trigger("change");
$('#intermediary_name').on('change', function() {
var y = document.getElementById("intermediary_name");
var interDetailMap = ${interDetailMap};
var interDetail = interDetailMap[y.value];
document.getElementById("int_spoc_name").value = interDetail["intSpocName"];
document.getElementById("int_emailid").value = interDetail["intermediaryMail"];
document.getElementById("int_phonenumber").value = interDetail["intermediaryMobile"];
document.getElementById("int_address").value = interDetail["intermediaryAddress"];
//$("#intermediary_name").append();
})
}
if (selectedType == "Outsource") {
var txt = "<input type='text' maxlength=50 class='form-control text-alphanumeric-field-alignment' id='intermediary_name' name='intermediary_name'>"
$("#intermediary_name").replaceWith(txt);
document.getElementById("intermediary_name").value = "";
document.getElementById("int_spoc_name").value = "";
document.getElementById("int_emailid").value = "";
document.getElementById("int_phonenumber").value = "";
document.getElementById("int_address").value = "";
}
});
<div class="container">
<div class="h2"> Intermediary Details</div>
<div class="row">
<div class="form-group col-md-3 mb-5 ">
<label class="field" for="sel1">Type <span
style="color: red; font-size: large;">*</span></label>
<select name="intermediary_type" class="form-control" id="intermediary_type" required>
<option selected disabled>Select</option>
<option value="">Broker</option>
<option value="">Field Functionary</option>
<option value="">Outsource</option>
</select>
</div>
<div class="form-group col-md-3 mb-5 ">
<label class="field" for="sel1">Name </label>
<select name="intermediary_name" class="form-control" id="intermediary_name" required>
<option selected disabled>Select</option>
</select>
</div>
<div class="col-md-3 mb-5">
<label for="" class="form-label field">Spoc Name</label>
<input type="text" name="spoc_name" class="form-control" placeholder="" id="int_spoc_name" aria-label="" value="">
</div>
<div class="col-md-3 mb-5">
<label for="" class="form-label field">Email ID</label>
<input type="text" name="int_emailid" class="form-control" placeholder="" id="int_emailid" aria-label="" value="">
</div>
<div class="col-md-3 mb-5">
<label for="inputBank_Branch_Address" class="form-label field">Phone Number</label>
<input type="text" name="int_phonenumber" class="form-control" placeholder="" id="int_phonenumber" aria-label="" value="">
</div>
<div class="col-md-3 mb-5">
<label for="inputBank_Branch_Address" class="form-label field">Address</label>
<input type="text" name="int_address" class="form-control" placeholder="" id="int_address" aria-label="" value="">
</div>
</div>
</div>

validations with "setCustomValidity" incompatible with alerts

Im working with forms so need to customize validations with "setCustomValidity" function, the problem comes when i work with alerts and validations in the same.
The button that i use to send my data form got type="submit" when i use that kind my form is making validations correctly but that type makes a refresh so the alert never shows up.
If i switch the type to type="button" then makes the opposite. Validations are not working and alerts finally shows up.
Here is some of the form´s side code:
<div class="modal-dialog">
<div class="modal-content">
<div class="col-12 user-img">
<img src="../../images/nuevoConcesionario.png" alt="">
</div>
<span id="switching1" class="d-none">
<center>
<div class="alert alert-danger" role="alert" id="mensajeError" value="AA">
</div>
</center>
</span>
<form class="formu">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6" >
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="button" id="bEnviar" class="btn btn-primary" onclick="altaConcesionario();">Dar de alta concesionario</button>
</div>
</div>
</form>
Here is altaConcesionario validation´s function:
function altaConcesionario() {
var nomConcesionario = document.getElementById('nomConcesionario');
var nifConcesionario = document.getElementById('nifConcesionario');
var nomCiudad = document.getElementById('nomCiudad');
var nomAdministrador = document.getElementById('nomAdministrador');
var cpConcesionario = document.getElementById('cpConcesionario');
var telefono = document.getElementById('tlf');
var direccion = document.getElementById('direccion');
var emailConcesionario = document.getElementById('emailConcesionario');
// TODO unificar este mismo patron
var nomConcesionarioPatt = /[A-Za-z0-9]{4,60}/;
var nomCiudadPatt = /[A-Za-z0-9]{4,60}/;
var nomAdminPatt = /[A-Za-z0-9]{4,60}/;
var addrPatt = /[A-Za-z0-9]{4,60}/;
var emailConcesionarioPatt = /^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
var elNif = checkNif(nifConcesionario.value);
var validate = true;
// Nombre concesionario
if (nomConcesionario.value) {
nomConcesionario.setCustomValidity("");
if (!nomConcesionarioPatt.test(nomConcesionario.value)) {
mostrarAlertaValidacion("Error en el ingreso. min[4] caracteres");
nomConcesionario.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomConcesionario.setCustomValidity("Por favor, rellene campo 'nombre concesionario'");
mostrarAlertaValidacion("Por favor, rellene campo 'nombre concesionario'");
validate = false;
}
// Nif concesionario
if (nifConcesionario.value) {
nifConcesionario.setCustomValidity("");
if (!elNif) {
nifConcesionario
.setCustomValidity("El nif introducido no es correcto");
validate = false;
}
} else {
nifConcesionario
.setCustomValidity("Por favor, rellene campo 'NIF concesionario'");
validate = false;
}
// Nombre ciudad
if (nomCiudad.value) {
nomCiudad.setCustomValidity("");
if (!nomCiudadPatt.test(nomCiudad.value)) {
nomCiudad
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomCiudad.setCustomValidity("Por favor, rellene campo 'nombre ciudad'");
validate = false;
}
// Nombre administrador
if (nomAdministrador.value) {
nomAdministrador.setCustomValidity("");
if (!nomAdminPatt.test(nomAdministrador.value)) {
nomAdministrador
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
nomAdministrador
.setCustomValidity("Por favor, rellene campo 'nombre administrador'");
validate = false;
}
if (direccion.value) {
direccion.setCustomValidity("");
if (!addrPatt.test(direccion.value)) {
direccion
.setCustomValidity("Error en el ingreso. min[4] caracteres");
validate = false;
}
} else {
direccion.setCustomValidity("Por favor, rellene campo 'direccion'");
validate = false;
}
// Email concesionario
if (emailConcesionario.value) {
emailConcesionario.setCustomValidity("");
if (!emailConcesionarioPatt.test(emailConcesionario.value)) {
emailConcesionario
.setCustomValidity("El email introducido no es correcto. mail#dominio.com");
validate = false;
}
} else {
emailConcesionario
.setCustomValidity("Por favor, rellene campo 'email colaborador'");
validate = false;
}
// TODO falta validacion email
// TODO poner las rewdirecciones en su sitio
// Si estan todos los campos rellenos entra
if (validate) {
// POPUP
// SI TRUE
$
.ajax({
type : "POST",
url : '/proyecto/Api',
data : {
action : 'addConcesionario',
auth_token : auth_token,
usuario_sesion : usuario,
nomConcesionario : nomConcesionario.value,
nifConcesionario : nifConcesionario.value,
nomCiudad : nomCiudad.value,
nomAdministrador : nomAdministrador.value,
cpConcesionario : cpConcesionario.value,
telefono : telefono.value,
direccion : direccion.value,
email : emailConcesionario.value
},
success : function(response) {
alert("EXITO");
window.location.href = "/proyecto/administracion/administracion.jsp";
},
error : function(result) {
alert("ERROR");
window.location.href = "/proyecto/administracion/administracion.jsp";
}
});
}
so i would like to know if there is any reasonable way to make both works together as i need to give information to the final user and is really important for me both of functions.
Thanks in advance,
This happened because you need to prevent form submitting event.preventDefault(). Take a look at example below
const form = document.querySelector('#myForm');
form.addEventListener('submit', ev => {
ev.preventDefault();
//Your code here (validation, http etc)
console.log('Prevented');
})
<form id="myForm">
<div class="row">
<div class="form-group col-md-6">
<label for="nombre" class="col-form-label">Nombre Concesionario(*)</label>
<input type="text" class="form-control" id="nomConcesionario" placeholder="Nombre Concesionario" required>
</div>
<div class="form-group col-md-6">
<label for="Nif" class="col-form-label">NIF(*)</label>
<input type="text" class="form-control" id="nifConcesionario" placeholder="Ejemplo NIF: A58818501" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Ciudad(*)</label>
<input type="text" class="form-control" id="nomCiudad" placeholder="Ciudad" required>
</div>
<div class="form-group col-md-6">
<label for="cp" class="col-form-label">Codigo Postal</label>
<input type="text" id="cpConcesionario" placeholder="Codigo Postal" class="form-control">
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for="ciudad" class="col-form-label">Telefono Contacto</label>
<input type="tel" class="form-control" id="tlf" placeholder="Telefono Contacto">
</div>
<div class="form-group col-md-6">
<label for="nom_admin" class="col-form-label">Nombre Administrador(*)</label>
<input type="text" id="nomAdministrador" placeholder="Nombre Administrador" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="email" class="col-form-label">Email(*)</label>
<input type="email" id="emailConcesionario" placeholder="email" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="nom_admin" class="col-form-label">Dirección(*)</label>
<input type="text" id="direccion" placeholder="direccion" class="form-control" required>
</div>
</div>
<div class="row">
<div style="width: 100%; margin: 0 25% 0 25%">
<button type="submit" class="btn btn-primary">Dar de alta concesionario</button>
</div>
</div>
</form>

Dynamically switch between field sets in html

I currently have a dropdown field that onchange will input the value.
function CurrentStatusChanged() {
var currentS1 = document.getElementById("currentStatus1").value;
var currentS2 = document.getElementById("currentStatus2").value;
document.getElementById("currentStatusView1").innerHTML = "You selected: " + currentS1;
document.getElementById("currentStatusView2").innerHTML = "You selected: " + currentS2;
}
I have many fieldsets created and then correct fieldset needs to show dependent on the what selected in the dropdown box.
My question is:
What is the best approach? As I don't feel innerHTML then all of the code is good practise.
<fieldset class="employed">
<h2>Employed</h2>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="partTime">If Part Time, please detail your contractual hours per week</label>
<div class="col-md-4">
<textarea class="form-control" id="partTime" name="partTime"></textarea>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="numberOfJobs">Number of Jobs</label>
<div class="col-md-4">
<input id="numberOfJobs" name="numberOfJobs" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobDescriptionTitle">Job Description / Title</label>
<div class="col-md-4">
<input id="jobDescriptionTitle" name="jobDescriptionTitle" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
I am trying to add a field set like the one above to a container, however i have at least 12 that change dependent on the drop-down. kindisch answer doesn't allow mt use the complete field set but is on the right track i believe.
Use templates for that. For example:
var storage = [],
select = document.getElementById("selection"),
container = document.getElementById("container");
select.addEventListener("change", function() {
var _id = select.value,
_tpl = document.getElementById(_id);
save();
container.innerHTML = _tpl.innerHTML;
update();
}, false);
// Save current state
function save() {
var _fields = container.getElementsByClassName("form-control");
for (var i = 0; i < _fields.length; i++) {
storage[_fields[i].name] = _fields[i].value;
}
}
// Fill input fields of element
function update() {
var _fields = container.getElementsByClassName("form-control");
for (var i = 0; i < _fields.length; i++) {
if (_fields[i].name in storage) {
_fields[i].value = storage[_fields[i].name];
}
}
}
<select id="selection">
<option value="status-one">One</option>
<option value="status-two">Two</option>
<option value="status-three">Three</option>
</select>
<div id="container"></div>
<script type="text/html" id="status-one">
<fieldset class="employed">
<h2>Employed</h2>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="partTime">If Part Time, please detail your contractual hours per week</label>
<div class="col-md-4">
<textarea class="form-control" id="partTime" name="partTime"></textarea>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="numberOfJobs">Number of Jobs</label>
<div class="col-md-4">
<input id="numberOfJobs" name="numberOfJobs" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="jobDescriptionTitle">Job Description / Title</label>
<div class="col-md-4">
<input id="jobDescriptionTitle" name="jobDescriptionTitle" type="text" placeholder="" class="form-control input-md" required="">
</div>
</div>
</script>
<script type="text/html" id="status-two">
<p>This is status two.</p>
</script>
<script type="text/html" id="status-three">
<p>This is status three.</p>
</script>
could you use html5 data attributes? https://jsfiddle.net/hj6bbgbd/
<select id="mySelect" onchange="myFunction()">
<option value="1" data-text = "text for choice one">One</option>
<option value="2" data-text = "text for choice two">Two</option>
<option value="3" data-text = "text for choice three">Three</option>
</select>
<fieldset>
<fieldset>
<legend>My Legend:</legend>
<p id="demo"> text for choice one </p>
</fieldset>
<script>
function myFunction() {
var sel = document.getElementById('mySelect');
var opt = sel.options[sel.selectedIndex];
document.getElementById("demo").innerHTML = opt.dataset.text;
}
</script>

Categories