Allow a user to click off select2 and keep free text - javascript

I currently have a select2 dropdown, version 4.0, that allows the selection of items as well as free text to be typed.
$("#dropdown").select2({
placeholder: "Select or enter a new item",
allowClear: true,
tags: true
});
I understand that typing free text creates a new option that can be clicked or will appear as an entry if the return key is pressed.
However clicking the newly entered option or hitting return are the ONLY ways for it to be accepted. This seems a little unintuitive as I know users will want to click onto other form elements or tab through the form.
Is there a way to allow a tag to be created just from de-focusing the form element?
I'm thinking something along the lines of having a .blur() event fire a selection or have select2:close cause a selection but I can't quite put it together.

It sounds like you are looking for the selectOnClose option. This will select the highlighted option when the drop down is closed.

Related

Automatic search for bootstrap-select with jQuery or JavaScript

As you can see on this link there is a bootstrap select box option which allows you to do live search for select box and find the option which you want.
The thing which i want and i don't have is searching on this table automatically with jQuery or JavaScript code.
If you didn't understand what i meant yet, there is an example :
$(".selectpicker").selectpicker('val', "test").selectpicker('refresh');
As you can see this code , this code will change the value of bootstrap select box option and then its will refresh it so select box value will change and the option on it which has value="test" will become selected and the bootstrap select will work well and you can deselect the option.
The thing which i want is search something after we refresh the select box with this code .selectpicker('refresh');.
Do you want to know why do i need something like this ? Because i using bootstrap select on my project and the select box has some options like Select All and when a user choose this option this code will be happen :
$(".selectpicker option").attr("disabled",true);
$(".selectpicker").selectpicker('val', "Select All").selectpicker('refresh');
And after this code happens the option of select box will be disabled and its ok but the problem is the select box have to refresh for showing that all of options disabled because all of them selected already and after refresh happens its will clear the search result and the search input will be still stay in the same thing which user searched in before but its not searching it anymore. And the thing which i want will fix this problem i mean i want to make it search the thing which user searched before after refresh.
The code which i looking for is something like this :
$(".selectpicker").selectpicker('search', "Some words").selectpicker('refresh');
Thanks.
$(document).on("change","#select-picker",function(){
$search_value="blob blob";
$("button[data-id='"+$(this).attr("id")+"']").next().children(".bs-searchbox").children("input[type='search']").val($search_value).trigger('propertychange');
});
// Bootstrap-select v1.13.9

How to prevent deselection of selected text on blur (focus lost) in html

