Trigger function on input event if selected text is within input - javascript

I've built a page where you can filter results by typing into an input box.
Basic mechanics are:
Start typing, input event is fired, elements without matching text begin hiding
If input becomes empty (or if you click a reset button), all elements are shown again
I have noticed a problem, though, when highlighting text. Say I type "apple" into the input. Then I highlight it, and type "orange."
If an element exists on the page containing "orange," but it was already hidden because I filtered for "apple," it does not show up. I have gathered this is because the input never truly empties; rather, I simply replace "apple" with the "o" from orange before continuing with "r-a-n-g-e." This means I get a subset of "apple" results that contain "orange," as if I had typed "apple orange."
What I really want to do is clear my input on the keypress for the "o" in "orange" before hiding nonmatching elements, so I'm effectively searching the whole page for "orange."
What I've tried so far
1: Set input value to '' on select event:
$('.myinput').on('select', function(){
$(this).val('');
});
This doesn't work because it just deletes my highlighted text, which is unexpected. I only want to reset the input on the keypress following the highlight.
2: Include an if statement in my input event that checks if there is a selection within the input:
$('.myinput').on('input', function(){
var highlightedText = window.getSelection();
if($(highlightedText).parent('.myinput')) {
//reset my input
}
});
This doesn't work because it seems to fire on every keypress, regardless of if there is any actual selection. (Are user inputs always treated as selected?)
3: Add a select event listener to the input element, and set a variable to true if there's a selection. Then, in my input event, check if the variable is true on keypress.
$(function(){
var highlightedText = false;
$('.myinput').on('input', function(){
if(highlightedText = true) {
//reset my input
}
//do stuff
highlightedText = false;
});
$('.myinput').on('select', function(){
highlightedText = true;
});
});
I really thought this one would work because a basic console log in the select function only fires when I want it to – when text in the input is highlighted, but not when other text is highlighted and not when text is entered into the input. But alas, when I change that to a variable toggle, it seems to fire on every keypress again.
So the question is: How can I fire a function on input only if text in my input is highlighted?
I have found this question that suggests binding to the mouseup event, but it seems like overkill to check every single click when I'm only worried about a pretty particular situation. Also, that solution relies on window.getSelection(), which so far isn't working for me.
I've also found another question that suggests to use window.selectionEnd instead of window.getSelection() since I'm working with a text input. I tried incorporating that into option 2 above, but it also seems to fire on every keypress, rather than on highlight.

This answer is not about text selection at all.
But still solve your problem to refilter text when highlighted text is being replaced with new input.
var input = document.getElementById('ok');
var character = document.getElementById('char');
var previousCount = 0;
var currentCount = 0;
input.addEventListener('input', function(){
currentCount = this.value.length;
if (currentCount <= previousCount){
/*
This will detect if you replace the highlighted text into new text.
You can redo the filter here.
*/
console.log('Highlighted text replaced with: ' + this.value);
}
previousCount = currentCount;
char.innerHTML = this.value;
});
<input type="text" id="ok">
<div id="char"></div>

I'll agree with others that you will save yourself some trouble if you change your filtering strategy - I'd say you should filter all content from scratch at each keypress, as opposed to filtering successively the content that remains.
Anyway, to solve your immediate problem, I think you can just get the selection and see if it is empty. You can modify your second attempt:
$('.myinput').on('input', function(){
// get the string representation of the selection
var highlightedText = window.getSelection().toString();
if(highlightedText.length) {
//reset my input
}
});
EDIT
As this solution seems to have various problems, I can suggest another, along the lines of the comment from #Bee157. You can save the old search string and check if the new one has the old as a substring (and if not, reset the display).
var oldSearch = '';
$('.myinput').on('input', function(){
var newSearch = $('.myinput').val();
if (newSearch.indexOf(oldSearch) == -1) {
// reset the display
console.log('RESET');
}
oldSearch = newSearch;
// filter the results...
});
This approach has the added benefit that old results will reappear when you backspace. I tried it in your codepen, and I was able to log 'RESET' at all the appropriate moments.

Related

Html select not changes option on click after jquery instant filter in jsp

