Dynamically growing an array of text inputs (HTML/JavaScript) - javascript

I'm creating a data entry app for some in-house stuff.
My team needs to enter info about "items" which can have many "categories" and vice versa.
I need a quick way to let them enter an arbitrary amount of categories.
Here's my idea:
On the item entry page, I'll have it so that initially there's one text input for "categories" and if it's tabbed out of while it's empty, the input field is deleted (unless it's the only one) and focus skips to the next field. If it's not empty when it's tabbed out of and if it's the last input field in the array, then an additional "category" text input will be added and focused.
This way people can enter an arbitrary amount of categories really quickly, without taking their hands off the keyboard, just by typing and hitting tab. Then hitting tab twice to denote the end of the list.
First of all, what do you think of this interface? Is there a better way to do it?
Second of all, is there a jQuery (or something) plugin to do this? I've searched but can't find one. I searched scriptaculous/prototype and mootools too, with no luck.
I would obviously rather use something tried and tested than roll my own.
Any and all advice appreciated

First I'll try to address the problems commented on nickf solution.
To set the focus on the newly created input $copy.find(":text").focus(); will not work. The jQuery focus method only triggers the event, but does not call the underlying focus method.
You can set the focus with setTimeout(function(){$copy.find(":text").get(0).focus()}, 10); but:
setTimeout is needed in firefox or strange things will happen with the blinking cursor.
IE7 needs another input to focus when tabbing. I haven't found the way to set the focus on an input if the focus goes to the address bar. I suppose this will not be a problem because you will need at least a submit button.
To control shift-tab I've been trying to track the focused element, in order to skip the blurHandler when the focused element is a previous input, but the resulting code is really ugly so I'll post this and look for a better solution.
And last, you're asking what we think of this UI, and I think that a comma separated list of categories is easier to code an to fill in. :-)

it's actually not too difficult to implement that, even with vanilla JS (ie: no jQuery, prototype, etc), but everything is easier with jQuery, so I'll have a go at it using that:
Assuming a structure like this:
<form id="myForm">
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
...
</form>
Here's the JS
$('#myForm :text').blur(onBlurHandler);
function onBlurHandler() {
$row = $(this).parent();
if ($row
.nextAll(":has(:text)") // all following divs with a text element
.length == 0 // but there aren't any, we're on the last one
) {
if ($.trim($row.find(":text").val())) { // the text box isn't empty
$copy = $row.clone(true);
$copy
.find(":text") // get the new text box,
.val('') // remove any text in it
.blur(onBlurHandler) // and add the event handler (is this necessary?)
;
$copy.insertAfter($row);
} else if ($row.prev(':has(:text)').length) { // the text box is empty, and this one isn't the first row
$row.remove(); // get rid of the row.
}
}
}
Response to comments:
thanks for the answer! i've tried it but it doesn't seem to work as intended. i'm on mac firefox. if i tab off the last field, it adds the new one but focuses the address bar. i tried adding: $copy.find(":text").focus(); after the insertAfter line, but it doesn't change anything. any ideas?
also if i shift-tab the blurhandler doesn't know i'm going in the opposite direction. is there any way around that?
Hmm, I hadn't thought about that. What you could try doing is to put an element after all your text fields which can take focus (like a textbox which is rendered off-screen, eg: margin-left: -10000px). Add an onfocus handler onto that to see if the last row is empty, and if it is, then it would have been added just then by the onBlurHandler function, so pass the focus back to the last row. If the last row isn't empty, then pass the focus onto the next element (your submit button, probably). If there are issues with the last row not existing in the DOM yet, then put the above into a timeout.
(If this actually works) this should let your users tab backwards and forwards without hassle.

Related

Moving caret in the contents of a read-only div allowing for dynamic highlighting

I've been struggling with getting a field working properly. This field displays a lot of data, and the user wants to select and copy a large portion of it. The data is basically a big list and the user wants to select all entries below a certain point. The way that they achieve the selection is by highlighting a word or two in the first entry they want then pressing ctrl+shft+end to select everything to the bottom. This was working until a new feature on the page was added below the contents of the list. Now the hot key select also selects the contents of the rest of the page.
The current implementation is simply :
<div id='diff-contents'>[content here]</div>
<div id='trailing-content'>blah blah blah...</div>
I have tried a read-only input field:
<input id='diff-contents' value='[content here]' readonly/>
This works in Firefox to some extent however the contents contains HTML, and the input field show html literally, not rendered. In addition to that Chrome doesn't show a blinking caret and the hot keys do nothing, so the input field is sadly not viable for me in this situation.
How can I make a selectable field that maintains focus for the cursor and shows a blinking caret but is not editable using javascript, CSS, HTML, or JQuery?
Edit: jsfiddle example that should clarify a bit.
Look at these questions how to determine the current selection: Getting selected text in a browser, cross-platform
The next step is to create a new range which starts at the end tag of #diff-contents. With this information, you should be able to extend/modify the existing selection.
I suggest to either add a button to the UI or use JavaScript with a key-press handler to trigger this code.
With that, the correct amount of HTML should be selected. Users can then copy that into the clipboard with Ctrl+C.
#Aaron Digulla mentioned key listeners, and that got me thinking about simply stopping the events.
The diff-content element is still a div but it is set to editable. This gives both HTML rendering and a blinking caret.
$(this).keydown(function (event) {
if (document.activeElement.id == 'diff-content') {
if (!allowedKeys(event.keyCode)) {
//The only other key presses that should be processed are ctrl+c (keycode 67) and ctrl+a (65)
if (!event.ctrlKey || !(event.keyCode == 67 || event.keyCode == 65)) {
event.preventDefault();
}
}
}
});
The javascript adds a keydown event listener to the entire page. This is necessary since if you just add it to the element, the event has already propagated through the rest of the page and will still be processed, and this was causing funny issues for me. Next we check if it's the diff-content that is active since we want other input elements to still operate normally. Then we check if the key event is an allowed key (tab, home, end, arrows). And finally, check for ctrl+c and ctrl+a and allow those too. I tried event.stopPropogation() and event.stopImmediatePropogation(), and neither of those worked, but preventDefault did.
Lastly, I added style="outline-style:none" to the element so that the blue border would not appear when the element has focus.
The only issue that I have yet to resolve is that since it is editable, the browser still allows you to select and then right click to either cut or paste, which will allow you to alter the text.
Here is the final jsfiddle for what I am using: http://jsfiddle.net/wh3nzmj8/12/

How to remove trigger delay when calling ajax document?

Ok.
Question is simple.
I want to call some document via ajax when user changed the value of <input type="text">.
Not even just 'keyboard typing' event.
Include that way... you know, the tool tip...which showing last input result of user...
I mean, that tool tip... position is below the input box... showing user's recent typed results... you know that.. hard to explain. don't know its name...
Anyway, I wanna call ajax document right after user changed value of <input type="text">... Not even just keyboard typing, include via choosing one of that tooltips by mouse clicking...
Well, I was able to call document right after 'key typing event'..
This is the code :
sensitiveInput.addEventListener('keyup',function(){
callDocument_viaAjax();
}
So I tried similar method with above code.
This is the code :
document.addEventListener('mouseup',function(){
if(sensitiveInput.value !== '') {
sensitiveInput.onchange=function(){
callDocument_viaAjax();
}
}
});
But this code had some delay.. That means, Failed to realize the ui that I want to make.
When user changed the value of <input type="text" id="sensitiveInput"> via choosing one of the tooltips below input box, callDocument_viaAjax() wasn't executed.
I had to click on the document one more time to execute callDocument_viaAjax()....
I don't know why this happening.
And don't know how to solve this problem...
Please some one show me the mercy...
I solved this problem by using an event trigger 'input'.
'input' event detect change of input even if do not lose the focus from input field.
('change' effects only when input field loses focus)

Simple .on('keydown') jQuery event not responding until next key is pressed

I'm making a page for a friend and I have a hidden text field and when the user types the text is transposed into a div so that it looks like they're typing on the screen rather than in an input field.
Here is a link to the page: http://merkd.com/godis.php
Here is the function that I use to respond to the key strokes:
$('#hiddenInput').keydown(function() {
var input = $('#hiddenInput').val();
var html = '<div style="float: left;">'+input+'</div><div id="cursor">|</div>';
$('#typingArea').html(html);
});
The text-field is visible right now so that you can see the problem. When text is entered or deleted, it doesn't respond until the next keypress. So if I type a single letter, nothing shows up until I type the next letter.
I looked at the jQuery .on() documentation but I couldn't find anything on this. Any help is much appreciated.
P.S. I know it should be in a separate question, but is there an easy way to make a text-field always in focus? I want to make it so that no matter where the user clicks or whatever, if they type, the text will still show up.
Use .keyup() event because when you first press (keydown), the letter is never typed so the var html is getting previous value. For second part you can bind keypress event in document to focus your input field.

Running function only if a certain element isn't burring

im making an application that creates a text input where ever you click. I was having a problem where whenever you would click inside the field another text field would appear but i managed to fix that. I have one last major issue that I just can't solve. I know ou can't use blur() and focus() as arguments (though it would be nice) but i need to find a way so that after you enter text into the input field and out click, it just blurs the input box and doesn't create another until the user clicks again.
Just create a variable to keep track or only use a certain ID for the input you create, then check for that variable or input element before creation..
if(!$("#myDynamicInputElement").length){
//TODO: Create your element..
}

How to prevent multiple html selection box displayed on screen?

I have been working on the last bit of my php + ajax based datagrid project.Everything works as I designed except one thing : I cannot stop user opening multiple selection boxes...
Go my research page and use username "ChenxiMao" and password "accedo" to login(without double quotes).
Note that perhaps the images used in this datagrid would not be displayed when page is loaded for the first time(weird, I am trying to fix this, browser incompatibilities, perhaps).
If you double click on one cell in the "CONSULTANT" column, a html select box would be displayed, you can select one consultant to assign him to this task or unassign the consultant from this task. No problem for this.
The problem is : when user leaves this selection box OPEN, he/she can still open another selection box... My jquery code cannot stop people from opening multiple selection boxes.
You can ctrl-U to see the source code on this page, and check the content inside the "gridview-helper.js" for what I have been done.
I want to let user only open a single selection box. When he/she leaves the cell, the selection box should be closed, without changing the html inside...
Puzzled, screwed up for this afternoon...
Thanks for any suggestons in advance!
JavaScript is single-threaded, so you can add a mutex variable and check its value before opening a new select box.
At the top of gridview-helper.js:
var is_choice_visible = false;
In your double-click handler:
$(this).dblclick(function()
{
if (is_choice_visible)
return;
is_choice_visible = true;
...
For your select box, add an onblur handler which sets is_choice_visible back to false and deletes itself.
Unrelated tip: Growing a string in a loop is slow on older versions of Internet Explorer. It's more efficient to append to an array and join the array, e.g.:
var html = ["<select>..."];
for (var i in consultantnames)
{
html.push("<option>...</option>");
}
html.push("</select>");
return html.join("");
Have you tried using the onmouseout event on the cell, and removing the child dropdown box element if mouse out is triggered? Seems that should work.

Categories