I have been doing research on this simple sounding issue for a couple of days and I have not seen any result.
In a nutshell my problem is as follows: I would like to select text in a some input field, move focus to another field (or generally speaking some other element), but not lose my selected text.
Such a situation could correspond to a use-case in which I select text in a field, right-click and display a custom popup menu, but do not wish to lose focus of selected text, because I want to do some operations on the previously selected text.
A small code test sample would be (for my initial simple scenario - here I am forcing text selection when the second input field gains focus):
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="text1" size="20" value="Test1"/>
<input type="text" id="text2" size="20" value="Test2"/>
<script>
$('#text2').focus( function (evt) {
var target = $('#text1')[0];
target.select();
console.log('active/focused element: ' + document.activeElement.id);
});
</script>
</body>
</html>
I have been searching SO and web for a solution to this and have not seen much if any help.
I am not sure this is even really possible (due to the link between blur and selection lost and focus and selection). I have seen a style property called preventDeselect, in another SO answer - this does not work and I have not even such documentation or browser support for this.
I am quite struggling with this and would appreciate some help: even saying I can't do this at all or maybe some ways to go.
UPDATE:
Just for the record, my user scenario, which refers to text selection and context menu, is a common one (it slipped my mind to mention): just select some text in this page (or in an input type field) and right click to get the browser's default context menu - my scenario is different in that i want to use a custom menu, but with similar behavior to the browser's context menu - which normally allows to select some text, cut/copy the selection, navigate within the context menu without losing the selected text. So I think it should be possible somehow :) to do all these things with a context menu and still have your selection.
Attempting to answer this part of your question:
Such a situation could correspond to a use-case in which I select text
in a field, right-click and display a custom popup menu, but do not
wish to lose focus of selected text, because I want to do some
operations on the previously selected text.
For this use-case, I created a quick fiddle: http://jsfiddle.net/4XE9a/1/
Note: Am using the same getSelection function from #David's answer.
If you select any text and then right-click on the input, a custom popup menu appears. Click "option 1". You will find that the selection is not lost even though the focus has shifted to that anchor tag.
However, for the second part of your question regarding focus shifting to another textbox, #David's answer suffices.
Update: (after your comments)
Please see this updated fiddle: http://jsfiddle.net/783mA/1/
Now, when you select some text and right-click on the input it will show the custom popup menu with three options. Use tab to navigate and press space or click on the highlighted option. (Due to paucity of time I could not implement up/down arrow keys, but the concept remains the same)
This demonstrates your question in the comment that the selection is still not lost while navigating the menu.
Note: You are wanting to visually keep the selection highlight and not lose the selection while clicking anywhere else. Please note that this is not possible because text selection behavior is OS implemented. Browser, html etc do not play a role here. The text selection is lost as soon as you click anywhere outside the context of selection. This is because the system starts expecting a new selection as soon as you click anywhere outside. However, controls without text surface are exempt. Button, scrollbar arrows etc will not cause selection to lose.
To view this behaviour, in the fiddle, select some text and then click any dropdown on the left pane. The text selection is not lost, even visually for that matter.
This is why in the new fiddle above, I purposely used buttons to demonstrate.
You can save each selection in an interval, then retrieve it when you like. Here is an example that pulls the selection when the input has focus and clears the interval on blur:
function getSelection(elm) {
var start = elm.selectionStart;
var end = elm.selectionEnd;
return elm.value.substring(start, end);
}
$('input').focus(function() {
var self = this;
$(this).data('interval', setInterval(function() {
$(self).data('selection', getSelection(self));
},20));
}).blur(function() {
clearInterval($(this).data('interval'));
});
Now you can stuff like:
$('#text2').focus(function() {
console.log('selection in #text1 was: '+$('#text1').data('selection'));
});
Demo: http://jsfiddle.net/qCCY5/

Re-enable radio inputs with a clear function

I've tried a number of different things, including typical form reset and jQuery examples I've found across the web with no luck.
Screenshot:
The Goal:
I have a rankable list where a user is expected to rank items from 1-6 according to importance to them. If they select "2" for a certain row, we don't want to let them select "2" for another row. Here is the jQuery that's accomplishing this:
// Disable sibling radio buttons in form once an item is selected
$("input:radio").click(function() {
var val = $(this).val();
$(this).siblings("input:radio").attr("disabled","disabled");
$("input:radio[value='" + val + "']").not(this).attr("disabled","disabled");
});
The Issue:
This code seems to be working, with a couple of quirks.
The code correctly disables sibling rows, but if the user wants to change, they're stuck. They can click "2" on a row, then click "3" on the same row, but that leaves all other "2" and "3" options disabled completely.
The user needs a way to completely clear the form via a "start over" or "reset" button that apparently needs some special jQuery magic that I haven't been able to figure out yet.
I took code referenced in another post from this url, but it seems to only half work on my site. I notice on that fiddle link that if you click "1", it also disables "2" and "3" on the same row, which doesn't happen on my local development attempt. It does, however, permanently disable "2" in other rows if you were to click "2"...so I'm unsure why it works in the example but not my code (above).
There's got to be some easier way around this that I'm just not seeing here. I appreciate any help or code examples that might work along these lines.
Instead of outright disabling radio options that are not valid, you can instead take one of two approaches:
When the user clicks an option, validate the option on the fly, i.e., that "3" is not already selected when you click another "3". If not valid, then display a popup to user and clear it out.
When the user clicks an option, say a "3", then clear out all other "3" options so that only one is rated at that amount at a time.
Here is a sample code that will use method #2, clearing out all same value options whenever an option is clicked: http://jsfiddle.net/xy9wC/
From a users perspective, disabling these kinds of radio buttons may be very annoying to deal with as it forces the user to use two clicks instead of one while selecting something else.
A better alternative would be to "suggest" errors to the user, then enforce them on submit. For example, you could make the row with the invalid option red, then allow the user to discover the error and fix it themselves.
An even better way than that, use jQuery to create a sortable list.
http://jqueryui.com/demos/sortable/
-Sunjay03

