I'm trying to give a for or foreach based on my data-index to add value to each of the adesaoTest fields
If the data-index is equal to zero it normally goes through the process
The first time the code is compiled normally, but the second time when the data-index is = 1 it does not calculate
JavaScript
adesao = 0.00;
const totalAdesao = document.querySelectorAll('.quota-row');
totalAdesao.forEach(adesaoTest => {
var index = adesaoTest.getAttribute('data-index');
var entrada = document.getElementById(`quota-entrada-${index}`);
var parcelas = document.getElementById(`quota-parcelas-${index}`);
var adesaoTest = document.getElementById(`quota-adesao-${index}`);
adesao = parseFloat(entrada.value) / parcelas.value;
adesaoTest.value = adesao;
})
For each of the fields var adesaoTest = document.getElementById(quota-adesao-${index})
must perform calculation above
Note:
I'm using fetch to add the new entries that will go through for or foreach
When the second element is created it gives the following error
This is the function that adds the other elements
var quotasDiv = document.getElementById('quotas');
const id = quotasDiv.querySelectorAll('.row').length + 1;
var quotaPrincipal = document.getElementById('quota-principal');
const request = new Request('/configuracoes/listFormaPagamento/json', { method: 'POST' });
fetch(request)
.then(res => {
res.json()
.then(data => {
var html = `<div class="row quota-row" data-index="${id}">
<div class="col-8" id="quota-${id}" >
<div>
<div class="col-xs-2">
<span>Entrada ${(id + 1)}</span>
<input onblur="calculaRestante(this)" type="text" data-index="${id}" id="quota-entrada-${id}" required="" name="entrada[]" placeholder="Primeira Parte" id="valor8" value="0">
</div>
<div class="col-xs-2 dateInput">
<span>Forma de Pagamento</span>
<select onchange="onChangeFormaPagamento(this)" data-index="${id}" id="quota-forma-pagamento-${id}" name="forma_pagamento[]">
<option value="">Selecione a forma de pagamento</option>
${data.map(forma_pagamento => {
return `<option value="${forma_pagamento.id_formas_pagamento}"> ${forma_pagamento.forma_pagamento} </option>`
})}
</select>
</div>
<div class="col-xs-1 dateInput">
<span>Parcelas</span>
<select data-index="${id}" id="quota-parcelas-${id}" onchange="calculaAdesao()" name="parcelas[]" >
<option value=""></option>
</select>
</div>
<div class="col-xs-2">
<span>Vencimento</span>
<input data-index="${id}" type="date" required="" id="quota-vencimento-${id}" name="vencimento[]" placeholder="Entrada">
</div>
<div class="col-xs-2">
<span>Adesão</span>
<input data-index="${id}" type="text" required="" id="quota-adesao-${id} "name="adesao[]" placeholder="Valor de entrada" id="valor6">
</div>
<div class="col-xs-2">
<span style="color: red; cursor: pointer; margin-top: 3rem" onclick="deleteQuotaHtml(this)"><i class="fas fa-trash-alt"></i></span>
<div>
</div>
</div>
</div>`;
quotasDiv.innerHTML += html;
})
})
}
Related
All of the buttons on my web site suddenly stopped working. When I try to press them, in the console it says that they don't exist. I've checked to make sure the Javascript filename in the script tag is correct. I made a folder only for my current Javascript, html, and CSS files. I tried changing the script tag from being at the end of the html document to in the header. None of these things did anything.
medAppFreshStart3.html:33 Uncaught TypeError: noteModal is not a function
at HTMLButtonElement.onclick (medAppFreshStart3.html:33)
onclick # medAppFreshStart3.html:33
<!DOCTYPE html>
<html>
<header>
<script src="medAppFreshStart3.js"></script>
<link rel="stylesheet" href="medAppStyle3.css" />
</header>
<body>
<div class="container">
<div class="d1">
demographics
<button onclick="newPatient()" id="newPatient">+ New Patient</button>
<button onclick="localStorage.clear()" id="clearPtData">
Clear Patient Data</button
><br />
<!--<label for="search">Patient Search</label>-->
<input id="search" placeholder="Enter patient name" />
<button id="searchButton">search</button>
<p id="nameDisplay"></p>
<p id="ageDisplay"></p>
<!--<label for="search">patient search</label>
<input
type="search"
onsearch="findPatient()"
name="search"
id="search"
/>-->
</div>
<div class="d2 flex-container">
current note
<button onclick="noteModal()" id="newNote">+ Add</button>
<div class="content">
<div class="current-note-sub content-1" id="subjective">
Subjective:
</div>
<div class="current-note-sub content-1" id="objective">
Objective:
</div>
<div class="current-note-sub content-1" id="assessment">
Assessment:
</div>
<div class="current-note-sub content-1" id="plan">Plan</div>
</div>
</div>
<div class="d3">
Problem-list
<button onclick="addProblem()" id="new problem">+ Add</button>
<div class="content">
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">PRoblem:</div>
</div>
</div>
<div class="d4 flex-container">
prescriptions
<button onclick="addPrescription()" id="new prescription">+ Add</button>
<div class="content" id="prescriptions">
<div class="prescription" id="prescription1">prescription1</div>
<div class="prescription" id="prescription2">prescription2</div>
<div class="prescription" id="prescription3">prescription3</div>
<div class="prescription" id="prescription4">prescription3</div>
</div>
</div>
<div class="d5 flex-container">
Previous Notes
<div class="content">
<div class="past-note" id="past-note1">Date: Complaint:</div>
<div class="past-note" id="past-note2">Date: Complaint:</div>
<div class="past-note" id="past-note3">Date: Complaint:</div>
<div class="past-note" id="past-note4">Date: Complaint:</div>
</div>
</div>
</div>
<div id="addPrescription" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closePrescription()" class="close">×</span>
<form action="" method="post" id="prescriptionForm">
<label for="Drug"> Drug:</label>
<input
type="text"
id="Drug"
name="Drug"
type="text"
reqired
aria-required="true"
/>
<label for="Dosage"> Dosage:</label>
<input
type="number"
id="Dosage"
name="Dosage"
required
aria-required="true"
/>
<label for="measurement">Measurement</label>
<select id="measurement" name="measurement">
<option value="micrograms">micrograms</option>
<option value="milligrams">milligrams</option>
<option value="grams">grams</option>
</select>
</form>
<button
type="submit"
value="submit"
form="PrescriptionForm"
onclick="createPrescription(); closePrescription()"
>
+ Create
</button>
</div>
</div>
<div id="noteModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeNote()" class="close">×</span>
<form action="" method="post" id="noteForm" name="noteform">
<label for="Date"> Date: </label>
<input
type="text"
id="Date"
name="Date"
reqired
aria-required="true"
/>
<label for="complaint"> Complaint: </label>
<input
type="text"
id="complaint"
name="complaint"
reqired
aria-required="true"
/>
<label for="subjective">Subjective</label>
<textarea id="subjective" name="subjective"></textarea>
<label for="objective">Objective</label>
<textarea id="objective" name="objective"></textarea>
<label for="assessment">Assessment</label>
<textarea id="assesment" name="assessment"></textarea>
<label for="plan">Plan</label>
<textarea id="plan" name="plan"></textarea>
</form>
<button onclick="createNote(), closeNote()">+ Create</button>
</div>
</div>
<div id="addProblem" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeProblem()" class="close">×</span>
<form action="" method="post" id="problemForm">
<label for="problem"> Problem:</label>
<input
type="text"
id="problemForm"
name="problemForm"
reqired
aria-required="true"
/>
</form>
<button
type="submit"
value="submit"
form="problem"
onclick="closeProblem()"
>
+ Create
</button>
</div>
</div>
<div id="newPtDemographics" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeDemo()" class="close">×</span>
<form action="" method="post" id="demoForm">
<label for="name"> Name:</label>
<input
type="text"
id="name"
name="name"
reqired
aria-required="true"
/>
<label for="age"> Age:</label>
<input
type="number"
id="age"
name="age"
reqired
aria-required="true"
/>
</form>
<button onclick="createPatient(), closeDemo()">+ Create</button>
</div>
</div>
</body>
</html>
```
```function newPatient() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'block';
}
function findPatient() {
let name = document.getElementById(search);
name = name.innerText;
console.log(name);
}
const button1 = document.getElementById('searchButton');
searchButton.addEventListener('click', () => {
const name = document.getElementById('search').value;
//console.log(name);
let patients = localStorage.getItem('patients');
patients = JSON.parse(patients);
let patient = patients[name];
nameDisplay = document.getElementById('nameDisplay');
ageDisplay = document.getElementById('ageDisplay');
nameDisplay.innerHTML = 'Name: ' + patient[key];
ageDisplay.innerHTML = 'Age' = patient.age;
//console.log(patient);
//patients = JSON.parse(patients);
});
function createPatient() {
let patients = localStorage.getItem('patients');
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
if (patients !== null) {
//instead of parsing here can just append array with new patient if it already exists.
//Will need to parse to retrieve data to fill patient details when select new patient or
//reopen broswer.
patients = JSON.parse(patients);
} else {
patients = {};
}
patients[name] = { age: age };
//patients.push({ [name]: { age: age } });
localStorage.setItem('patients', JSON.stringify(patients));
//console.log(patients[name]);
}
function addPrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'block';
}
function createPrescription() {
const div = document.getElementById('prescriptions');
const newPrescription = document.createElement('div');
newPrescription.classList.add('prescription');
const name = document.getElementById('name').value;
console.log(name);
//var patient = JSON.parse(localStorage.getItem('patients.[name]'));
//newPrescription.innerHTML = patient;
//div.appendChild(newPrescription);
//console.log('testing');
//console.log(patient);
//console.log('testing');
/*
newPrescription.innerHTML =
'Drug: ' +
document.getElementById('prescriptionForm').Drug.value +
' Dosage: ' +
document.getElementById('prescriptionForm').Dosage.value +
' ' +
document.getElementById('prescriptionForm').measurement.value;
div.appendChild(newPrescription);
*/
}
function createNote() {
let noteForm = document.getElementById('noteForm');
let formData = new FormData(noteForm);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
var note = JSON.stringify(object);
}
function noteModal() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'block';
}
function addProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'block';
}
function closeProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'none';
}
function closeNote() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'none';
}
function closePrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'none';
}
function closeDemo() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'none';
}
I have created a course container and I want to populate the options by fetching them from the backend
(URL: https://ffcc-app.herokuapp.com/get/courses)
<div class="container">
<form action="#" method="POST">
<h2>Course 1</h2>
<div class="select-box">
<div class="options-container">
<select class="option" id="one">
<option value="">Select a course.. </option>
</select>
</div>
<div class="selected">
Select Courses
</div>
<div class="search-box">
<input type="text" placeholder="Search..." />
</div>
</div>
</form>
</div>
Also when I type any character in the search box it should filter the options.
Can someone help me on how to fetch the data from the URL to populate the options list?
PS: I am familiar with Fetch API for fetching the data
You could do something like this:
let result = {};
let allCourses = {};
function filterCourses() {
var filter = document.getElementById("inputFilter").value;
result.courses = allCourses.courses.filter(x => x.title.includes(filter))
let select = document.getElementById("one");
while (select.firstChild) {
select.removeChild(select.firstChild);
}
for (let i = 0; i < result.courses.length; i++){
let option = document.createElement("option");
option.value = result.courses[i]._id;
option.text = result.courses[i].title;
select.appendChild(option);
}
}
async function getCourses() {
let url = 'users.json';
try {
let res = await fetch("https://ffcc-app.herokuapp.com/get/courses");
return await res.json();
} catch (error) {
console.log(error);
}
}
async function renderCourses() {
allCourses = await getCourses();
result = Object.assign({}, allCourses);
let select = document.getElementById("one");
for (let i = 0; i < result.courses.length; i++){
let option = document.createElement("option");
option.value = result.courses[i]._id;
option.text = result.courses[i].title;
select.appendChild(option);
}
}
renderCourses()
<div class="container">
<form action="#" method="POST">
<h2>Course 1</h2>
<div class="select-box">
<div class="options-container">
<select class="option" id="one">
<option value="">Select a course.. </option>
</select>
</div>
<div class="selected">
Select Courses
</div>
<div class="search-box">
<input type="text" id="inputFilter" placeholder="Search..." onchange="filterCourses()"/>
</div>
</div>
</form>
</div>
Explanation: after loaded all the courses, I made an option for each course (with _id as option value and title as option text). This is made by function renderCourses.
Then the filterCourses function: basically it takes the value from input and looks for an option that contains what you typed in input. If you clean the input, function returns all the courses.
You have to get your api, create a function to manipulate your DOM, pass the data to this function so that it renders the content inside the select tag.
This is just for the select tag.
const select = document.querySelector('.option')
fetch('https://ffcc-app.herokuapp.com/get/courses')
.then(response => response.json())
.then(data => {
data.courses.forEach(course => render(course))
});
function render(course) {
const opt = document.createElement('option')
opt.value = course.title
const content = document.createTextNode(`${course.title}`)
opt.appendChild(content)
select.appendChild(opt)
}
<div class="container">
<form action="#" method="POST">
<h2>Course 1</h2>
<div class="select-box">
<div class="options-container">
<select class="option" id="one">
<option value="">Select a course.. </option>
</select>
</div>
<div class="selected">
Select Courses
</div>
<div class="search-box">
<input type="text" placeholder="Search..." />
</div>
</div>
</form>
</div>
I am working in ASP.Net MVC4. My div elements contents are generated in a loop as below:
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span class="product-price">Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span>Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;"
})
<button type="button" class="apply-discount">Recalculate</button>
</div>
}
}
JavaScript portion
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon").val();
var price = $(this).parent().find(".product-price").val();
var cost = 0;
if (applyCoupon === NaN) {
applyCoupon = 0;
}
if (price === NaN) {
price = 0;
}
$(this).parent().find(".product-price").val(applyCoupon);
});
Browser generated html is below
<div>
<div class="col-md-1">
<img src="/Astrology/Product/GetImage/51da66b7-3cb9-418b-ae9a-bc9fe8073b26" style="width: 50px; height: 50px;" alt="Mapa Natal Cármico" />
</div>
<div class="col-md-6 vcenter">
<span style="font-size: large">Mapa Natal Cármico. Escrito por Marcelo Dalla</span>
</div>
<div class="col-md-2 vcenter">
<span class="product-price">Preço: R$ 44,00</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
<button type="button" class="dec-count">-</button>
<input chart-price="44,0000" class="product-count" data-val="true" data-val-number="The field Quantity must be a number." data-val-required="The Quantity field is required." dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__Quantity" name="products[7819060a-0f29-4637-83de-9262beb1a13f].Quantity" product-coupon="10" readonly="readonly" style="width:50px;" type="text" value="1" />
<button type="button" class="inc-count">+</button>
</div>
<span>If you have a discount coupon for the purchase please enter it here and press the recalculate button.</span>
<div class="col-md-2 vcenter" style="text-align: end;">
<input chart-price="44,0000" class="product-discount-coupon" dicsount-price="10,0000" id="products_7819060a-0f29-4637-83de-9262beb1a13f__CouponTemp" name="products[7819060a-0f29-4637-83de-9262beb1a13f].CouponTemp" product-coupon="10" style="width:50px;" type="text" value="" />
<button type="button" class="apply-discount">Recalculate</button>
<input id="apply-product-coupon" type="hidden" name="apply-product-coupon">
</div>
<div class="col-md-1 vcenter">
<a href="/Astrology/Shop/DeleteFromCard?productId=41f7e40b-62ad-4202-964a-cbed7381b06c">
<i class="fa fa-remove"></i>
</a>
</div>
</div>
When the user clicks on the Recalculate button I want to put CouponTemp textbox value in another span. Note that clicking on block-1 does not impact on block-2 or rest, in the same way click on block-2 not impact on another block content.
<span>Preço: #Model.Price.ToString("C")</span>
Here is your script:
$(document).ready(function(){
$("button.apply-discount").click(function(){
//get your input value
var discount = $(this).prev('input.product-discount-coupon').first().val();
//Get your span
var resultSpan = $(this).parent().prev().prev().prev().find('span');
//Update your span with input value
resultSpan.html("Preço: R$ " + discount);
});
});
I create JSFiddle to show how it works.
Following code snippet may help you.
$(".apply-discount").on("click", function () {
var applyCoupon = $(this).parent().find(".product-discount-coupon");
var price = applyCoupon.val();
//to get others info
var chart_price= applyCoupon.attr('chart_price');
var dicsount_price= applyCoupon.attr('dicsount_price');
var product_coupon= applyCoupon.attr('product_coupon');
$(this).parent().prev().prev().find(".product-price").html('Preço: '+price*1);
});
N.B: price*1 will convert it to a number.
Well, pretty easy if you just assign ids to the elements. Use something like id from your product to ensure they are unique and match.
#foreach (var product in Model.Products)
{
<div class="col-md-2 vcenter">
<span>Preço: #Model.Price.ToString("C")</span>
</div>
#if (Model.IsValid != null && Model.IsValid != "")
{
<div class="col-md-2" style="text-align: end;">
<span id="#product.Id">Enter number.</span>
</div>
<div class="col-md-2 vcenter" style="text-align: end;">
#Html.TextBoxFor(m => m.CouponTemp, new {
#class = "product-discount-coupon",
chart_price = Model.Price.ToString(),
dicsount_price = Model.SpecialPrice.ToString(),
product_coupon = Model.Coupon,
style = "width:50px;",
id = "txt_" + #product.Id
})
<button type="button" class="apply-discount" onclick="adjustPrice(#product.Id);">Recalculate</button>
</div>
}
}
Then have a function that handles it:
<script type="text/javascript">
var adjustPrice = function (id) {
var txt = $('#txt_' + id).val();
$('#' + id).val(txt);
};
</script>
Have a form to create a contract, where that contract can have one or more users associated.
The area to input the users info, starts with only one field of one user, and one button to add more fields if needed.
<div id="utilizadores" class="row">
<div id="utilizador1" class="container-fluid">
<div class="row">
<div class="col-lg-5">
<input type="text" class="form-control" id="nomeUtilizador1" placeholder="Nome Utilizador">
</div>
<div class="col-lg-6">
<input type="text" class="form-control" id="funcaoUtilizador1" placeholder="Função">
</div>
</div>
</div>
</div>
This is the starting div
Clicking on Add User button it adds a new div under the "utilizador1"
<div id="utilizadores" class="row">
<div id="utilizador1" class="container-fluid">
<div class="row">
<div class="col-lg-5">
<input type="text" class="form-control" id="nomeUtilizador1" placeholder="Nome Utilizador">
</div>
<div class="col-lg-6">
<input type="text" class="form-control" id="funcaoUtilizador1" placeholder="Função">
</div>
</div>
</div>
<div id="utilizador2" class="container-fluid">
<div class="row">
<div class="col-lg-5">
<input type="text" class="form-control" id="nomeUtilizador2" placeholder="Nome Utilizador">
</div>
<div class="col-lg-6">
<input type="text" class="form-control" id="funcaoUtilizador2" placeholder="Função">
</div>
</div>
</div>
My question is, how can I get the number of users created, and insert them into a list using Javascript. The list will be a attribute of a Object (Contract).
What i have til now:
function test_saveItem() {
var contract = new Object();
contract.Dono = <% =uID %>;
contract.BoostMes = $("#boostMes").val();
contract.BoostAno = $("#boostAno").val();
var ListaUtilizadores = [];
var divs = document.getElementsByName("utilizador");
for (var i = 0; i < divs.length; i++){
var user = new Object();
user.Nome = $('#nomeUtilizador' + i).val();
ListaUtilizadores.push(user);
}
var test = JSON.stringify({ "contract": contract });
}
Any help appreciated
Edit: Got to a solution thanks to Shilly
List = [];
Array.prototype.slice.call(document.querySelectorAll('.user')).forEach(function (node, index) {
List.push({
"name" : document.getElementById('nameUser' + (index + 1)).value,
"job" : document.getElementById('jobUser' + (index + 1)).value
});
});
Something like this? But adding it into the addUser function as Super Hirnet says, will be more performant.
var divs = document.querySelector('#utilizadores').childNodes,
users = [];
Array.slice.call(divs).forEach(function (node, index) {
users.push({
"name" : divs[index].getElementById('nomeUtilizador' + (index + 1)).value
});
});
You can have an empty array and on every click of addUser put a new object into the array. The object can have information related to the added user.
I have the following HTML and JS Code and the problem, that I'm not quite sure how to get the values from the input-boxes with the classes bti, bi, bp and bb when I click on the savebtn Button. I really hope someone can help me and give me a hint! best regards
$(document).ready(function() {
$('.savebtn').click(function() {
//how to i get the values?
});
});
<div class="modal-body">
<?php
for ($i=0; $i<count($barkeeperarr); $i++) {
?>
<div class="panel panel-primary" value="<?php echo $barkeeperarr[$i]->getID(); ?>" >
<div class="panel-heading clickablePanel">
<div class="panel-title"><?php echo $barkeeperarr[$i]->getFirstname().' '.$barkeeperarr[$i]->getLastname(); ?></div>
</div>
<div class="panel-body" style="display: none">
<div class="container-fluid">
<div class="row" value="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bti" placeholder="Gesamtumsatz">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bi" placeholder="Einladung">
</div>
<div class="col-xs-2">
<button type="button" class="btn btn-primary btn-sm savebtn">Hinzufügen</button>
</div>
</div>
<div class="row" style="margin-bottom: 3px">
<div class="col-xs-5">
<input type="text" class="form-control bp" placeholder="Personal">
</div>
<div class="col-xs-5">
<input type="text" class="form-control bb" placeholder="Bruch">
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
It will something like this,
$('.savebtn').click(function() {
$.each($('input:text.form-control'), function(){
if ($(this).prop('class') === 'bti'){
alert('form-control bti value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bp'){
alert('form-control bp value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bb'){
alert('form-control bb value = ' + $(this).val()));
} else if ($(this).prop('class') === 'bi'){
alert('form-control bi value = ' + $(this).val()));
});
});
You could store the values in an array and then process that array to add the values to your database.
For instance, let's create an array called values :
var values = [];
Then add an object to that array with the values of the respective classes bti, bi, bp and bb like :
jQuery(document).ready(function ($) {
var formControl = $(".form-control");
$('.savebtn').on("click", function () {
//how to i get the values?
for (var i = 0; i < formControl.length; i++) {
values[i] = {
name: formControl[i].className.split(" ")[1],
val: formControl[i].value
}
}
});
}); // ready
Notice we targeted the selector .form-control, which is a common class to all input fields.