Deselect previously selected option on click - javascript

HTML <select> <option>s are selected by mouse click. Multiple selections are possible by CTRL+click or mouse click+drag. Deselection is possible by CTRL+click.
I would like to allow deselection of a previously selected option by clicking on it again. Any click then would toggle the selection.
var option = document.createElement('option');
option.onclick = function() {
if(this.selected) {
this.selected=false;
};
};
https://jsfiddle.net/L0L3378q/1/
Unfortunately, it seems that onclick is evaluated after the browser (Firefox in my case) handles the click itself, which results in "select" followed immediately by the "deselect" of my onclick function.
Now it would seem that all the browser does every time is "select" the option on click, which would render the function useless, if it never gets the actual selected state.
Is there a way to ensure that onclick is evaluated first, the brower's click is suppressed, or that the selected state can be tracked independently (custom property)?

as per your requirement try this
var option = document.createElement('option');
option.onmousedown = function() {
if (this.selected) {
this.selected = false;
return false;
}
else
{
this.selected = true;
return true;
}
};
option.innerHTML = "hey, hoh, gelato!";
var select = document.getElementById("sel");
select.appendChild(option);
hope it work for you

OK, specifically, on Windows 7 it doesn't work with Chrome, Firefox, Opera, Internet Explorer. On Android it doesn't even look like a pulldown menu, but that's just a jsfiddle problem, nothing to do with the code. I'll try on Windows 10 later this week.

The approach with a custom property seems to work:
https://jsfiddle.net/L0L3378q/3/
HTML:
<select id="sel" size="3" multiple="multiple">
<option>First!</option>
</select>
JavaScript:
var option = document.createElement('option');
option.myselected = false;
option.onclick = function() {
if (this.myselected) {
this.selected = false;
this.myselected = false;
}
else {
this.myselected = true;
};
};
option.innerHTML = "hey, hoh, gelato!";
var select = document.getElementById("sel");
select.appendChild(option);

Related

Change event triggering too early on select box

Here is a simplified version of my problem:
The HTML:
<select id="mySelect">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
The jQuery:
$('#mySelect').change( function() {
// do stuff
} );
The problem is that when I move my mouse cursor over the options, do stuff happens as I hover over one of the options, before I actually select the new option. How do I avoid this behaviour so that .change() is triggered only when I have finished choosing a new option in the select?
Edit 1: Further information
Apparently this code would not cause behaviour described. In the actual code the select boxes are being updated as further data is loaded via .get() and processed.
Edit 2: Actual function that updates a select box
This function is the one in my code that updates one of the select boxes after more data has loaded. The global variable padm_courses is an array of course objects, that have a code and name property used to populate the course filter select box.
function loadCourseFilter() {
var selected = '';
var sel = $('<select>').attr('id','padmCourseFilter');
$(padm_courses).each(function() {
sel.append($("<option>").attr('value',this.code).text(this.name));
});
if($('#padmCourseFilter').length) {
selected = $('#padmCourseFilter').val();
$('#padmCourseFilter').replaceWith(sel);
if(selected != '') $('#padmCourseFilter option[value="'+escape(selected)+'"]').prop('selected', true);
} else {
sel.appendTo('#padm_hub_filters');
}
$('#padmCourseFilter').change( function() {
processMCRsByCourse($('#padmCourseFilter').val());
var tables = $('.sv-datatable').DataTable();
tables.rows('.duplicate').remove().draw();
filterTheBlockFilter();
} );
}
Try changing your change event
$(document).on('change', '#mySelect', function() {
// do stuff
});
Okay, I found a solution. It seems that when triggered, the function loadCourseFilter was recreating the selectbox from scratch each time and overwriting the old one. This caused weird behaviour when hovering over one of the options.
A revised version of the function adds only new options, and does not update the filter if nothing was actually added...
function loadCourseFilter() {
var sel, output;
if($('#padmCourseFilter').length) {
var count = 0;
sel = $('padmCourseFilter');
output = [];
$(padm_courses).each(function() {
if($('#padmCourseFilter option[value="'+this.code+'"]').length == 0) {
count++;
output.push('<option value="'+this.code+'">'+this.name+'</option>');
}
});
if(count > 0) {
sel.append(output.join(''));
sortDropDownListByText('padmCourseFilter');
}
} else {
sel = $('<select>').attr('id','padmCourseFilter');
$(padm_courses).each(function() {
sel.append($("<option>").attr('value',this.code).text(this.name));
});
sel.appendTo('#padm_hub_filters');
}
$('#padmCourseFilter').change( function() {
processMCRsByCourse($('#padmCourseFilter').val());
var tables = $('.sv-datatable').DataTable();
tables.rows('.duplicate').remove().draw();
filterTheBlockFilter();
} );
}