Switchable selectable text

I have a table which is filled with data from a database. Some javascript allows a user to select certain rows and take some actions. I allow users to click one row and then to shift click another row to create a group (as well as alt-click to select/deselect individual rows).
The problem is I don't like how the text highlights when they shift click. Is there some CSS setting or javascript/jQuery solution to disable the selectable text (cross browser preferablly or just in firefox).
If possible I also want to be able to let the user select text to copy and paste sometimes or inside a textbox form input inside the same table so I would like to be able to enable and disable the selecting of text somehow. Any ideas?
this should do the trick:
$('td').disableSelection();
example:
http://jsfiddle.net/GhfuJ/1/
Here's one way you could completely disable text selection:
$("selector").bind($.support.selectstart ? "selectstart" : "mousedown", function(event) {
event.preventDefault();
});
This is how jQueryUI implements its disableSelection() method.
You could tailor your selector to exclude textarea elements, or wrap code inside the event handler with an if block that evaluates a boolean that gets set under certain circumstances (For example, you could turn on booleans when the user is clicking or shift/alt + clicking).

Clean and accesible Other option (Check box and text box)

When I have a set of either check boxes or radio buttons I often need to have an Other choice. This check box or radio button is very often accompanied by a text box where the user is supposed to fill out what this Other is.
How do you usually handle this set up? What kind of markup do you use? What do you require in your validation? Do you use java script for anything? For example:
How do you make the form accessible? Do you use and how do you use the label tag, for example.
Do you connect the check box and text box in any way with some javascript? For example, do you activate the text box when the check box is checked? Do you check or uncheck the check box automatically if the text box is filled out or cleared?
Do you let validation fail with error messages if the check box is checked but the text box is not filled out, or if the text box is filled out but the check box is not checked? Or do you just consider it not filled out and not checked?
Very unsure how to best deal with this issue, so any advice and examples are most welcome c",)
Typically when I have dynamic forms, I insert the input dynamically. That is, in the case of jQuery, I'll use .append('<input...') or some other similar function to actually insert the elements, and id it (or class it, depending), so that it can be easily .remove()-ed if the user decides they want to use another option instead. Validation is either handled via an onClick on an input button. If I'm feeling feisty, I'll go the AJAX route, and skip the <form> altogether.
I would definitely let the validation fail. They want "Other", and you want to know what "Other" is. If you don't care what Other is, then don't bother with the input box.
Edit: Might look something like this.
$('input[type="radio"]').click( function() {
if($(this).next().attr('name') != 'other' && $(this).attr('name') == 'other_input') {
$(this).after('<textarea name="other"></textarea>');
} else {
$('textarea[name="other"]').remove();
}
}
The click will react to any radio being clicked, and the if will make sure that it's only the "other" radio button that will react to the click, and that it will only react if there isn't already a textarea after it (so you don't get multiple textarea propogations).
On the processing side of things, you'll have to do a validation at first to see if other was checked, and to grab the input of the textarea if it was. You should probably use server-side validation for that.
Hope that gets you started.
I usually enclose my radio buttons in a label like this:
<label><input type=radio value=xyz name=stjames>Saint James</label>
this way the user can click on the text to trigger the button.
When deciding how to behave, I usually say to myself "what do you think the user expected when they did that..." and that often gives me the answer. So, upon click or Focus of the text box, turn on the radio that goes with it. This won't work if you've disabled the text box!
( ) US ( ) UK (*) Other [________________]
If the Other choice is a dangerous one (deleting data), though, I'd disable the text box until the user explicitly clicks Other. Then, the Radio drives the Text Box instead of the other way around. You want the user to have to go through another step in this case. It depends on the situation - think about what'll happen in each case.
I usually try to make it impossible or annoying for the user to do something 'wrong'. EG disable the OK button if something is inconsistent. Or, select the Other radio when the user types in text. If there's text in the text box but the radio buttons are set to something different, I'd usually just ignore the text. But if it's a serious/dangerous situation, you want to make sure the user's made up their mind; if you delete the text when the user chooses a different radio, that might piss them off but it might be appropriate if they should be careful.

Categories

Resources