I wrote an autocomplete type thingy that goes through divs and adds them to a list if their name/id is found. I am using an event handler that I found online that is called on any sort of input change. The issue that I am having is: When a valid div is found and added to the autocomplete list, and then the user continues to type, but is typing an invalid div name, the div name is removed from the list; HOWEVER, if no divs are found, the list persists but is blank.
A better way to explain is to try it out.
http://jsfiddle.net/ypz0zrzv/21/
Type "Test Unit" in the box, and then continue to type random letters. I am trying to get the now empty list to remove. The issue is that, when I implement such a feature, it is only going to happen after a second character is entered. This is because the handler checks the list on input change.
So if I type "Test Unit" it adds the div. If I type "Test Unita" it shows a blank autocomplete div. If I type "test Unitaa" now the autocomplete div will be gone. I am puzzled how to get the autocomplete to be blank immediately after it has found no divs.
Code problem in question
if ($('#autocomplete_list li').length === 0){
hide_remove($('#autocomplete'))
}
Your check for the auto complete was in the wrong location. It was being triggered by the wrong event.
I moved the check into its own function, in case you want to call this check at a later time:
function checkArray(){
console.log($('#autocomplete_list li').length);
if ($('#autocomplete_list li').length <= 0){
hide_remove($('#autocomplete'))
}
}
Then I added that checkArray() function into the hide_remove() function.
function hide_remove($div){
if ($div.length > 0){
$div.slideUp(250, function(){
$div.remove();
checkArray();
});
}
}
Here is a DEMO. Hope this helps!
Related
I have one more input box - ibox2, on the same page.
Problem - After doing anything on ibox1 and leaving value of length > 5 there, if I start typing in ibox2 the focus jumps back to ibox1.
It is that if loop with ibox1.focus() that is doing it. How could I remove focus entirely from ibox1 upon clicking outside and nullify the if loop and its statements.
I tried blurbut it did not work.
var ibox1 = $("#inputbox1");
$(document).on("change", ibox1,function(e) {
var valu = ibox1.val();
if(valu.length > 5){
#do something
ibox1.focus(); #used this as input box lost focus with each charater typed.
}
});
var ibox2 = $("#inputbox2"); #This is for google places autocomplete.
PS - Please do not tag it as a duplicate one, I have tried almost everything here, and only then I posted this. I shall remove it upon getting solution.
Respected mods, I followed a nice accepted answer and made a mistake about understanding $('document'), but I now got it cleared. That's the reason I am not deleting this question, even though I said I would, as it might help others. You guys, if
you feel, could delete this. Thanks.
The focus is jumping back to ibox1 because you are instructing your document to do so each time the onChange event is fired.
e.g.: $(document).on("change", ibox1, funct... where you are calling for ibox1.focus(); `.
Possible solution: bind your change event to the element of interest itself and avoid binding an event of such local significance to the whole document in the future.
Use a simple method to attach an event to inputs. Check below code it may help you.
(function(){
var in1 = jQuery('#input1'); // first input
var in2 = jQuery('#input2'); // second input
// On change of first input
in1.change(function(){
if(this.val().length > 5){
// do something
}
});
// On change of second input
in2.change(function(){
if(this.val().length > 5){
// do something
}
});
})();
I have a ASP.NET MVC application and I want to focus the first field in error. On submit, if the last field has error and user tries to submit the form, the focus is going to the last field in error instead of the first field. I tried multiple including the below:
$().ready(function() {
$("#Form").submit(function() {
$('.input-validation-error').focus();
$(".input-validation-error").each(function() {
$(this).focus();
});
});
});
Is there any solution where the user can always go to the first field in error.
No need to use each here and loop over all errors. You can just set the focus to first element with error class input-validation-error like:
$('.input-validation-error:first').focus();
#Palash has a good answer but I will explain why your code does not work so you understand it.
You need to leave the loop after the focus is set to the first item by returning false like below:
$(".input-validation-error").each(function () {
$(this).focus();
return false;
});
When you return false, you are instructing jQuery to stop processing the rest of the elements.Otherwise, it will keep looping and you will end up focusing the last item.
You can use eq method.
eq method reduces the set of matched elements to the one at the
specified index.
$('.input-validation-error').eq(0).focus();
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.
I'm currently working on a Qualtrics survey in which respondents have to solve a long list of anagrams, and then answer some demographic questions.
To make the anagram part easier, I've used a Loop and Merge block: the first field is the anagram to be solved, the second field is the solution of the anagram, and the survey can therefore check the answer of the respondent against the solution for each anagram.
As it is, the survey is working perfectly: however, I'd like to allow respondents to prematurely exit the loop by typing "EXIT" in the response field, and to redirect them to the next question block (the demographic questions).
This is typically something that is achieved using "Skip" logic: however, skipping to the end of the block does not do the trick (the loop restarts). I managed to redirect them to the end of the survey, but not to the demographic question block.
Is there a way to use javascript to jump to the demographic block or exit the loop and merge block prematurely? Am I missing a Qualtrics option that would do the trick?
If this is still relevant to you: I needed the same functionality and this is how I solved it: First, I define a helper variable, call it EndLoop, which I initialize to 0. Then I set up a function to change the value of EndLoop to 1 after people hit a button, additionally I add a display logic to the question in the loop showing them only if EndLoop is still 0 and hiding the questions as soon as EndLoop is 1.
This is a step-by-step instruction and the javascript and html code.
The bold stuff is what you need to do, the bulletpoints a more detailed instruction how to do it.
1. Before your loop-and-merge define an embedded data field called EndLoop and initialize it as 0.
Go to the Survey Flow Panel
Add a new element > select embedded data field
Name the field 'EndLoop'
Set its value t0 the number 0 by click on the link "set value now"
Make sure you move it before the merge-and-loop block
2. For each item in the loop set a display logic to show them conditional on 'EndLoop' = 0
Go to the options menu of each question in the loop
Select "add display logic"
Select "Embedded Data" from the first dropdown menu
A new type field opens > as name type EndLoop + select "is equal to" + type 0 as value
3. Insert a customized button into the page where people should be able to opt-out. The button runs a user-defined function called setEndLoop() onclick.
Click on the question where the button should appear
On the top-right of the question text select "html view"
The code I used is:
<input id="css-class-mybutton" onclick="setEndLoop()" value=" done " type="button">
If you want to change the button text, change the " done " in value = " done "
4. Define the function setEndLoop() using custom javascript to change the value of EndLoop to 1 and emulate a next button click
Go to the options menu of each question in the loop
Select "add JavaScript"
The code I used is:
/* Get the EndLoop variable */
var EndLoop = "${e://Field/EndLoop}";
Qualtrics.SurveyEngine.addOnload(function(){
/* hide previous and next button */
$('NextButton') && $('NextButton').hide();
$('PreviousButton') && $('PreviousButton').hide();
/* Function: on click on user-defined button -> change the field EndLoop */
var that = this;
setEndLoop = function(){
Qualtrics.SurveyEngine.setEmbeddedData('EndLoop', 1);
that.clickNextButton();
};
});
The button will not have the default style, thus, define a custom css to style your button to look like the buttons of your theme. The class name for the button I used here is id="css-class-mybutton", use .css-class-mybutton{ ... } in the css.
Hope that helps.
I know this is a bit late, but I had a similar issue and wanted to post an alternative solution. I used the loop and merge function, but I didn't want to have participants click on a button to exit the loop, instead I wanted to use a multiple choice question to exit the loop. This question was, "would you like to ask more questions?", with responses yes and no. If the participant selected "Yes" they would keep going through the loop and if they selected "No" they would exit the loop and go on to the next block of questions.
My first two steps are the same as those above.
1.Set up an Embedded data field named EndLoop and set the value to 1.
- in the survey flow panel select add an element. Then type in the name EndLoop.
- Then select set value now and set the value to 1.
- make sure that this is before your loop and merge block in the survey flow.
For each question in the loop and merge block use display logic to ensure that they only display when the embedded data element EndLoop is 1.
Now for the question "would you like to ask more questions?" add the following code in the add javascript area.
the javascript area can be found by clicking the advanced options button under the question number on the lefthand side of the screen. Select 'Add javascript...'
There will be some code already present...it should look like this:
Qualtrics.SurveyEngine.addOnload(function()
{
/Place Your Javascript Below This Line/
});
Basically I used event tracking to update the embedded data field EndLoop to the numerical value associated with the answer choice when the answer choice was selected. In this case the answer "Yes" had a value of 1 because it was the first option and "No" had a value of 2 because it was the second option. When "No" was selected, the embedded data field EndLoop was set to a value of 2. This then meant that none of the questions would display since they have display logic to ensure they only display when the EndLoop field is 1.
My entire code looks like this:
Qualtrics.SurveyEngine.addOnload(function ()
{
this.questionclick = function(event,element)
{
console.log(event, element);
if (element.type == 'radio')
{
var choiceNum = element.id;
if (choiceNum == 2)
{
Qualtrics.SurveyEngine.setEmbeddedData("EndLoop", choiceNum);
}
}
}
});
I used the second solution. Here's a minor correction for the script:
I wrote element.id.split('~')[2] instead of element.id, and it worked!
Qualtrics.SurveyEngine.addOnload(function ()
{
this.questionclick = function(event,element)
{
console.log(event,element);
if (element.type == 'radio')
{
var choiceNum = element.id.split('~')[2];
if (choiceNum == 2)
{
Qualtrics.SurveyEngine.setEmbeddedData("EndLoop", choiceNum);
}
}
}
});
Im just wondering how I go about catching the event when the user is typing into a text input field on my web application.
Scenario is, I have a contacts listing grid. At the top of the form the user can type the name of the contact they are trying to find. Once there is more than 1 character in the text input I want to start searching for contacts in the system which contain those characters entered by the user. As they keep typing the data changes.
All it is really is a simple type ahead type functionality (or autocomplete) but I want to fire off data in a different control.
I can get the text out of the input once the input has lost focus fine, but this doesnt fit the situation.
Any ideas?
Thanks
Use the keyup event to capture the value as the user types, and do whatever it is you do to search for that value :
$('input').on('keyup', function() {
if (this.value.length > 1) {
// do search for this.value here
}
});
Another option would be the input event, that catches any input, from keys, pasting etc.
Why not use the HTML oninput event?
<input type="text" oninput="searchContacts()">
I would use the 'input' and 'propertychange' events. They fire on cut and paste via the mouse as well.
Also, consider debouncing your event handler so that fast typists are not penalized by many DOM refreshes.
see my try:
you should put .combo after every .input classes.
.input is a textbox and .combo is a div
$(".input").keyup(function(){
var val = this.value;
if (val.length > 1) {
//you search method...
}
if (data) $(this).next(".combo").html(data).fadeIn(); else $(this).next(".combo").hide().html("");
});
$(".input").blur(function(){
$(this).next(".combo").hide();
});