My on change jQuery event is not working properly - javascript

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>

Related

sql add "n" row with values

I have code below.
When I click the button, the new value is named "name+1"
I want to enter these values ​​into the sql database
Bad Sql query:
$sql = "INSERT INTO bb(numer, ID, numerczesci, iloscczesci, przyczyna,
numerfaktury, data, uwagi)
VALUES ('','','$numerczesci','$iloscczesci',
'$przyczyna', '$numerfaktury', '$data', '$uwagi' )";
I don't know how to declare variables and what sql query to write.
var i =0;
var k =0;
function duplicate() {
var original = document.getElementById('duplic');
var rows = original.parentNode.rows;
i++;
var clone = original.cloneNode(true); // "deep" clone
var InputType = clone.getElementsByTagName("input");
clone.id = "duplic" + (i); // there can only be one element with an ID
original.parentNode.insertBefore(clone, rows[i]);
k=k+1;
document.getElementById("numerczesci").setAttribute("name", "numerczesci" + k );
document.getElementById("iloscczesci").setAttribute("name", "iloscczesci" + k );
document.getElementById("przyczyna").setAttribute("name", "przyczyna" + k );
document.getElementById("numerfaktury").setAttribute("name", "numerfaktury" + k );
document.getElementById("data").setAttribute("name", "data" + k );
document.getElementById("uwagi").setAttribute("name", "uwagi" + k );
}
<table >
<tr id="duplic"> <td>
<div class="form-group required">
<label for="fldNazwa" class="control-label">numer części/symbol</label>
<input type="text" class="form-control" id="numerczesci" name="numerczesci" required>
</div>
<div class="form-group required">
<label for="fldNazwa" class="control-label">ilość części</label>
<input type="number" class="form-control" id="iloscczesci" name="iloscczesci" value="1" min="1" required>
<br>
<div class="form-group required">
<label for="fldNazwa" class="control-label">przyczyna zwrotu</label>
<select name="przyczyna" required id="przyczyna">
<option disabled selected value> -- wybierz opcję -- </option>
<option value="zlaczesc">część źle zamówiona </option>
<option value="bladdostawcy">błąd dostawcy przy wysyłce </option>
<option value="czescuszkodzona">część uszkodzona podczas transportu lub wadliwa</option>
</select>
</div>
<div class="form-group required">
<label for="fldNazwa" class="control-label">numer faktury</label>
<input type="text" class="form-control" id="numerfaktury" name="numerfaktury" required>
</div>
<div class="form-group ">
<label for="fldNazwa" class="control-label">data wystawienia faktury</label>
<input type="date" class="form-control" id="data" name="data">
</div>
</div>
<div class="form-group ">
<label for="fldNazwa" class="control-label">uwagi</label>
<textarea class="form-control" id="uwagi" name="uwagi"></textarea>
</div>
<br> <br>
</td>
<td>
</td>
</tr>
</table>
<button id="addmore" onclick="duplicate()">Dodaj Towar</button>
<br><br>

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>

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>

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>

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