Please guide me how can I make this code better.
var employees_json = [
{"id":"1","departments_id":"1","designations_id":"1","employee_types_id":"1","name":"name1"},
{"id":"2","departments_id":"2","designations_id":"2","employee_types_id":"1","name":"name2"},
{"id":"3","departments_id":"3","designations_id":"3","employee_types_id":"2","name":"name3"},
{"id":"4","departments_id":"4","designations_id":"4","employee_types_id":"3","name":"name4"},
{"id":"5","departments_id":"5","designations_id":"5","employee_types_id":"3","name":"name5"}
];
$("._employee_selection").change(function() {
update_employees();
});
function update_employees() {
var departments_id = $('#departments_id').val();
var designations_id = $('#designations_id').val();
var employee_types_id = $('#employee_types_id').val();
options = '<option value="">Select an option</option>';
$.each(employees_json, function(index, val) {
var selection = 0;
if (departments_id == '' || val.departments_id == departments_id) {
selection += 1;
}
if (designations_id == '' || val.designations_id == designations_id) {
selection += 1;
}
if (employee_types_id == '' || val.employee_types_id == employee_types_id) {
selection += 1;
}
if (selection == 3) {
options += `<option value="${val.id}">${val.name}</option>`;
}
});
$("#employees_id").html(options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id="departments_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Administration</option>
<option value="2">Data Entry</option>
<option value="3">Development</option>
<option value="4">Management</option>
<option value="5">Marketing</option>
</select>
<select id="designations_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Administration</option>
<option value="2">Data Entry</option>
<option value="3">Development</option>
<option value="4">Management</option>
<option value="5">Marketing</option>
</select>
<select id="employee_types_id" class="_employee_selection">
<option value="" selected="selected">Select an option</option>
<option value="1">Permanent</option>
<option value="2">contract</option>
<option value="3">Probation</option>
</select>
<select id="employees_id">
</select>
What is a better way to populate a dropdown on the basis of multiple dropdown selections?
This is basically a search filter and I'm not doing an Ajax to fetch data from filtered dropdowns.
I have a json array of employees with their department, designation and type in each element of array.
From the dropdown above selected in any combination, I'm trying to populate the employee list.
The following code is working for me, But I'm hoping for an easy and better way of doing it, which I'm not sure how can be done more efficiently.
Related
I'm trying to select an option from a category dropdown through a chrome extension with javascript and jquery. When I normally select an option from the first dropdown menu, the values ??in the second dropdown menu change based on my selection.
I tried to select an option with many different methods, here are most of them:
in jquery
$("#categorisation_1").val($("#categorisation_1 option").eq(4).val());
$('#categorisation_1').val('5: Object').change();
$('#categorisation_1').val('5: Object').dblclick();
$('#categorisation_1>option:eq(5)').prop('selected', true);
$("#categorisation_1").val('5: Object').trigger('change');
$('#categorisation_1').val('2: Object');
$('#categorisation_1>option:eq(5)').attr('selected', 'selected').trigger('change');
$('#categorisation_1').find('option:eq(3)').attr('selected', true);
in javascript
document.getElementById('categorisation_1').options[3].selected=true;
document.getElementById('categorisation_1').value = '9: Object';
document.getElementById("categorisation_1").selectedIndex = 1;
document.getElementById('categorisation_1').getElementsByTagName('option')[10].selected = 'selected';
document.getElementById('categorisation_1').value = '9: Object';
document.getElementById('categorisation_1').focus();
document.getElementById('categorisation_1').value = '5: Object';
document.getElementById("categorisation_1").options[2].selected = "selected";
document.getElementById('categorisation_1').getElementsByTagName('option')[5].selected = 'selected'
*******************
var select = document.getElementById("categorisation_1");
select.size = select.options.length;
******
document.getElementById('categorisation_1').setAttribute('size', 3);
********************
Array.from(document.getElementById('categorisation_1').options)
.filter(x => x.value === "9: Object")[0]
.setAttribute('selected', true);
Nothing worked... They change the value in the category dropdown but it doesn't trigger the changes in the next dropdown. Is there a way to select an option as if I was human, via javascript or Simulate pressing a button on the keyboard or any other method?
here is the source code of the first drop down menu
enter image description here
$(function()
{
$('#items').on('change', function()
{
var val = $(this).val()
if(val == '')
{
$('#sub_tems').html('');
}
else
{
$('#sub_tems').html(creaeOptions($(this).val()));
}
});
$('#items').val('2: Object').trigger("change")
});
function creaeOptions(val)
{
var data = [];
data['1: Object'] = '<option value="1">Sub Item 1 1</option><option value="2">Sub Item 1 2</option><option value="3">Sub Item 1 3</option>';
data['2: Object'] = '<option value="1">Sub Item 2 1</option><option value="2">Sub Item 2 2</option><option value="3">Sub Item 2 3</option>';
data['3: Object'] = '<option value="1">Sub Item 3 1</option><option value="2">Sub Item 3 2</option><option value="3">Sub Item 3 3</option>';
return data[val];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="items">
<option value="">Select</option>
<option value="1: Object">Item 1</option>
<option value="2: Object">Item 2</option>
<option value="3: Object">Item 3</option>
</select>
<select id="sub_tems"></select>
here is the answer if it can help anyone else thanks #Snm
const select1 = document.getElementById('select1');
const select2 = document.getElementById('select2');
select1.addEventListener('change', () => {
select2.removeAttribute('disabled');
});
setTimeout(() => {
select1.value = 2;
select1.dispatchEvent(new Event("change"));
}, 1E3);
<select id="select1">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select> -
<select id="select2" disabled="disabled">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>
I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!
Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>
I used the same class on all the dropdowns and then use only one event handler.
$('.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!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.
I'm hoping someone will point me in the right direction or give me an example. I'm trying to filter through this multidimensional json object using a form with four filter options (see below).
After the user makes their selections and hits the submit button the results of that product or service's details are displayed on the page (ie...link to that product, content of that product), there can also be more than one product or service to display based on the search filter. Can someone please help me out?
Here is my object:
var data = {
"Product":{"url":["http://www.google.com"],"mode":["gyro"],"modeOptions":["drop-controlled-descent","seated-wireline-steering","slickline-memory","surface-readout-ms","wireline-orientation"],"diameter":{"usa":"1.75","intl":"44.5mm"},"accuracy":{"usa":"0.5 deg","intl":"0.5 deg"},"temp":{"usa":"400F","intl":"204C"},"speed":{"usa":"250 ft\/min","intl":"76.2m\/min"}},
"Service":{"url":["http://www.google.com"],"mode":["gyro"],"modeOptions":["drop-controlled-descent","seated-wireline-steering","slickline-memory","surface-readout-ms","wireline-orientation"],"diameter":{"usa":"(2.2)","intl":"(55.9mm)"},"accuracy":{"usa":"0.15 deg","intl":"0.15 deg"},"temp":{"usa":"(400F)","intl":"(204C)"},"speed":{"usa":"600 ft\/min","intl":"182.9m\/min"}}
};
Her is my html form:
<form name="searchForm" id="searchForm">
<select name="diameter">
<option value="" selected="">Select One</option>
<option value="1.2">1.2</option>
<option value="1.75">1.75</option>
<option value="2.2">2.2</option>
</select>
<select name="accuracy">
<option value="" selected="">Select One</option>
<option value="0.15 deg">0.15</option>
<option value="0.5 deg">0.5</option>
<option value="1 deg">1</option>
<option value="2.5 deg">2.5</option>
</select>
<select name="temp">
<option value="" selected="">Select One</option>
<option value="257F">257F</option>
<option value="300F">300F</option>
<option value="400F">400F</option>
</select>
<select name="modeOptions">
<option value="" selected="">Select One</option>
<option value="surface-readout-ms">Surface Readout/MS</option>
<option value="wireline-orientation">Wireline Orientation</option>
<option value="memory-orientation">Memory Orientation</option>
<option value="slickline-memory">Slickline memory</option>
<option value="drop-controlled-descent">Drop – Controlled Descent</option>
<option value="drop–freefall-descent">Drop – Freefall Descent</option>
<option value="seated-wireline-steering">Seated Wireline Steering</option>
</select>
<input type="submit" value="submit"/>
</form>
Get TaffyDB. It is made for these sorts of things.
Try something like
var $form = $('#searchForm'),
$diameter = $form.find('select[name="diameter"]'),
$accuracy = $form.find('select[name="accuracy"]'),
$temp = $form.find('select[name="temp"]'),
$modeOptions = $form.find('select[name="modeOptions"]');
$('#searchForm').submit(function (e) {
e.preventDefault();
var diameter = $diameter.val(),
accuracy = $accuracy.val(),
temp = $temp.val(),
modeOptions = $modeOptions.val();
var selected = $.map(data, function (obj) {
return (!diameter || diameter == obj.diameter.usa) && (!accuracy || accuracy == obj.accuracy.usa) && (!temp || temp == obj.temp.usa) && (!modeOptions || $.inArray(modeOptions, obj.modeOptions) > -1) ? obj : undefined
});
//print result
console.log('found:', selected);
$('#result').html($.map(selected, function (val) {
return '<p>' + JSON.stringify(val) + '</p>'
}))
})
Demo: Fiddle
I'm trying to build a form with drop downs that will query a json object with jQuery and then display that product with its data on my html page depending on what was chosen in the drop downs.
Here is my json object:
var obj = {
"ProductOne":
{
"url":["http://www.google.com"],
"map":["test-one"],
"options":["test-one","test-three","test-four"],
"dim":{
"bam":"5",
"tin":"4"
},
"acc":{
"bam":"1",
"tin":"2"
}
},
"ProductTwo":
{
"url":["http://www.google-two.com"],
"map":["test-two"],
"options":["test-two","test-three","test-five"],
"dim":{
"bam":"6",
"tin":"9"
},
"acc":{
"bam":"8",
"tin":"6"
}
}
};
Here is my form:
<form name="searchForm" id="searchForm">
<select name="dim">
<option value="" selected="">Select One</option>
<option value="5">5</option>
<option value="4">4</option>
<option value="6">6</option>
<option value="9">9</option>
</select>
<select name="acc">
<option value="" selected="">Select One</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="6">6</option>
<option value="8">8</option>
</select>
<select name="options">
<option value="" selected="">Select One</option>
<option value="test-one">Test One</option>
<option value="test-two">Test Two</option>
<option value="test-three">Test Three</option>
<option value="test-four">Test Four</option>
<option value="test-five">Test Five</option>
</select>
<input id="button" type="button" value="submit"/>
</form>
You can filter with this:
var filteredProducts = {},
dim = $("select[name=dim]").val(),
acc = $("select[name=acc]").val(),
option = $("select[name=options]").val();
function valueInObject(object, value){
for(var key in object){
if(object[key] == value) return true;
}
return false;
}
$.each(obj, function(key, product){
if(
(option == "" || $.inArray(option, product.options)) >= 0 &&
(acc == "" || valueInObject(product.acc, acc)) &&
(dim == "" || valueInObject(product.dim, dim))
){
filteredProducts[key] = product;
}
});
console.log(filteredProducts);
alert(JSON.stringify(filteredProducts));
Then, you have the filtered products in the filteredProducts object, that has same structure as the original obj object.
Then you can traverse it and show it in a table or something.
Assuming you want to show them on a list, let's say you have:
<div id="filteredProducts"></div>
you would do:
$('#filteredProducts').empty(); //Clears previous results
$.each(filteredProducts, function(productKey, product){
$('<div class="title">'+productKey+'<br/>'+
''+ product.url + ''+
'</div>').appendTo('#filteredProducts');
});
It would add each product to the list.
Cheers, from La Paz, Bolivia