Switchery as radio button, cannot toggle back

Now making playlist using switchery checkbox,
and already make it like a radio button,
but it cant toggle back.
How can i make Switchery back to idle state / unchecked state ??
>>> my Fiddle Demo <<<
Here is my js :
$(document).ready(function() {
//switchery
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
var switchery = new Switchery(html,{size: 'small',});
});
//detect change
$('input.pinmusic').on('change', function() { //detect change
// auto uncheck when selecting other checkbox
// but this is not working with switchery
$('.pinmusic').not(this).prop('checked', false);
});
});
PS : its already checked, but only switchery get stuck.
already browse some topic of switchery here but still error.
I'm late but, here's my solution:
var $switches = [];
var elems = Array.prototype.slice.call();
$.each(document.querySelectorAll('.js-switch'),function(i,html) {
$switches[html.name] = new Switchery(html,{size: 'small',});
});
$('input.js-switch').on('change', function () {
if (this.checked) {
$.each(document.querySelectorAll('input.js-switch:not([name="' + this.name + '"])'),
function (i, e) {
switcherySetChecked($switchers[e.name], false)
});
}
});
function switcherySetChecked(switcher, check) {
var curr = $(switcher.element).prop('checked');
var disabled = $(switcher.element).prop('disabled');
if (disabled) {
switcher.enable();
}
if (check) {
if (curr) {
$(switcher.element).prop('checked',false);
}
$(switcher.element).trigger('click');
} else {
if (!curr) {
$(switcher.element).prop('checked', true);
}
$(switcher.element).trigger('click');
}
if (disabled) {
switcher.disable();
}
}
It's pretty difficult to be sure of your problem, but if I understand well, you want to uncheck a radio button.
Well, you can't. A radio button is not made to be unchecked. The meaning of a pool of radio buttons is "choose exactly one of the following options". Unchecking a radio button would mean that the user chooses zero option, which is not allowed.
From Wikipedia's Radio button:
A radio button or option button is a graphical control element that allows the user to choose only one of a predefined set of options.
It is possible that initially none of the radio buttons in a group are selected. This unselected state cannot be restored by interacting with the radio button widget, though it may be possible through other user interface elements.
What you need to use if you want to be able to choose zero option, is a Checkbox.

Moving select option from one drop down to another does not work with a single option

I'm using the following code to move options from one drop down to another using jQuery:
$(document).on('change keyup', '.select-groups', function(){
moveSelectOptions($(this), 'available-groups', 'selected-groups');
});
var moveSelectOptions = function(elm, source, target){
var sourceId = source;
var targetId = target;
if (elm.attr('id') != sourceId) {
var sourceId = target;
var targetId = source;
}
return !$('#'+sourceId+' option:selected').remove().appendTo('#' + targetId);
};
I'm using both on change and on keyup events and everything works well, expect when there is only one option left in the dropdown, which in that case the option does not get moved over to the other dropdown.
I tried adding click event too but looks like it's conflicting with the other events.
Any idea how this can be resolved? Thanks.

how to disable select view in angular?

