Make it 100% of all - javascript

I have 3 dropdown boxes, in which there are values of 10 to 100. I want user to select cumulative value of 100 from all dropdown boxes.
Which means, if I select 20 from the first dropdown box the next 2 dropdown should be left with the options of selecting total of 100
What I have done so far is here: CHECK IT HERE (JS FIDDLE)
HTML
<select id="foreign" class="me">
<option value="">Foreign Policy</option>
<option value="10">10%</option>
<option value="20">20%</option>
<option value="30">30%</option>
<option value="40">40%</option>
<option value="50">50%</option>
<option value="60">60%</option>
<option value="70">70%</option>
<option value="80">80%</option>
<option value="90">90%</option>
<option value="100">100%</option>
</select>
<select id="economy" class="me">
<option value="">Economy Policy</option>
<option value="10">10%</option>
<option value="20">20%</option>
<option value="30">30%</option>
<option value="40">40%</option>
<option value="50">50%</option>
<option value="60">60%</option>
<option value="70">70%</option>
<option value="80">80%</option>
<option value="90">90%</option>
<option value="100">100%</option>
</select>
<select id="social" class="me">
<option value="">Social Policy</option>
<option value="10">10%</option>
<option value="20">20%</option>
<option value="30">30%</option>
<option value="40">40%</option>
<option value="50">50%</option>
<option value="60">60%</option>
<option value="70">70%</option>
<option value="80">80%</option>
<option value="90">90%</option>
<option value="100">100%</option>
</select>
<br />
<span id="message"></span>
JavaScript
/*var total = new Array();
$('#foreign option').each(function() {
total.push($(this).val());
});
console.log(total);*/
var total = 100;
var ids = ['foreign', 'social', 'economy'];
var current_selected;
$('.me').change(function() {
current_selected = $(this).attr('id');
var socval = $('#' + current_selected + ' option:selected').val();
total = total - socval;
if ($.inArray($(this).attr('id'), ids) > -1) {
ids.splice($.inArray($(this).attr('id'), ids), 1);
}
for (var i = 0; i < ids.length; i++) {
$('#' + ids[i] + ' option').each(function() {
if ($(this).val() >= total) {
$(this).attr('disabled', true);
} else {
$(this).attr('disabled', false);
}
});
}
if (total <= 0) {
total = 100;
}
console.log(total);
ids.push(current_selected);
});
It is pretty much working, with some minor faults.
UPDATE
I think I solved it.
SOLVED FIDDLE
Thanks who helped.
Regards