I have 3 select tags on one page, generated from struts2 select tag. I am using a jQuery filter function that filters the select. One textfield for every select, but all of them use the same filter function. I have another js function that is called on onChange event.
The problem is that before adding this jQuery function i was filtering the lists with form submit and reload the page and now the filtration happens instant, but when i write a filtration criteria the select somehow the select loses focus and when i click an element no select happens, or better lets say is a kind of select: the element is circled with a dotted line, not selected with a blue filled square. The js is called, the form submitted, but with the old value. However, if i first click in the select where are no elements (empty zone) and then i select an element everything is ok. How can i jump over the firs click?
And now my code:
I. The jQuery filter function and the binding to the selects and textfields.
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append($('<option>').text(option.text).val(option.value));
}
});
});
});
};
$(function() {
$('#selectedClientId').filterByText($('#filterClient'));
$('#selectedLocationId').filterByText($('#filterLocation'));
$('#selectedViewPointId').filterByText($('#filterViewpoint'));
});
II. One of the selects:
<s:select size="10" cssStyle="width:220px;"
label="Select a client"
listKey="id" listValue="name"
list="clientSelectList"
name="selectedClientId" id="selectedClientId"
headerKey="-1" headerValue="Client List"
onchange="onChangeSelect()"
/>
III. The select's textfield:
Filter:<s:textfield name="filterClient" id="filterClient" size="15" autocomplete="off"/>
IV. The onChangeSelect():
function onChangeSelect() {
document.getElementById('deviceListForm').action = '<s:url value="/admin/displayDeviceListPage.action"/>';
document.getElementById('deviceListForm').submit();
}
In the image: in the first select is how looks the selected option after jquery filter and in the other 2 selects are "the good" selected options.
http://i.stack.imgur.com/TAJeY.png
EDIT: So, after the first response to this post (Thanks Amit1992) I started digging further. In Mozilla after the first click (after the frame or dotted line appears) a request is made to the server with the old selected item (or null if none selected), the page refreshes as nothing happened.
In Chrome, on the other hand, the first click does not make any request. It just selects (let's say) the select tag. And the second select makes a good request.
Short story:
mozilla: click 1 -> request with old selected value ->refresh -> no changes
chrome: click 1 -> selects the select tag and no request is made -> click 2 -> request as it should happen
IE - works ok. 1 click-> select and load page as it should . OK this really surprises me. at first I thought is useless to look in IE what happens.
EDIT2
After some digging i concluded that the problem is that when typing in the textfield the select loses focus. If I put $('#selectedClientId').focus();
in the filterByText function at the end of the $(textbox).bind('change keyup', function() the fist select is focused after every char written. But this gives me another problem. I can't write more than 1 char at a time. I have to click the textfield, write a char, click again, write a char etc.
May be this will help you. i did some modification in your code.
$(function() {
$('#selectedClientId').filterByText($('#textbox'), false);
$("#selectedClientId").change(function(){
alert("you have selected ++ " + $(this).val());
});
});
I used change() event of jquery instead of javascript onChange().
you can refer this link http://jsfiddle.net/amitv1093/q55k97yc/ and I recommend you to use jquery fully if you are using it.
kindly let me know if it will work.
I solved the problem by changing the whole filter function. The function with problem was taken from a stack overflow question response (How to dynamic filter options of <select > with jQuery?). The problem is, from what I concluded, that the $(textbox).bind('change keyup', function() line was changing the focus on the textfield, so the first click was changing the focus to the select tag. The new function, the one that works was taken from the same post, John Magnolia's answer:
$(document).ready(function() {
filterClient();
filterLocation(); //same as filterClient
filterViewpoint(); //same as filterClient
});
function filterClient(){
var $this, filter,
$input = $('#filterClient'),
$options = $('#selectedClientId').find('option');
$input.keyup(function(){
filter = $(this).val();
$options.each(function(){
$this = $(this);
$this.removeAttr('selected');
if ($this.text().toLowerCase().indexOf(filter.toLowerCase()) != -1) {
$this.show();
} else {
$this.hide();
}
});
});
}

Control Cursor Location on Focus in Form Field

I have a form with 4 fields. I want the first of the four to have the autofocus and be the first the user fills out. But then, either by tab or mouse or whatever, when the user gets to second field, I want the cursor to end up at the end of the string to start. There is a pre-filled string in that field.
I'm using Django so I have a form widget controlling the attributes. I can get the string to show up and even get the cursor to the end, but this always causes autofocus as well on that second field. I haven't managed to get both.
Here is code I'm using so far:
Django
field = forms.URLField(
widget = forms.URLInput(
attrs = {
'placeholder': 'enter field',
# call to javascript function - this works
'onfocus': 'add_string("field_id", "string")',
}
)
)
JavaScript:
// add string to element
function add_string(id, string) {
var input = document.getElementById(id);
input.value = string;
}
I've played around with various JS scripts but to no avail. I then found setSelectionRange and played around with this like so:
input.setSelectionRange(7, 7)
Where 7 would be end of the particular "string" in the onfocus JavaScript function call, but I could't get this to work...
Finally, I played around with some jQuery that looked like this:
// focus after string, no highlight
$(document).ready(function() {
var $field = $("#field_id");
var old_val = $field.val();
$field.focus().val('').val(old_val);
});
But this did the same thing: brought initial focus to second field and brought cursor to the end.
Any idea how I can do this, get both autofocus on field one but get cursor to jump to end of pre-filled string of field two on it's focus? Might be a nice trick if I knew how to do it.
You're almost there, you just need to fire your code when your form field is focused, instead of on document ready. In my tests it was necessary to add a zero timeout, because otherwise the field value remains selected:
$(document).ready(function() {
var $field = $("#field_id");
$field.on('focus', function() {
setTimeout(function() {
var old_val = $field.val();
$field.val('').val(old_val);
}, 0);
});
});
JSFiddle demo

"scroll" to the end of the input after js modifies input's value

I have a <input id="inp" type="text"> that user writes in, and sometimes uses suggests from a dictionary. When a suggest is selected I do:
var input = $('#inp');
input.val(input.val()+suggestedText+' ');
input.focus(); // that is because the suggest can be selected with mouse
everything works great, but when after adding a suggest that makes the resulting input.val() too long to fit in the edit field, the cursor is at the end of the string (which is good), but only the beginning of the string is visible in the edit field, so the cursor is hidden as well.
As soon as a key is pressed (a key that changes the value) the "scroll" goes to the end of the string hiding the beginning... How to trigger this behavior automatically, without having to press a key?
I have found a solution here - but it is not good as the whole input experience is changed...
Have you tried:
var input = $('#inp');
input.val(input.val()+suggestedText+' ');
input.focus(); // that is because the suggest can be selected with mouse
var height=input.contents()[0].outerHeight()
input.animate({
scrollTop:height
},'normal');
?
thank you all for answers, meanwhile I have found sth as well...
when using mouse to click the input lost focus (clik on sth else), and then regained it (thanks to input.focus()) - "scrolling" to the end, but when choosing a suggest was done with a keyboard, focus was never lost, and that is why it was not "scrolling" itself. I just simply added input.blur(), before input.focus(), now works like a charm... have a look at working example
http://46.4.128.78/input/
To make this work you need to set the focus() BEFORE you set the value. You can fix this in many ways, for example:
input.focus(); // that is because the suggest can be selected with mouse
var input = $('#inp');
input.val(input.val() + suggestedText + ' ');
Or this one:
function changeValue(element, newValue) {
element.focus();
element.val(element.val() + newValue + ' ');
}

How to lock the first word of a textarea?

Basically I need to create a textarea that is character limited, but will have a single word at the beginning, that they can't change.
It needs to be a part of the textarea, but I don't want users to be able to remove it or edit it.
I was thinking I could create a JQuery function using blur() to prevent the user from backspacing, but I also need to prevent them from selecting that word and deleting it.
UPDATE
I wrote this JQuery which seems to work great! However I like the solution below as it requires no Javascript.
<script type="text/javascript">
var $el = $("textarea#message_create_body");
$el.data('oldVal', $el.val());
$el.bind('keydown keyup keypress', function () {
var header = "Header: ";
var $this = $(this);
$this.data('newVal', $this.val());
var newValue = $this.data("newVal");
var oldValue = $this.data("oldVal");
// Check to make sure header not removed
if (!(newValue.substr(0, header.length) === header)) {
$(this).val(oldValue);
} else {
$(this).data('oldVal', $(this).val());
}
});
</script>
If you just want the textarea to show a prefix, you can use a label, change the position, and indent the textarea content. User will not notice the difference.
You can see how it works here: http://jsfiddle.net/FLEA3/.
How about just putting this word as a label next to the textbox? It may be confusing for the users not to be able to edit part of the text in the textbox.
Wouldn't it be better if you just alert the user that whatever he inputs in the textarea will be submitted with a "prefix" and then
show the prefix as a label before the textarea
add the prefix to the inputted text before submitting

Input box that converts text to buttons

I am trying to create a text input field that converts the input text to a "button" onblur. For example in the hotmail "new email page" when you enter email addresses it will make it into a little button-like object with a delete button when you enter a delimiter (semi-colon or comma). Anyone know how to do this?
I did a sort of workaround thing to what i want where i have a div with a border. In the div there is an input field with the borer invisible and a hidden button. I have a js function that takes the input value and makes the button visible with the value but this is not exactly what im looking for..
actually i just realised stackoverflow does this as well when im adding tags to the post
This is a multiple value field. Give a look at this one.
The feature is not so complex. It's an HTML list, and each value that you choose is converted into a LI node and appended to that list. The input field is inside the last LI, so its cursor can always be after the last choice. Besides, the input value is assigned to a hidden input, which can be used on the server-side as a comma-separated value.
Here's a simple way to fake it (and it looks like this is similar to what SO does for tags):
Create your text <input>, and make sure that its border and outline are both set to none.
Create a container for your tags (or buttons, or whatever) and put it next to the <input>.
Monitor the keydown event on the <input>; when the user tries to enter a "break" character (such as a semi-colon or comma), create the button, add it to the container, empty the <input>'s value, and prevent default (so that the "break" character isn't inserted into the tag, or left in the <input>).
That's the basic idea. Once you've done that, you can add event listeners/handlers to the buttons, or style them any which you'd like, etc.
Here's the simple example I cooked up:
var inp = document.getElementById('yourInput'),
tags = document.getElementById('yourContainer'),
breaks = {
186: 1, // semi-colon
188: 1 // comma
};
function createTag(txt) {
var elem = document.createElement('span');
txt = document.createTextNode(txt);
elem.appendChild(txt);
elem.className = 'tag';
tags.appendChild(elem);
}
function monitorText(e) {
e = e || window.event;
e = e.keyCode;
if (breaks[e]) {
e = inp.value;
inp.value = '';
createTag(e);
return false;
}
}
inp.focus();
inp.onkeydown = monitorText;

Categories