Show alert if two Select2 selects are selected - javascript

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(); });

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>

Change <select> after reading <span> JS

So, I have a form with input and select. What I need to do is put another color in the camps that are required, and I'm trying not to change the html that I already have so I'm doing a function in JS.
For the input is easy cause I do the following function and it changes the color of the input cause the "data-val-required" is in the input.
$('input').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
$(this).css("background-color", 'rgb(250, 255, 189)');
$(this).attr('title', 'Este campo é obrigatório!');
}
});
But, for the select I can't do the same cause the "data-val-required" is in a span after the <select> . what I want to do is read the <span> and then color the <select> before it.
The html is something like this (the class="col-md-9" is the same for every camps of the form in the view)
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
I tried this but this colors all the <select> camps I have in my code and not just only the ones required.
$('span').each(function () {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
$('select').css("background-color", 'rgb(250, 255, 189)');
$('select').attr('title', 'Este campo é obrigatório!');
}
});
Is there anyway without changing HTML, to make the function read the span and change just the select before that span?
I'm searching childNodes but I can't seem to do that with class instead of id.
Thank you!
You had to select on direct child '~' ot type SPAN from SELECT with class form-control. For searching the SELECT look for a sibling from your SPAN with the desired class and type of SELECT.
$('select.form-control ~ span').each(function () {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
let select = $(this).siblings('select.form-control');
select.css("background-color", 'rgb(250, 255, 189)');
select.attr('title', 'Este campo é obrigatório!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span>Campo obrigatório2</span>
</div>
Try this.
$('span').each(function() {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
$(this).siblings('select').css("background-color", 'rgb(250, 255, 189)');
$(this).siblings('select').find('select').attr('title', 'Este campo é obrigatório!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span>Campo obrigatório2</span>
</div>

Show text based on option selected in dropdown

I have a dropdown like below.
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
I intend to show Text 1 when Feature 1 is selected, Text 2 when Feature 2 is selected and so on.
Any ideas on how can I do this with JS (or jQuery)?
P.S. Most existing solutions require input field rather than options field or maybe I am too noob. xD
Give the p tags the id as the value of the options, and show the p tag when selected option has the value which is equal to the id of p
$('p').hide();
$('#1').show();
$('select').change(function() {
$('p').hide();
var a = $(this).val();
$("#" + a).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div>
<p id="1">Text1</p>
</div>
<div>
<p id="2">Text2</p>
</div>
<div>
<p id="3">Text3</p>
</div>
<div>
<p id="4">Text4</p>
</div>
function display(){
var e = document.getElementById("dropDownId");
var index = e.selectedIndex;
if(index==0){
document.getElementById("first").style.display = 'block'
document.getElementById("second").style.display = 'none'
}
else if(index==1){
document.getElementById("first").style.display = 'none'
document.getElementById("second").style.display = 'block'
}
}
<label for="form_name">Title</label>
<select class="bootstrap-select" id="dropDownId" onchange="display()">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
</select>
<div id="first"><p>Text1</p></div>
<div id="second" style="display: none;"><p>Text2</p></div>
Please run this snippet..and check out your solution..
With pure javascript
let select = document.querySelector("select");
let divs = document.querySelectorAll("div");
let result = document.querySelector("#result");
function func1(par){
result.innerText = divs[par - 1].innerText;
}
div:not(#result) {
display:none;
}
<label for="form_name">Title</label>
<select class="bootstrap-select" onchange="func1(this.value)">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
<div id="result"></div>
You can use ids on your div that you want to show and change the value of your select with the ids you choosed
$("#select-panel").change(function(){
updateDisplay();
})
function updateDisplay(){
var idToShow = $("#select-panel").find(":selected").val() || "div1";
$(".subcontent").each(function(){
$(this).css("display",$(this).is("#"+idToShow) ? 'block' : 'none');
})
}
updateDisplay();
.subcontent{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-panel">
<option value="div1">1</option>
<option value="div2">2</option>
</select>
<div id="div1" class="subcontent">Text 1</div>
<div id="div2" class="subcontent">Text 2</div>

Adding clone element values with quantities

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>

Exchange text label to select value

I have a box entitled by label "Data sprzedaży":
<div class="formField">
<label for="invoice_invoice_sale_date">Data sprzedaży</label>
<?php draw_date_selects('invoice_sale_date', date('d'), date('m'), date('Y'))?>
<div class="clearer"></div>
</div>
I would like to put there dropdown with 3 options.
If I choose one of 3 options, it will replace the default label.
So the first thing you need to do is pass the option value to a variable, from there you can replace the text of the label with the option value:
$(function() {
$('select').on('change', function() {
labelText = $(this).val(); // Get value of selected option
$('label').text(labelText); // Pass selection option value into label
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="formField">
<label for="invoice_invoice_sale_date">Data sprzedaży</label>
<?php draw_date_selects('invoice_sale_date', date('d'), date('m'), date('Y'))?>
<div class="clearer"></div>
</div>
<select>
<option value="" disabled selected>Select an option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>

Categories