JS - compare select option then make it selected - javascript

We have several <select> fields that need to be set at the specified <option>. We have this "answer list" with UUID. Every <option> is evaluated: if the UUID is included at "answer list" then thats the <option> selected, otherwise we keep default "not available" <option> selected.
See below my current code, the comparison is the part I'm facing trouble.
JS code:
$('#severalStores .selectLimitInformation').each(function () { //Scan all the select fields
$(this).find("option").each(function () { //Search within every option
$.each(JSON.parse(answerList), function (item) { //Scan all "answer list"
//Compare values then choose value (not working)
if ($(this).option.value == item.expectedUUID)
$(this).val(item.expectedUUID);
else
$(this).val('0');
$(this).trigger('change');
});
});
});
HTML code:
<div class="row form-horizontal" id="severalStores">
<div class="col-md-6">
<div class="row form-horizontal">
<div class="col-md-4">
<label>Store AAA:</label>
</div>
<div class="col-md-8">
<select class="form-control selectLimitInformation">
#foreach (...) //data from ViewBag
{
<option value="#storeLimit.info">#storeLimit.description</option>
}
<option value="0">Not available</option>
</select>
</div>
</div>
<div class="row form-horizontal">
<div class="col-md-4">
<label>Store BBB:</label>
</div>
<div class="col-md-8">
<select class="form-control selectLimitInformation">
#foreach (...) //data from ViewBag
{
<option value="#storeLimit.info">#storeLimit.description</option>
}
<option value="0">Not available</option>
</select>
</div>
</div>
//Several other select
</div>
</div>

You don't need the nested loops. Put all the expected UUIDs in a Set. Then you can use the .has() method to test if the option value is in the set, and update the select value.
answerList = JSON.parse(answerList);
let expectedUUIDs = new Set(answerList.map(a => a.expectedUUID));
$('#severalStores .selectLimitInformation').each(function(i, select) { //Scan all the select fields
select.value = "0"; // start with a default
$(this).find("option").each(function(j, option) { //Search within every option
if (expectedUUIDs.has(option.value)) {
select.value = option.value;
return false; // stop looping over the options
}
});
});

Related

How to set validation in multi-drop down with one element being set by default in jquery