Changing:
if ($(this).val() >= total) {
to
if ($(this).val() > total) {
solves the problem of only being able to select upto 90%
Working sample
Update
With regard to changing values, i'd probably take a forward-looking approach and reset the value of the forward selects. Something like:
var selectIds = ['first', 'second', 'third']
$('select').change(function(){
var currentIndex = $.inArray($(this).attr('id'), selectIds);
for(var i = currentIndex + 1; i < selectIds.length; i++)
{
$('#' + selectIds[i]).val("0");
}
});
This basically resets the value of select items in the chain that are further ahead than the current select box being used.
Working example
You'll also want to look ahead when doing the disables. You should only be disabling items in the select lists further down the chain from the current select. The first select list should always be able to choose any value and the following selects filtered based on that. This fits in well with the above approach.

I did another version of your code, plus fixing the bug
http://jsfiddle.net/rzBej/62/
$('.me').change(function() {
var totalSoFar = 0;
$('.me').each(function() {
totalSoFar += +$(this).val();
});
var tmp = 100 - totalSoFar;
$('.me').each(function() {
var $this = $(this);
$this.find('option').each(function() {
$this.prop('disabled', $this.attr('value') > tmp);
});
})
});​

Related

Iterate through select options with button click

this seems like something that should be incredibly easy to do but it's early in the morning and I'm drawing a blank.
I have a select that contains % values (for zooming) and as well as having this as a dropdown I want to have two buttons (+ and -) to iterate through the list.
So assuming I had:
<button id="minusButton">-</button>
<select id="zoomSelect" onchange="zoom()">
<option value="10">10%</option>
<option value="20">20%</option>
<option value="50">50%</option>
<option value="100" selected="selected">100%</option>
</select>
<button id="plusButton">+</button>
How would I go about switching up and down the select each time a button is pressed. Also ensuring it stops nicely on 100% and 10% (ie, no wrapping round or throwing an error if I keep pressing +).
Thanks very much!
$(document).on('click', '#minusButton', function() {
var selIndex = $("#zoomSelect").prop('selectedIndex');
if (selIndex != 0) {
$("#zoomSelect").val($('#zoomSelect option').eq(selIndex - 1).val());
zoom();
}
});
$(document).on('click', '#plusButton', function() {
var selIndex = $("#zoomSelect").prop('selectedIndex');
if (selIndex != $('#zoomSelect option').length - 1) {
$("#zoomSelect").val($('#zoomSelect option').eq(selIndex + 1).val());
zoom();
}
});
function zoom() {
console.log('zoomed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="minusButton">-</button>
<select id="zoomSelect" onchange="zoom()">
<option value="10">10%</option>
<option value="20">20%</option>
<option value="50">50%</option>
<option value="100" selected="selected">100%</option>
</select>
<button id="plusButton">+</button>
Click event can be written as such so as to change the value of select box, and trigger the zoom function accordingly.
You can use selectedIndex to work with the selected item like
var $zoom = $('#zoomSelect'),
len = $zoom.find('option').length;;
jQuery('#plusButton, #minusButton').click(function() {
var op = (this.id === 'minusButton' ? -1 : 1);
$zoom.prop('selectedIndex', function(idx, value) {
var x = value + op;
return x < 0 || x > len - 1 ? value : x;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="minusButton">-</button>
<select id="zoomSelect" onchange="zoom()">
<option value="10">10%</option>
<option value="20">20%</option>
<option value="50">50%</option>
<option value="100" selected="selected">100%</option>
</select>
<button id="plusButton">+</button>
Pure JS answer
Basically you need to get selectedIndex and set that index.
document.getElementById("zoomSelect").selectedIndex will get what index is currently selected and you can set that based on Plus or Minus click.
function zoom(isPlus) {
var zoomSelect = document.getElementById("zoomSelect");
var index = zoomSelect.selectedIndex;
var length = zoomSelect.length;
if (isPlus && (index < length - 1)) {
zoomSelect.selectedIndex = index + 1;
} else if (!isPlus && (index > 0)) {
zoomSelect.selectedIndex = index - 1;
}
}
<button id="minusButton" onclick="zoom(false)">-</button>
<select id="zoomSelect" onchange="zoom()">
<option value="10">10%</option>
<option value="20">20%</option>
<option value="50">50%</option>
<option value="100" selected="selected">100%</option>
</select>
<button id="plusButton" onclick="zoom(true)">+</button>
Found a duplicate of this with an answer - Choose option from select list using next/previous button with jquery
So this can be closed.

Populate dropdown from array on the basis of multiple dropdown values

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.

Compare select values and show alert if they match

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.

Duplicate Drop Down value across dropdowns

I have multiple dropdowns where people can select opening times for a store and I need to make it easy for people to enter the value in the first dropdown and then click to copy across all days;
Basically an onclick;
Copy selected value in monfrom and monto and assign values to other dropdowns.
<select name="monfrom" id="monfrom">
<option value="00:30">00:30</option>
<option value="01:30">01:30</option>
<option value="02:30">02:30</option>
</select>
<select name="monto" id="monto">
<option value="00:30">00:30</option>
<option value="01:30">01:30</option>
<option value="02:30">02:30</option>
</select>
<a href='#' onclick='JavascriptCode()'>Apply to all</a>
I hope someone can help.
You can use this, using plain javascript:
Javascript
function applyAll() {
var monfrom = document.querySelectorAll('select[name$="from"]');
var monto = document.querySelectorAll('select[name$="to"]');
for (i = 0; i < monfrom.length; i++) {
monfrom[i].value = monfrom[0].value;
};
for (i = 0; i < monto.length; i++) {
monto[i].value = monto[0].value;
};
};
window.onload = function () {
var apply = document.getElementById('apply');
apply.addEventListener('click', applyAll);
};
HTML
<select name="monfrom" id="monfrom">
<option value="00:30">00:30</option>
<option value="01:30">01:30</option>
<option value="02:30">02:30</option>
</select>
<select name="monto" id="monto">
<option value="00:30">00:30</option>
<option value="01:30">01:30</option>
<option value="02:30">02:30</option>
</select>
<button type="button" id="apply">Apply to all</button>
Demo
Since you seem to have jQuery, you can use this (although it's not faster):
function applyAll() {
var monfrom = $('select[name$="from"]');
var monto = $('select[name$="to"]');
monfrom.val(monfrom[0].value);
monto.val(monto[0].value);
};
$(function () {
$('#apply').on('click', applyAll);
});

Changing values in dynamically generated html using Jquery

As the title says, I'm wondering if there's a way to change the value of html items that are generated by jquery. Here's the code that I currently have:
the javascript
<script type="text/javascript">
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
$(".row:first").clone(true).insertAfter(".row:last");
$('#dateDueMonth['+i+']').val(curentMonth + 1);
})
});
</script>
My thought here was that after the row was cloned, I could then change the dropdowns content based upon it's current name, but obviously that's not working, and I've been unable to find a way to "hook" into dynamic html content.
and the base html
<select id="months" name="months">
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td><div id="showRows"><div class="row" id="row[]"><td class="td_alt"><select id="dateDueMonth[]" name="dateDueMonth[]" >
<option value="0">Select</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option selected value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="dateDueYear[]" name="dateDueYear[]">
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected value="2011">2011</option>
</select>
Now the generation of dynamic html and form submission works great. Gives me the data that I can use for my back end code. However having it so that I can increment the values in the various dropdowns as I see fit would make data entry by the folks using this page a whole lot easier, hence the issue.
To all that reply, thanks for your help with this jquery/JS noob.
EDIT: For this what I want to have is a form that can spawm multiples copies of the first line encased within the showRows div. When this is submitted, I want it to be able to collect that information in arrays for each select/input statement for the rows that are generated. For example if I selected two months, dateDueMonth, dateDueYear, and amount would be arrays in my form that would have two entries each. The current code does this, but by default it has the default elements for the dropdown menus set the same as the row of HTML that it is cloning.
Not sure what you want to do, but it should work like this
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
var arr;
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
arr=[$(".row:first").clone(true).insertAfter(".row:last")];
$('#dateDueMonth['+i+']').val(curentMonth + 1); //don't know why its here
arr[0].text("your value"); //apply the index you wanna change
})
});
Are you trying to achieve this kind of markup? Demo
<div id="showRows"><div class="row" id="row[0]"><select id="dateDueMonth[0]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[0]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
</div><div class="row" id="row[1]"><select id="dateDueMonth[1]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[1]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
...
This may be what you need. See my demo linked above.
for (var i = 1; i <= this.selectedIndex; i++) {
row = $(".row:first").clone(true)[0];
row.id = "row["+i+"]";
$(row).find("[id^='dateDueMonth']").attr("id","dateDueMonth["+i+"]").val((curentMonth + i) % 12 + 1);
$(row).find("[id^='dateDueYear']").attr("id","dateDueYear["+i+"]");
$(row).insertAfter(".row:last");
}
you cannot use ids as array in JavaScript. if you want, you have to put array index as well when you create element. or else just access the select element as bellow
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++) {
$(".row:first").clone(true).insertAfter(".row:last");
$('.row:last select').val(curentMonth + 1);
}
})
});
Working sample

Categories

Resources