Adding clone element values with quantities - javascript

I'm creating a quote generator, and I have a product field that's cloneable.
Each option in the select tag has a value, but there is a quantity next to the product, so that the user can select a product and how many they want.
The field is also clone-able so that the user can have multiple products each with their own quantities.
I need to take the quantity for each row, multiply it by the value of the option and add all the rows together to give a total.
This is what I have so far
HTML
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
Javascript
$(".onChangePrice").change(function(){
var productTotal = 0;
$('.product').each(function(){
if (this.value != "") {
productEachTotal = this.value * $(".productQuantity").value;
productTotal += parseFloat(productEachTotal);
};
});
console.log(productTotal);
});
But its just returning NaN.
Any help would be appreciated!
Thanks

You need to use .val() to get the value.
$(".onChangePrice").change(function(){
var productTotal = 0;
$('.product').each(function(){
if (this.value != "") {
productEachTotal = this.value * parseInt($(".productQuantity").val());
productTotal += parseFloat(productEachTotal);
};
});
console.log(productTotal);
});

Try this one:
function calculateRowTotals(rowSelector, productSelector, quanitySelector) {
let rows = [].slice.call(document.querySelectorAll(rowSelector));
return rows.map(function(rowElement) {
var product = rowElement.querySelector(productSelector);
var quantity = rowElement.querySelector(quanitySelector);
if(!quantity || !product) return 0;
return parseFloat(product.value || 0) * Math.abs(parseFloat(quantity.value || 0));
});
}
function calculateTotal(rowSelector, productSelector, quanitySelector) {
return calculateRowTotals(rowSelector, productSelector, quanitySelector).reduce(function(total, rowTotal) {
return total + rowTotal;
}, 0);
}
// demo code
[].slice.call(document.querySelectorAll('.onChangePrice')).forEach(function(element) {
element.addEventListener('change', function(e) {
console.log('rows total: ', calculateRowTotals('.row', '.product', '.productQuantity'));
console.log('total: ', calculateTotal('.row', '.product', '.productQuantity'));
});
});
console.log(calculateTotal('.row', '.product', '.productQuanity'));
<div class="row">
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
</div>
<div class="row">
<select class="form-control onChangePrice add product" name="Product">
<option value="">Select...</option>
<option value="3300">Product 1</option>
<option value="4500">Product 2</option>
<option value="6000">Product 3</option>
<option value="8000">Product 4</option>
</select>
<div class="col-lg-3 col-md-3 col-sm-3">
<input class="form-control onChangePrice productQuantity" type="number" name="ProductQuantity" value="1">
</div>
</div>

Related

Select options based on another option selected