I have this code where I have to add a validation that whether 'ALL' option is displayed on multi drop down menu although all other elements will also be available in drop down menu or if some other element is selected from drop down then 'ALL' option will automatically be removed but will be available in drop down. Precisely, either 'ALL' or others get selected in multi drop down .
I am a bit new to jquery.
This is what I am trying:
$('#selectPlayerDropDown').change( function() {
console.log($(this).val()+"tttttt");
console.log($(this).val()=='ALL')
var sel = $('#selectPlayerDropDown').val();
if(jQuery.inArray( "ALL", sel)){
console.log("Well Well");
//sel.find("option:sel(0)").remove();
// $('#selectPlayerDropDown').children('option:not(:first)').detach();
}
console.log(sel+"///////////");
});
Here's the original code
if( $.scoreType == 'PLAYER') {
$(".selectPrintOnSingleOrMultiplePage").addClass('hide');
$('#printForAllPlayersDiv').addClass('hide');
$('#selectPlayerDropDown').find('option').remove().end();
$('#selectPlayerDropDown').append($('<option>', {
value : 'ALL',
text : 'All'
}));
$('#printOrderSelection').removeClass('hide');
$.each($.reservationAndPlayerData.playerData, function(index, object) {
$('#selectPlayerDropDown').append($('<option>', {
value : index,
text : object
}));
});
$(".player").removeClass('hide');
$(".selectPracticeCar").addClass('hide');
$('#selectPlayerDropDown').val('ALL').trigger('chosen:updated');
}
HTML CODE:
<div class=" player hide col-md-12 row">
<label for="select-players" class="col-md-6"
th:text="#{label.competition.score.player.select}">Select
players</label>
<div class="col-md-6">
<fieldset class="form-group">
<select class="form-control chosen-select"
id="selectPlayerDropDown" name="playerIds"
data-placeholder="Choose players ..." multiple="multiple">
</select> <label
class="jqueryValidationErrorClass selectPlayerDropDownLabel hide"
id="player-error" th:text="#{label.competition.player.choose}">Choose
Players</label>
</fieldset>
</div>
</div>
Try below code where you can check if ALL is selected or not and remove the ALL value from array of selected values of the dropdown.
$(document).ready(function(){
$('#selectPlayerDropDown').on('change', function(){
var value = $(this).val();
if(value!='ALL' && value.indexOf('ALL')>-1) {
var index = value.indexOf('ALL');
if (index > -1) {
value.splice(index, 1);
}
$(this).val(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class=" player hide col-md-12 row">
<label for="select-players" class="col-md-6"
th:text="#{label.competition.score.player.select}">Select
players</label>
<div class="col-md-6">
<fieldset class="form-group">
<select class="form-control chosen-select"
id="selectPlayerDropDown" name="playerIds"
data-placeholder="Choose players ..." multiple="multiple">
<option>ALL</option>
<option>Player 1</option>
<option>Player 2</option>
<option>Player 3</option>
</select>
<label class="jqueryValidationErrorClass selectPlayerDropDownLabel hide"
id="player-error" th:text="#{label.competition.player.choose}">Choose Players</label>
</fieldset>
</div>
</div>

onchange I would like to filter a drop down list that has a dynamic name

I am stuck with a complex javascript issue, please help.
There are 2 drop down lists, the name of the attributes are "dynamic". Users can add additional div's that logic is working fine so its not relevant to the issue I have now.
When the user selects a Product from the drop down list I want to display the year relevant to the Product Index. I am able to get the Product name and the suffix, but don;t know how to get or set the Fiscal Year attribute properties.
<script type="text/javascript">
function loadYear(obj) {
alert("The attribute name is " + obj.name);
var suffix = obj.name.match(/\d+/);
alert("the suffix is " +suffix);
alert(" how to get the name and value of Fiscal_Year attribute that changes dynamically");
}
</script>
<div class="row">
<div class="form-group">
<div class="col-md-10">
<select name="[0].Product" onchange="loadYear(this);">
<option value="15>Corporate HQ</option>
<option value="16">Data Campaign</option>
<option value="17">Digital Products </option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-8">
<select name="[0].FISCAL_YEAR">
<option value="15">FY15</option>
<option value="16">FY16</option>
<option value="17">FY17</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-10">
<select name="[1].Product" onchange="loadYear(this);">
<option value="15>Corporate HQ</option>
<option value="16">Data Campaign</option>
<option value="17">Digital Products </option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-8">
<select name="[1].FISCAL_YEAR">
<option value="15">FY15</option>
<option value="16">FY16</option>
<option value="17">FY17</option>
</select>
</div>
</div>
</div>
Instead of the name like [0].Product cant you dynamically create name like Product_0 and FISCAL_YEAR_0, that will be easy, because then in your loadYear function you can just do
obj.name.replace('Product_', '');
And that will give you the index of selected product.. then you can just use the javascript to access the year
Is it possible in your logic ?
Maybe something like this would work:
function loadYear(obj) {
alert("The attribute name is " + obj.name);
var suffix = obj.name.match(/\d+/);
alert("the suffix is " +suffix);
// Get the year value from the year selection
var selectedYear = obj.value;
// Find the corresponding FISCAL_SELECT element
var fiscalSelects = document.getElementsByName("[" + suffix + "].FISCAL_YEAR");
if (fiscalSelects != null && fiscalSelects.length > 0) {
// Set the value (assuming only one element exists)
fiscalSelects[0].value = selectedYear;
}
}
As requested, here is the last bit of that function implemented with jQuery:
// Get the year value from the year selection
var selectedYear = $(obj).val();
// Find the corresponding FISCAL_SELECT element
var fiscalSelects = $('[name="[' + suffix + '].FISCAL_YEAR"]');
if (fiscalSelects != null && fiscalSelects.length > 0) {
// Set the value (assuming only one element exists)
fiscalSelects[0].val(selectedYear);
}

Can't get values from SemanticUI multi dropdown

I'm trying to get the user selections from a multi-select dropdown but I don't seem to be able to get them. Here is the HTML:
<div id="content_dropdown" class="ui multiple search normal selection dropdown" style="border-radius: 0px;width: 100%;">
<i class="dropdown icon"></i>
<div class="default text">Dashboard widget, Improved reporting</div>
<div id="content_dropdown_menu" class="menu">
{% for content_tag in content_tags %}
<div class="item" data-value="{{content_tag}}">{{content_tag}}</div>
{% endfor %}
</div>
</div>
And here is the javascript I have tried:
var selectedValues = $('#content_dropdown').val();
var selectedValues = $('#content_dropdown').dropdown('get value');
Both of these return nothing even though the dropdown is populated.
I should also note that I had this working in a separate page, but I have been moving content onto 1 page, where I put this form into a modal. I'm not sure why this would affect it, just thought I'd point it out.
Thanks.
.dropdown('get value') won't work for multiple. You'll have to find a way to observe changes to dropdown. Here's how to do it in Aurelia:
form.html:
<select id="thickness" name="thick" multiple="" class="ui multiple dropdown selection" value.bind="thickness_selected">
<option value="">Выбрать</option>
<option value="100">100 mm</option>
<option value="150">150 mm</option>
</select>
form.ts:
export class form {
thickness_selected: number[] = [];
submit() {
const self = this;
for (let id of self.thickness_selected) {
console.log(id);
}
}
}
Try this:
var selectedValues;
$('#content_dropdown')
.dropdown({
action: function(text, value) {
selectedValues = value;
}
})
;

JQuery cloning of select areas and passing all to PHP Array

I need to pass cloned areas of a form to PHP via post an add then each to an array.
My code
<div class="input-main white_bg cloneneedsanalysis">
<div class="action-input clone-needs-analysis">
<div class="action-input-white-shorter">
<div class="inner-sub-title-less-padding">
<p>Audience Analysis</p>
</div>
<div class="col-md-12">
<div class="form-group">
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose ..." name="needs_analysis[]">
<option value="">-- Choose Audience Categories --</option>
<option value="536"> Finance - - Cash collection </option>
<option value="537"> IT - - Comms IT </option>
<option value="538"> Strategy - - Strategy team 1 </option>
</select>
</div>
</div>
</div>
<div class="action-input-plus-needs-analysis"> </div>
<div class="action-input-remove-needs-analysis"> </div>
</div>
</div>
The cloning works, but when I send to PHP via POST it will only capture the last one because they are all called called needs_analysis[]
So, when cloning how can I edit the name so that it's different and how can I get PHP to loop though each of the arrays?
My JQuery;
$(document).on('click', '.clone_needs_analysis_button', function(e) {
e.preventDefault();
$(this).closest('.clone-needs-analysis').clone().insertAfter('.cloneneedsanalysis:last');
$(this).closest('.action-input-plus').hide();
$(this).closest('.action-input-remove').removeClass('hidden');
My PHP;
$needs_analysis = array();
foreach ($_POST['needs_analysis'] as $key => $value) {
$needs_analysis[$key]['audience_id'] = $value;
$needs_analysis[$key]['created'] = $_POST['updated'];
$needs_analysis[$key]['created_by'] = $_POST['updated_by'];
$needs_analysis[$key]['solution_id'] = $_POST['solution_id'];
}
foreach ($needs_analysis as $needs_analysis_insert) {
$db->insert('design_needs_analysis', $needs_analysis_insert);
}
Your names for the multi-select should look like this:
needs_analysis[1][]
needs_analysis[2][]
You can either do this server-side, when generating the page, or rename them in JavaScript:
$('[name="needs_analysis[]"]').each(function(index) {
var currentElement = $(this)
currentElement.attr('name', 'needs_analysis['+index+'][]')
})
In order to loop through the values in PHP, you could do this:
foreach ($_POST['needs_analysis'] as $k=>$v) {
//$v represents the value array for a select element
foreach ($v as $k2=>$v2) {
//do something with each value
}
}

jQuery Check Other Select Elements Once This Is Selected

I have 3 HTML select under 1 div :
<div id="kurir_list">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<select disabled class="tarif">
<option select="selected"></option>
<option value="12000">JNE REGULER</option>
<option value="18000">JNE YES</option>
</select>
</div>
</div>
</div>
and I have this jquery :
$(".tarif").change(function() {
if ($(".tarif").is(':disabled')) {
alert ("yes you still have disabled element, next button disabled");
} else {
alert ("no, you don't have disabled element");
// check the other select value
$(".tarif").each(function() {
alert($(this).val());
});
}
});
every time a .tarif is selected, I need to check the other two select element value. whether it's still empty or not. but, my jquery code alert all 6 values from all select elements.
how to make jquery to be able to inform me, whether in #kurir_list still have empty select or not. thank you.
Perhaps you can try something like this, look at every select in your wrapper, if any have an empty val() then your variable will be true, in which case you can do something
var emptySelect = false;
$('#kurir_list select').each(function(){
if (!$(this).find('option:selected').val()) {
emptySelect = true;
}
});
alert(emptySelect);

Categories