I want to disable the ui multiple select view whenever I select particaular value in my example "Nicole" .If I select "Nicole" it disable the ui select then user not able to select other option.
can we remove previous selected option when user select "Nicole" .? I want only if user select "Nicole" it disable the select view and remove other selected option .
plunker
http://plnkr.co/edit/eVXVzlRXJ4KUZaNjID6P?p=preview
$scope.OnClickSelect = function(item) {
$scope.multipleDemo.push(item.age)
}
$scope.OnRemoveSelect = function(item) {
var index = $scope.multipleDemo.indexOf(item.age);
$scope.multipleDemo.splice(index, 1);
}
I forked your plunker here.
index.html
I changed
ng-disabled="disable"
to
ng-disabled="isDisabled()"
demo.js
$scope.disabled = false;
$scope.OnClickSelect = function(item) {
if (item.name === 'Nicole') {
// Check to make sure there is a previous user to remove
if ($scope.multipleDemo.length > 0) {
$scope.multipleDemo.pop();
}
// Disable user picker
$scope.disabled = true;
}
$scope.multipleDemo.push(item.age);
}
$scope.isDisabled = function() {
return $scope.disabled;
}
Currently, when you select "Nicole" it disables the ui select picker and it removes the previously added user from the list multipleDemo. For some reason, it's removing the previously added user from multipleDemo list but it's not removing it from the UI. The digest cycle is not updating properly. Might it worth it to try it in your project to see if it gets updated properly there.
Hope this helps!
Modified OnClickSelect function call to OnClickSelect($item, $select) and added disabled in scope. $select variable will hepl us to manipulate the selected data.
use on-select="OnClickSelect($item, $select)" and ng-disabled="disabled" in ui-select tag.
$scope.disabled = false;
$scope.restrictNames = ["Nicole", "Michael"];
$scope.OnClickSelect=function(item, $select)
{
if($scope.restrictNames.indexOf(item.name) != -1){
$select.selected = [];
$scope.multipleDemo = [];
$scope.disabled = true;
}
$scope.multipleDemo.push(item.age);
}

RadioButton doesn't "receive" focus

I've pieced together some code to use in ASP.NET to prevent controls from losing focus on postback so a tab OR click of another control saves the users position and returns it.
In Page_Load I have the following:
PartNum_tb.Attributes["onfocus"] = "gotFocus(this)";
Department_tb.Attributes["onfocus"] = "gotFocus(this)";
PartWeight_tb.Attributes["onfocus"] = "gotFocus(this)";
Standard_rb.Attributes.Add("onfocus","gotFocus(this)");
Special_rb.Attributes.Add("onfocus","gotFocus(this)");
if (Page.IsPostBack)
Page.SetFocus(tabSelected.Value);
This is my Javascript (tabSelected is a hidden field):
<script type="text/javascript">
function gotFocus(control) {
document.getElementById('form1').tabSelected.value = control.id;
if (control.type == "text") {
if (control.createTextRange) {
//IE
var FieldRange = control.createTextRange();
FieldRange.moveStart('character', control.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
control.focus();
var length = control.value.length;
control.setSelectionRange(length, length);
}
}
}
</script>
The problem is when I tab or click onto one of the radio buttons, it returns focus to whatever the last control was instead which is unintuitive and confusing to a user. It does this because the RadioButton never gets focus, therefore the cursor position doesn't get updated. After extensive Google searching it appears that its not really possible to know when a RadioButton gains focus. Is there any solution known to even just work around this problem?
A solution may be adding a keypress event to the previous field and use the click event on the radios. Also, move the control.focus(); out of the if statement:
Javascript
function changeFocus(next) {
gotFocus(next);
}
function gotFocus(control) {
document.getElementById('form1').tabSelected.value = control.id;
control.focus();
if (control.type == "text") {
if (control.createTextRange) {
//IE
var FieldRange = control.createTextRange();
FieldRange.moveStart('character', control.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
var length = control.value.length;
control.setSelectionRange(length, length);
}
}
}

Categories