I have an HTML page where the end user can rank our items via a select box element.
See the fiddle to see a simple demonstration:
https://jsfiddle.net/Balkanlii/ghecv1j8/1/
I want to build a jquery script that changes the selected option if the same ranking is selected a second time (if the end user changes their mind, etc.). so:
Suppose item 1 is selected as number one, then when the end user comes to item 2 and decides to set this item as number one, he should only select option 1 here and other items should Select Automatically set to Level 2.
Suppose project 1 is selected as ranked first and project 2 is selected as ranked second. Then, suppose that when the end user checks item 3, he decides to set it to rank number one. Once he does this, item 1 should automatically rank second and item 2 should automatically rank third.
I have built a query that can be used successfully for this purpose, but the script is broken due to the following conditions:
How to fix it?
Also, is there a better way than mine, I'd like to know since how I do it is getting more complicated.
Any help would be greatly appreciated.
My jQuery script so far:
var previousValue = 0; $("select[class='myclass']").on('focusin', function(){ previousValue = $(this).val(); }); $("select[class='myclass']").on('change', function (event) { var prevValue = parseInt(previousValue); var selectedValue = parseInt($(this).val()); var selectedId = $(this).attr('id'); $('#' + selectedId + " option").removeAttr("selected"); $('#' + selectedId + " option[value=\""+selectedValue+"\"]").attr('selected', true); $("select[class='myclass']").each(function (index, element) { var eval = parseInt($('#' + element.id).val()); if (prevValue !== 0 && selectedValue !== 0) { if (eval >= selectedValue && (eval < prevValue) && element.id !== selectedId) { var b = eval + 1; if (b <= 3) $('#' + element.id).prop('selectedIndex', b); $('#' + element.id + " option").removeAttr("selected"); $('#' + element.id + " option[value=\"" + b + "\"]").attr('selected', true); } else if (eval <= selectedValue && (eval > prevValue) && element.id !== selectedId) { var b = eval - 1; $('#' + element.id).prop('selectedIndex', b); $('#' + element.id + " option").removeAttr("selected"); $('#' + element.id + " option[value=\"" + b + "\"]").attr('selected', true); } } else if (prevValue == 0) { if (selectedValue > 0) { if (eval >= selectedValue && element.id !== selectedId) { var b = eval + 1; if (b <= 3) { $('#' + element.id).prop('selectedIndex', b); $('#' + element.id + " option").removeAttr("selected"); $('#' + element.id + " option[value=\"" + b + "\"]").attr('selected', true); } } } } }); });
You can disable selected options in other fields by performing the following operations. Here's a screen recording of it working...