Im trying to select an option when i choose a specific option from list above. Any help how can achieve that?
Print of frontend
The main idea is, when i choose Field_Support, select option "94" from StardardTemplateID
My actual try:
$(document).ready(function () {
setTimeout(function () {
const Action = Core.Config.Get("Action");
const SupportedActions = ["AgentTicketNote"];
if ($.inArray(Action, SupportedActions) !== -1) {
if (Action === "AgentTicketNote") {
$('#DynamicField_QueueNote').on('change', function () {
const Option = $(this).val();
if (Option === '- Move -')
$('#Subject').val('');
else if (Option === 'Field_Support')
$('#Subject').val('Nota para Field');
else if (Option === 'Field_Support')
$("#StandardTemplateID").html("<option value='94'>dados_para_field</option>");
else if (Option === 'Helpdesk')
$('#Subject').val('Nota para Helpdesk');
else if (Option === 'Sistemas_Windows')
$('#Subject').val('Nota para Sistemas');
else if (Option === 'Networking')
$('#Subject').val('Nota para Networking');
});
}
}
})
});
Here's one way. Bake the value associations into the select option elements as data-attributes. Then just reference it on the change event.
$(document).ready(function() {
$('select#DynamicField_QueueNote').change(function() {
$('select#StandardTemplateID').val($(this).find('option:selected').data('link'))
$('#StandardTemplateID_Search').val($('select#StandardTemplateID').find('option:selected').text());
$('#Subject').val($(this).find('option:selected').data('subject'))
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="DynamicFieldText Modernize" id="DynamicField_QueueNote" name="DynamicField_QueueNote" size="1">
<option value="">-</option>
<option value="- Move -" selected="selected">- Move -</option>
<option value="Field_Support" data-link='94' data-subject='Nota para Field'>Field_Support</option>
<option value="Helpdesk" data-link='' data-subject='Nota para Helpdesk'>Helpdesk</option>
<option value="Sistemas_Windows" data-link='' data-subject='Nota para Sistemas'>Sistemas_Windows</option>
</select>
<hr>
<label>Subject</label>
<input type="text" id="Subject" name="Subject" value="" class="W75pc Validate Validate_Required" aria-required="true">
<hr>
<label for="StandardTemplateID">Text Template:</label>
<div class="Field">
<div class="InputField_Container" tabindex="-1">
<div class="InputField_InputContainer"><input id="StandardTemplateID_Search" class="InputField_Search ExpandToBottom" type="text" role="search" autocomplete="off" aria-label="Text Template:" style="width: 273.333px;" aria-expanded="true"></div>
</div>
<select class="Modernize" id="StandardTemplateID" name="StandardTemplateID" style="display: none;">
<option value="">-</option>
<option value="71">1ª_Tentativa_Contacto</option>
<option value="72">2ª_Tentativa_Contacto</option>
<option value="73">3ª_Tentativa_Contacto</option>
<option value="80">Acesso_VPN_atribuido</option>
<option value="94">dados_para_field</option>
</select>
<p class="FieldExplanation">Setting a template will overwrite any text or attachment.</p>
</div>
<!--
<select id='select1'>
<option> Choose...</option>
<option value='option1' data-link='100'> Option 1 (link to 100)</option>
<option value='option2' data-link='133'> Option 2 (link to 133)</option>
<option value='option3' data-link='94'> Option 3 (link to 94)</option>
<option value='option4' data-link='120'> Option 4 (link to 120)</option>
</select>
<select id='select2'>
<option></option>
<option value='94'>Template 94</option>
<option value='100'>Template 100</option>
<option value='120'>Template 120</option>
<option value='133'>Template 133</option>
</select> -->
You can create a conditional that checks the value of the select on change and then sets the value of the input if the value of the select equals the target value.
Using jQuery:
$(document).ready(function() {
$('#StandardTemplate').change(function() {
if ($(this).val() === '94') {
$('#text_template').val($('option[value="94"]').text())
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<select class="Modernize" id="StandardTemplate" name="StandardTemplate">
<option value>-</option>
<option value="71">1_Tentative_Contacto</option>
<option value="72">2_Tentative_Contacto</option>
<option value="73">3_Tentative_Contacto</option>
<option value="80">Accesso_VPN_atibuido</option>
<option value="94">dadios_para_field</option>
</select>
<label for="text_template">Text Template: <input name="text_template" id="text_template"></label>
</div>
Using Vanilla JS:
const sel = document.getElementById('StandardTemplate')
const input = document.getElementById('text_template')
sel.addEventListener('change', e => {
if(e.target.value === '94'){
document.getElementById('text_template').value = document.querySelector('option[value="94"]').textContent
}
})
<div id="parent">
<select class="Modernize" id="StandardTemplate" name="StandardTemplate">
<option value>-</option>
<option value="71">1_Tentative_Contacto</option>
<option value="72">2_Tentative_Contacto</option>
<option value="73">3_Tentative_Contacto</option>
<option value="80">Accesso_VPN_atibuido</option>
<option value="94">dadios_para_field</option>
</select>
<label for="text_template">Text Template: <input name="text_template" id="text_template"></label>
</div>

Select another dropdown value based on the previous dropdown selection

I am new to html javascript and trying to learn it. I am having an issue that when I select a value of a dropdown it will select another dropdown value when certain criteria matches.
If they Select the option 4 (takeout) from service_type dropdown, the counter dropdown will automatically selected the option 2 driveway. else user are free to select any value on both dropdown. Only if they select Takeout, it will make driveway selected and also make the table service option inactive.
if they select 1,2 or 3 from the Service type dropdown then option 1 will be enabled.
I need a javascript and no jquery. Please help me
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
You can use javascript like this:
function Checker(el){
const select = document.getElementById('counter');
removeOptions(select);
if(el.value == '4'){
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}else{
var option2 = document.createElement("option");
option2.text = "Table Service";
option2.value = "1";
select.add(option2);
var option1 = document.createElement("option");
option1.text = "Driveway";
option1.value = "2";
select.add(option1);
}
}
function removeOptions(selectElement) {
var i, L = selectElement.options.length - 1;
for (i = L; i >= 0; i--) {
selectElement.remove(i);
}
}
<div class="form-group col-md-12">
<select name="service_type" id="service_type" class="form-control form-control-line" onChange="Checker(this)" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service Fist</option>
</select>
</div>
Create two function one for create option base to first choise and second for remove option everytime function is called.
const firstSelect = document.querySelector('#serviceType');
const secondSelect = document.querySelector('#counter');
firstSelect.addEventListener('change', (event) => {
if (event.target.value === '4') {
secondSelect.value = '2';
secondSelect.disabled = true;
} else if (typeof event.target.value === 'string' && event.target.value.length > 0) {
secondSelect.disabled = false;
secondSelect.value = '1';
} else {
secondSelect.disabled = false;
secondSelect.value = '';
}
});
<div class="form-group col-md-12">
<select name="service_type" id="serviceType" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Service</option>
<option value="1">Dining</option>
<option value="2">Beverages</option>
<option value="3">Liquor</option>
<option value="4">Takeout</option>
</select>
</div>
<div class="form-group col-md-12">
<select name="counter" id="counter" class="form-control form-control-line" required>
<option value="" selected="selected" >Select Counter</option>
<option value="1">Table Service</option>
<option value="2">Driveway</option>
</select>
</div>
How does it work?
You need to select your Select controls from DOM and then listen to change event on first select, then you can get value from it and depending on your choice change value of Select #2. In order to disable ability to choose another option in second dropdown, you can disable it.

Show alert if two Select2 selects are selected

Let's say for example that I have two Select2 selects:
Select A
Option 1
Option 2
Select B
Option 1 Option 2
I want to capture an event when some option has been chosen for Select A and some option for Select B and then show a dismissible alert like alert alert-warning alert-dismissible fade show
I had thought to do it capturing the focus event but I have not been able to implement it, any ideas?
<label style="font-size: 20px;">SELECT A </label>
<select id="selectA" class="form-control" disabled>
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
<label style="font-size: 20px;">SELECT B </label>
<select id="selectB" class="form-control" disabled>
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
I would like to implement something like this:
$(function () {
'use strict';
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
})
The problem is that this function only compares if the two selected values are equal. I need and event for when the two selected values of the selects are different than the default value 'All', but they don't necessarily have to be equal values.
The problem lies within your conditional. You need to check whether the 2 selects are NOT equal to the default value "All".
inequality / not equal operator: !=.
Read more about expressions and operators here.
HTML:
<div class="row d-flext justify-content-center">
<div class="col-md-4">
<label style="font-size: 20px;">SELECT A </label>
<select id="selectA" class="multi-select form-control">
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="col-md-4">
<label style="font-size: 20px;">SELECT B </label>
<select id="selectB" class="multi-select form-control">
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
</div>
jQuery:
$('.multi-select').on("change", function() {
var selectValA = $('#selectA').val();
var selectValB = $('#selectB').val();
if(selectValA != "All" && selectValB != "All") {
alert('The value of the two selects are no longer "All"');
}
});
Snippet:
$('.multi-select').on("change", function() {
var selectValA = $('#selectA').val();
var selectValB = $('#selectB').val();
if(selectValA != "All" && selectValB != "All") {
alert('The value of the two selects are no longer "All"');
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row d-flext justify-content-center">
<div class="col-md-4">
<label style="font-size: 20px;">SELECT A </label>
<select id="selectA" class="multi-select form-control">
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="col-md-4">
<label style="font-size: 20px;">SELECT B </label>
<select id="selectB" class="multi-select form-control">
<option selected>All</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
</div>
Codepen example here.
I didn' test the code below. Just a kind of pseudo-code to describe what I meant in the comment.
// Handler get data from two select and check them
function handler() {
var data1 = $('#selectA').select2('data');
var data2 = $('#selectB').select2('data');
if (data1 && data2) {
alert("msg you want to show");
}
}
// trigger event only
$('#selectA').on('select2:select', function (e) { handler(); });
$('#selectB').on('select2:select', function (e) { handler(); });

function needs to wait until select tag's value selected

I have a function in my main.js needs to wait until some options selected on select tag. According to that, I will update the element. I tried to do it with addlistenerevent, but I could not succeed it. Any suggestions? Am I doing wrong?
var test = function() {
const langOptions = {
dummy: 0,
one: 5,
two: 8,
three: 2
};
var unit_1 = 1;
var selectSource ="";
var selectTarget = "";
var section = document.getElementById("unit");
var span_1 = '<span>Unit : </span>';
section.insertAdjacentHTML("beforeend", span_1);
var span_2 = '<span id= "span_2">' + unit_1 +'</span>';
section.insertAdjacentHTML("beforeend", span_2);
document.getElementById('source-lang').addEventListener('change', function() {
selectSource = $('source-lang').find('select').val();
for (const key of Object.keys(langOptions)) {
if (key === selectSource || key === selectTarget) { unitPrice *= langOptions[key];}
}
var element = document.getElementById('span_2').innerHTML = unit_1;
});
};
test();
<div id="langs">
<section class="container">
<div class="dropdown">
<select id="source-lang" style="background-color:#5e3080" name="source-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<div id="unit"></div>
</div>
</section>
</div>
I think that what you are looking for, is the onchange Event
function selectOne() {
const id = 'selectOne';
console.log(id, document.getElementById(id).value);
}
document.getElementById('selectTwo').addEventListener("change", function() {
console.log(this.id, this.value)
});
<p>Select One</p>
<select id="selectOne" type="text" onchange="selectOne()">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<!-- Or using addEventListener -->
<p>Select Two</p>
<select id="selectTwo" type="text">
<option value=a>a</option>
<option value=b>b</option>
<option value=c>c</option>
</select>
Use onchange Event
<select id="source-lang" style="background-color:#5e3080" name="source-lang" onchange="test()">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang" onchange="test()">

How to disable the option in dropdown by selecting in another dropdown using javascript

I want to disable the Grade 11 and Grade 12, if any BSIT, BSCS, etc (all BS) are selected; but if STEM, TOP, GAS and HUMSS are selected the Grade 11 and Grade 12 will be enabled and all BS will be enabled.
var disable_options = false;
document.getElementById('type').onchange = function () {
//alert("You selected = "+this.value);
if(this.value == "Student")
{
document.getElementById('course').removeAttribute('disabled');
document.getElementById('year_level').removeAttribute('disabled');
}
else
{
document.getElementById('course').setAttribute('disabled', true);
document.getElementById('year_level').setAttribute('disabled', true);
}
}
<div class="control-group">
<label class="control-label" for="inputPassword">Type:</label>
<div class="controls">
<select name="type" id="type" required>
<option></option>
<option>Student</option>
<option>Teacher</option>
<option>Staff</option>
<option></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Course Type:</label>
<div class="controls">
<select name="course" id="course" required>
<option></option>
<option>BSIT</option>
<option>BSCS</option>
<option>BSHRM</option>
<option>BSBM</option>
<option>BSTM</option>
<option>STEM</option>
<option>TOP</option>
<option>GAS</option>
<option>HUMSS</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Year Level:</label>
<div class="controls">
<select name="year_level" id="year_level">
<option> </option>
<option>First Year</option>
<option>Second Year</option>
<option>Third Year</option>
<option>Fourth Year</option>
<option>Grade 11</option>
<option>Grade 12</option>
</select>
</div>
</div>
Thank you for your response and it will help me for my project thank you.
Similar to what you have already, you need to add an onchange listener to the course element.
document.getElementById("course").onchange = function() {}
Then add ID's to the grade 11 and grade 12 options, so that you can find them in the DOM.
<option id="grade-11">Grade 11</option>
<option id="grade-12">Grade 12</option>
Finally, listen to the onchange value and modify the options accordingly.
document.getElementById('course').onchange = function() {
if (["BSCS", "BSIT"].indexOf(this.value) > -1) {
document.getElementById("grade-11").setAttribute("disabled", true);
document.getElementById("grade-12").setAttribute("disabled", true);
} else {
document.getElementById("grade-11").removeAttribute("disabled");
document.getElementById("grade-12").removeAttribute("disabled");
}
}
That's it! The option elements can take the disabled attribute and cannot be selected when the course element is "BSCS" or "BSIT"
Full code
var disable_options = false;
document.getElementById('type').onchange = function () {
//alert("You selected = "+this.value);
if(this.value == "Student")
{
document.getElementById('course').removeAttribute('disabled');
document.getElementById('year_level').removeAttribute('disabled');
}
else
{
document.getElementById('course').setAttribute('disabled', true);
document.getElementById('year_level').setAttribute('disabled', true);
}
}
document.getElementById('course').onchange = function() {
if (["BSCS", "BSIT"].indexOf(this.value) > -1) {
document.getElementById("grade-11").setAttribute("disabled", true);
document.getElementById("grade-12").setAttribute("disabled", true);
} else {
document.getElementById("grade-11").removeAttribute("disabled");
document.getElementById("grade-12").removeAttribute("disabled");
}
}
<div class="control-group">
<label class="control-label" for="inputPassword">Type:</label>
<div class="controls">
<select name="type" id="type" required>
<option></option>
<option>Student</option>
<option>Teacher</option>
<option>Staff</option>
<option></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Course Type:</label>
<div class="controls">
<select name="course" id="course" required>
<option></option>
<option>BSIT</option>
<option>BSCS</option>
<option>BSHRM</option>
<option>BSBM</option>
<option>BSTM</option>
<option>STEM</option>
<option>TOP</option>
<option>GAS</option>
<option>HUMSS</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Year Level:</label>
<div class="controls">
<select name="year_level" id="year_level">
<option> </option>
<option>First Year</option>
<option>Second Year</option>
<option>Third Year</option>
<option>Fourth Year</option>
<option id="grade-11">Grade 11</option>
<option id="grade-12">Grade 12</option>
</select>
</div>
</div>
First add value="value" to the <option> elements, so you can read the values consistently. ie: <option value="bsit">BSIT</option>, <option value="grade12">Grade 12</option>, etc.
document.getElementById('course').addEventListener('change', function(){
if(this.value && this.value.substr(0, 2) === 'bs'){
// if a "bs" option is selected, disable grade 11 and 12 options
document.querySelector('[value="grade11"]').setAttribute('disabled', '');
document.querySelector('[value="grade12"]').setAttribute('disabled', '');
}else{
// remove all disabled attributes from options
var disabledOptions = document.querySelectorAll('option[disabled]'),
i, l = disabledOptions.length;
for(i = 0; i < l; ++i){
disabledOptions[i].removeAttribute('disabled');
}
}
});

Categories