Why my equations are not running in this function? - javascript

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>

Related

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>

Check the value of an element and take action

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>

Form Values Returning Null in localStorage When Editing Selects Using Javascript?

I have a form which sends data to localStorage, which I am able to view, delete and edit. My form has a mixture of input types, text select and textarea, when I submit the form, these values store correctly, however when I use my edit function, the values show correctly on the edit form, but if I don't change the values (even to the same value), they update/store as null.
For example:
I have a form with Name(type text), Address(type address) and Dog Breed(type select), when I edit, the values of all three will be there from the form before, but if I hit submit without changing any, the dog breed would return null. They update correctly if I change the values, but as this is an appointment scheduler, not every value will be changed (for eg they may only need to change the time or breed).
Here is my snippet - I know it can't be run fully because of sandboxing but just so you can see:
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
window.onload = showTimes();
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="${bookings[i].email}" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" onchange="validateContact()" placeholder="Contact Number" name="${bookings[i].number}" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="${bookings[i].sdate}" onchange="checkStartDate()" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="${bookings[i].stime}" onfocus="showTimes()" class="time select form-control required" value="${bookings[i].stime}">${bookings[i].stime}
<option value="${bookings[i].stime}" selected disabled hidden>${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="${bookings[i].duration}" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">${bookings[i].duration}
<option value="${bookings[i].duration}" selected disabled hidden>${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="${bookings[i].address}" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="${bookings[i].postcode}" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="${bookings[i].dogname}" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="${bookings[i].breed}" value="${bookings[i].breed}">
<option value="${bookings[i].breed}" selected disabled hidden>${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="${bookings[i].info}">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" onchange="checkStartDate()" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
There are a few issues in the code you'll need to take care of:
First thing is, I'd wrap everything in a "document.ready" event handler from jQuery:
$(function() {
...
});
The above is shorthand and just ensures your code runs once all of the HTML code has been parsed.
Now, the caveat with that is now all of your functions are no longer in the global scope, so you can't reference them in HTML attributes like onclick. So, you'll need to attach them to your elements using jQuery or plain old DOM methods.
You had two lines which set the window.onload property. In the code below I've changed it to use jQuery-style event handler attachment.
You were setting the name attribute of the form elements to the value of edited appointment, but the name attribute really shouldn't need to change that often.
$(function() {
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
function loadBreeds() {
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
}
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$(window).on('load', function() {
showBooking();
showTimes();
loadBreeds();
});
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
$(document).on('change', '.datepicker', checkStartDate);
$(document).on('change', '.number', validateContact);
$(document).on('focusin', '.time', showTimes);
$(document).on('click', '.edit-booking', function(e) {
var index = +$(this).data('index');
editBooking(index);
});
$(document).on('click', '.delete-booking', function(e) {
var index = +$(this).data('index');
deleteBooking(index);
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button data-index="${i}" class="edit-booking col-md-4 btn btn-outline-danger ">Edit</button>
<button data-index="${i}" class="delete-booking col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="fname" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="lname" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="email" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" placeholder="Contact Number" name="number" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="stime" class="time select form-control required" value="${bookings[i].stime}">
<option value="${bookings[i].stime}">${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="duration" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">
<option value="${bookings[i].duration}">${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="address" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="postcode" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="breed" value="${bookings[i].breed}">
<option value="${bookings[i].breed}">${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="info">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
loadBreeds();
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>

Cannot get value from select (JS)

I have Form with several selects
Here is code
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Ф.И.О</label>
<input type="text" class="form-control" id="Name">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Дата Рождения</label>
<input type="date" class="form-control" id="birthday">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Должность:</label>
<textarea class="form-control" id="position"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Телефон:</label>
<textarea class="form-control" id="telephonepeople"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">График работы:</label>
<select class="form-control" id="workTime">
<option>Дневная Смена</option>
<option>Ночная смена</option>
<option>Сутки</option>
<option>Дневная -Ночная смены</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Адрес проживания:</label>
<textarea class="form-control" id="adress"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Регион:</label>
#Html.DropDownList("Region", null, htmlAttributes: new { #class = "form-control", #id = "region" })
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Паспортные данные:</label>
<textarea class="form-control" id="passportData"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">ИНН:</label>
<textarea class="form-control" id="INN"></textarea>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Медицинская книга:</label>
<select class="form-control" id="medicalCard">
<option>Имеется</option>
<option>Не Имеется</option>
</select>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Дата окончания мед книжки:</label>
<input type="date" class="form-control" id="bookending">
</div>
I need to get values from it and pass to back-end.
I have this javascript code (here is part, where I get values, because all other is working great)
function AddPeople() {
let proposalurl = '/peopleforworks/addpeople';
let Name = $('#Name').val();
let birthday = $('#birthday').val();
let telephone = $('#telephonepeople').val();
let workTime = $('#workTime').text();
let adress = $('#adress').val();
let passportData = $('#passportData').val();
let medicalCard = $('#medicalCard').val();
let INN = $('#INN').val();
let medicalbookdate = $('#bookending').val();
let position = $('#position').val();
let region = $('#region').text();
alert(workTime);
But alert shows me nothing. All other selects are working and values is getting from them.
Where can be my problem?
Thank's for help
You need to define a value for each of your select's <option>:
Replace this:
<select class="form-control" id="workTime">
<option>Дневная Смена</option>
<option>Ночная смена</option>
<option>Сутки</option>
<option>Дневная -Ночная смены</option>
</select>
By this:
<select class="form-control" id="workTime">
<option value="Дневная Смена">Дневная Смена</option>
<option value="Ночная смена">Ночная смена</option>
<option value="Сутки">Сутки</option>
<option value="Дневная -Ночная смены">Дневная -Ночная смены</option>
</select>
And also:
let workTime = $('#workTime').text();
By this:
let workTime = $('#workTime').val();
use .val()
let workTime = $('#workTime').val();

Unable to create array of object to save MongoDB from AngularJS

I have created html dynamically and want to save in MongoDB using Mongoose from AngularJS. But the problem is that, I'm unable to create that require object which I have created Mongoose schema.
model code
var SegmentSchema = new Schema({
name: String,
uiName:String,
type:String,
lower:Number,
upper:Number,
options:[{key:String,value:String}]
});
export default mongoose.model('Segment', SegmentSchema);
view code
<form class="form-horizontal" ng-submit="addSegment()">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<p class="form-control-static"><input class="form-control" type="text" required ng-model="segment.name" name="name" value=""></p>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">UI Name</label>
<div class="col-sm-6">
<input class="form-control" type="text" ng-model="segment.uiName" name="uiName" value="">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 control-label">Type</label>
<div class="col-sm-6">
<select ng-model="segment.type" ng-change="changeType()" class="form-control" name="type">
<option value="">---select type---</option>
<option value="text">Text</option>
<option value="range">Range</option>
<option value="select">Select</option>
<option value="binary">Binary</option>
</select>
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.lower" type="number" name="lower" value="">
</div>
</div>
<div ng-show="rangeShow" class="form-group">
<label for="lower_range" class="col-sm-2 control-label">Lower Range</label>
<div class="col-sm-6">
<input class="form-control" ng-model="segment.upper" type="number" name="upper" value="">
</div>
</div>
<div ng-show="numOptionShow" class="form-group">
<label for="inputPassword" class="col-sm-6 control-label"></label>
<div class="col-sm-2">
<input placeholder="Options count" class="form-control col-sm-3" ng-keydown="keyupOptionNumber()" ng-keyup="keyupOptionNumber()" ng-model="numOption" type="text" value="">
</div>
</div>
<div ng-show="selectOptionShow" class="" id="segment-select-option">
</div>
<div class="form-group">
<button type="submit" ng-show="addSegmentBtn" class="btn btn-success">Add</button>
</div>
</form>
angularjs(controller) code:
angular.module('nrichApp')
.controller('SegmentCtrl', function ($scope,$http,segment) {
$scope.loading = true;
$scope.addSegmentDiv=false;
segment.get().success(function(data) {
$scope.segments=data;
});
$scope.loading = false;
})
.controller('AddSegmentCtrl', function ($scope,segment,$location,$compile) {
$scope.loading = true;
$scope.addSegmentBtn=false;
$scope.changeType=function(){
$scope.addSegmentBtn=true;
$scope.rangeShow=false;
$scope.selectOptionShow=false;
$scope.numOptionShow=false;
switch ($scope.segment.type) {
case 'range':
$scope.rangeShow=true;
break;
case 'select':
$scope.numOptionShow=true;
break;
case 'binary':
break;
default:
}
};
$scope.keyupOptionNumber=function(){
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
$scope.addSegment=function(){
$scope.loading = true;
var param = {'segment' : $scope.segment};
console.log(JSON.stringify(param));//it is output which show at below
segment.create(param)
.success(function(data) {
$scope.loading = false;
$location.path('/segment');
});
$scope.loading = false;
};
});
Output:
{
"segment":{
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options":{
"0": { "key":"k3","value":"v2"},
"1": { "key":"k4","value":"v4"}
}
}
}
Desired Output:
{
"segment": {
"type":"select",
"name":"range2",
"uiName":"Select 3",
"options": [
{"key":"k3","value":"v2"},
{"key":"k4","value":"v4"}
]
}
}
Finally, i got solution. I just declare array data type for options variable i.e,
$scope.options=[]
Inside angular controller:
$scope.keyupOptionNumber=function(){
$scope.options=[];//Here, this line is missing
console.log($scope.numOption);
$scope.selectOptionShow=true;
var input ='';
for (var i = 0; i < $scope.numOption; i++) {
input+='<div class="form-group">';
input+='<label for="option_key" class="col-sm-2 control-label">Key</label>';
input+='<div class="col-sm-2"><input ng-model="segment.options[' + i + '].key" class="form-control" type="text" name="key" value=""></div>';
input+='<label for="option_value" class="col-sm-1 control-label">Value</label>';
input+='<div class="col-sm-3"><input ng-model="segment.options[' + i + '].value" class="form-control" type="text" name="value" value=""></div>';
input+='</div>';
}
var eleDiv=angular.element(document.querySelector('#segment-select-option'));
eleDiv.html(input);
$compile(eleDiv)($scope);
};
Thanks #shaishab roy

Categories