I'm attempting to make a page that allows users to input text and it will automatically format the input -- as in a screenplay format (similar to Amazon's StoryWriter).
So far I can check for text with ":contains('example text')" and add/remove classes to it. The problem is that all of the following p tags inherit that class.
My solution so far is to use .next() to remove the class I added, but that is limited since there might be need for a line break in the script (in dialogue for instance) and that will remove the dialogue class.
$('.content').on('input', function() {
$("p.input:contains('INT.')").addClass("high").next(".input").removeClass("high");
$("p.input:contains('EXT.')").addClass("high").next(".input").removeClass("high");
});
I can't get || to work in the :contains parameter either, but that's the least of my issues.
I have a JS fiddle
I've worked on this for a while now, and if I could change only the node that contains the text (INT. or EXT. in this example) and leaves the rest alone that would work and I could apply it to the rest of the script.
Any help would be appreciated, I'm new to the stackoverflow so thank you.
See the comments in the code below for an explanation of what's going on.
Fiddle Example
JQuery
var main = function(){
var content = $('.content');
content.on('input', function() {
$("p.input").each(function() {
//Get the html content for the current p input.
var text = $(this).html();
//indexOf will return a positive value if "INT." or "EXT." exists in the html
if (text.indexOf('INT.') !== -1 || text.indexOf('EXT.') !== -1) {
$(this).addClass('high');
}
//You could include additional "if else" blocks to check and apply different conditions
else { //The required text does not exist, so remove the class for the current input
$(this).removeClass('high');
}
});
});
};//main close
$(document).ready(main);
I am trying to setup an interchange using two texts boxes with a command button in between.
The idea is you type a reference/code in the left hand text box, click the button and it generates an alternative reference/code in the right hand text box.
The point being the user can check alternate bearing references if they can't find what they are looking for with the one they have.
The code I use so far is:
<script type="text/javascript">
oldRef = new Array ("Z582","T608","A173");
newRef = new Array ("C850","S708","X449");
function convert()
{
document.getElementById("v2").value = "";
for (index=0 ; index < oldRef.length ; index++)
{
if ( document.getElementById("v1").value == oldRef[index] )
document.getElementById("v2").value = newRef[index];
}
}
</script>
V1 and V2 refer the the text box ID.
This works with the text boxes but I don't know how to incorporate the command button into this so that they need to click the button in the middle for it to generate.
Any suggestions would be much appreciated.
Best
Will
Its pretty Easy stuff what you need to do is to use onclick of the button like this
document.getElementById('button').onclick = function () {
document.getElementById("v2").value = "";
for (var index=0 ; index < oldRef.length ; index++) {
if (document.getElementById("v1").value == oldRef[index])
document.getElementById("v2").value = newRef[index];
}
}
Here is a demo
I hope this is waht you want....
So essentially there are two things that you need to accomplish what you asked. You need to create a element within your HTML, in this case a button. You then need to catch the event that you want to catch from that element and then execute you convert function.
This is one example of accomplishing this:
So create an button within your HTML
<button id="btn_command">Command</button>
Then in Javascript you want to target that button and add an event listener to that button. In the example the below the variable var btnCommand is set to the html button by using the getElementById method to get that button with that id. Then we add and event listener to that element that when clicked it executes your convert function.
var btnCommand = document.getElementById ("btn_command") ;
btnCommand.addEventListener("click", convert, false) ;
If you want to use jQuery you would do something like this.
$('#btn_command').on('click', function() { convert(); });
Here is another quick and dirty way to just test you button with your function. It is not a best idea to mix your javascript inline with your html but just to test your button and if your convert function is doing that you think you could just say
<button onClick="convert()">Command</button>
Well there are few ways to accomplish what you asked. Happy Coding!
For example, i have a div which users can type into it. i would like to place shortcuts so when the user inputs the word pi. The output would be the symbol π. Or if the user inputs sqrt then they would get this symbol inf then the output would be ∞. and even when the tab button is clicked to indent a couple of lines. I have not seen a web app that does this yet so any help would be appreciated.
There's some extensive key tracking + field updating you can do to accomplish this, or you can get a jQuery plugin that already does something similar (if not exactly) and modify it to accomplish the same task.
This might be what you are looking for though:
http://code.google.com/p/js-hotkeys/wiki/about
You could simply use a replace. See JSFiddle demo here
$('.test').keydown(function (event) {
if ($('.test').val().contains("pi")) {
var newVal = $('.test').val().replace("pi", "π");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
else if ($('.test').val().contains("inf")) {
var newVal = $('.test').val().replace("inf", "∞");
$('.test').val(newVal);
//Place Cusor at the end of the div if using editable div
}
});
In this sample I am using an input. You can change that to div
I am making an application which makes use of context menus and has selection. Right now i can select 1 element, but what i want to do is to ctrl+click to allow me to say append the elements into an array for the selection of MULTIPLE elements simultaneously. That way i can affect the attributes of N things at the same time.
I Need it to be something like Control+Clicking, if there was a better idea, i could be interested. Maybe Shift+click but that has the general understanding of selecting everything ebtween X and Y, where as users are more familiar with clicking individual items with ctrl.
I know how to do the append thing, but i wasnt sure how to do the:
var ev = mouse||window.event;
var t_sel = ev.target || ev.srcElement;
...
$('.item').click(function(e) {
if (e.ctrlKey || e.metaKey) {
// required code to make selection
// propably, add class to item to style it like selected item and check hidden checkbox
$(this).toogleClass('selected');
$(this).find('input[type=checkbox]').attr('checked', !$(this).find('input[type=checkbox]')('checked'));
}
});
This will allow you to detect a control click:
$(document).click(function(e) {
if(e.ctrlKey) {
//You do your stuff here.
}
});
I've used shiftcheckbox to have the ability to select a range of checkboxes in a grid.
The code is available so you can alter it to fit your needs. You may also use it as inspiration for a functionallity that suits you.
https://github.com/nylen/shiftcheckbox
I'm creating a <select> replacement using jQuery to replace it with divs and links.
Now I want to filter it when I start to type something with the new select open.
Like Google Translate does on the language selector.
Do you have any advice how do i proceed?
I started something with:
$(document).bind('keypress', function(event) {
//...
});
But I capture only single keys, not the whole typed string.
Important:
I don't have an <input /> to detect the keypress or keyup events on it
I prefer not to create this <input /> since I want to use only <div>'s and <a>'s on the "new select"
Lately I'll need to navigate on the open select with arrow keys + enter to select the option with my keyboard
You could achieve this by 'listening' about what is pressed on the window, and then detecting the particular letter/string pressed, search through items list and if you find it change its css properties or add a new 'selected' class i.e. (demo => http://jsfiddle.net/steweb/mC6tn/ ..try pressing whatever :) and added after something found press left or right btns, or enter) :
JS: (supposing that each element you want to find something into and select it has class 'elem')
var whatYouAreSearching = $('<div class="searching-string"></div>'); //just to see what string you're typing
$(document.body).append(whatYouAreSearching);
function search(what){
what = what.toLowerCase();
$('.elem').removeClass('selected'); //reset everything
$.each($('.elem'),function(index,el){
if($(el).html().toLowerCase().indexOf(what) > -1){
$(el).addClass('selected');
return false; //found, 'break' the each loop
}
});
}
var letterPressed = [];
var timeOutResetLetters = null;
$(window).keypress(function(e) {
clearTimeout(timeOutResetLetters); //clear timeout, important!
timeOutResetLetters = setTimeout(function(){ //if 500 ms of inactivity, reset array of letters pressed and searching string
letterPressed = [];
whatYouAreSearching.html('');
},500);
letterPressed.push(String.fromCharCode(e.keyCode)); //look at the comment, thanks Niclas Sahlin
whatYouAreSearching.html(letterPressed.join('')); //show string
search(letterPressed.join('')); //and search string by 'joining' characters array
});
EDIT added left/right/enter keys handling
$(window).keydown(function(e){ //left right handling
var currSelected = $('.elem.selected');
if(e.keyCode == "37"){ //left, select prev
if(currSelected.prev() && currSelected.prev().hasClass('elem')){
currSelected.prev().addClass('selected');
currSelected.removeClass('selected');
}
}else if(e.keyCode == "39"){ //right, select next
if(currSelected.next() && currSelected.next().hasClass('elem')){
currSelected.next().addClass('selected');
currSelected.removeClass('selected');
}
}else if(e.keyCode == "13"){ //enter
$('.entered').remove();
$(document.body).append(currSelected.clone().addClass('entered'));
}
});
You can try using jQuery UI's autocomplete
How to do what you asked
Each time the keypress event is triggered on the document, keep a record of the character that was typed, either in a variable (accessible from the global scope or in a closure) or in an element on the page (you may choose to use display: hidden; if you don't want this to be visible to the user).
Then, do a pass over the elements in your dropdown and hide those that don't contain/start with the string you've built from individual keystrokes.
What's actually recommended
Use an input element to contain the user's typed keystrokes, and let the user see the element.
Why?
Because it's an interaction behavior users are already familiar with. If you don't use an input element, you open several new questions that are already solved with an input element:
How does the user know that they can type to filter the list? Input elements are a clear declaration to the user: "You should type here!"
How does the user know what string is going to be filtered on when they press more than one key? When I quickly type 'hu' in that Google Translate interface, 'Hungarian' is selected, as I would expect. However, what happens when I type it slowly? If it's slow enough, 'Hatian Creole' is selected, and then 'Ukranian'.
What if I mistype something and want to start over? Is there a button to press to clear it out? How long do I need to wait for the filter to clear on its own?
You could certainly create a new interface element that solves all of these problems, and if that's your goal, go for it, but there are preexisting standards for these sorts of things.
For one, that previously-mentioned autocomplete widget is really handy, and really flexible.
you can try something like this:
var _interval;
$("#textarea/field_id").bind('keypress', function(event) {
clearTimeout(_interval);
_interval = setTimeout(onTimeout, 1000);
});
function onTimeout(){
var words = $("#textarea/field_id").val().split(' ');//do what you want with the string in the field
}
This will capture the entire string onTimeout. Play with the timeout a little bit to get it nice and clean!
What about this:
var word='';
$(document).bind('keypress', function(event) {
//UPDATE word ACCORDING TO THE CHAR, LIKE:
if (event.charCode >=48 && event.charCode <=57) {
.... ....
.... ....
}
//OR
switch(event.charCode) {
.... ....
.... ....
}
});
I created my own version of a <select> with <div> tags, check it out here.. If i understand you correctly, this is what you want..
http://jsfiddle.net/myTPC/
It also supports backspace (atleast in firefox).
What I've tried to do is:
1) get the keypressed (only 0-9, a-z and space) and save this inside a div
2) created a LI list (you can use a div with a-elements, that's fine aswell)
3) find LI-items with the text that's being saved
4) add up/right down/left arrows to get next/previous item in the list
For now it keeps all items in the list, you can hide them aswell if you want. It's just an illustration.
// EDIT:
Here's a starters setup: http://www.pendemo.nl/keyinputtest.html
In firefox the body doesn't get automatically selected which causes that you need to click the body/webpage again before a second input is being detected. In Chrome it detects keys pressed after eachother.
// EDIT2:
Working in firefox. Text is now saved inside a div (you can type a string you want and see it being placed in the body).
// EDIT3:
Added an UL list with some items. typing some text will filter this list with items matching the typed string.
// EDIT4:
Only a-z and space are being used to search. Still looking for a way on how to find the backspace key. Since Chrome is adding 'history.go-1' by default. Firefox however does notice the backspace key. event.preventDefault() is not changing anything in Chrome.
// EDIT5:
Added up+right arrow to select next and left+down array to select previous item.
// EDIT6:
Upon using the enter key, the current value is alert. Ofcourse the scripts stops after the alert. But as you can see the value is available for you.
Here's the code I came up with so far:
var typed_string = '';
$(document).ready(function() { $('#typedtext').select(); });
$(document).bind('keypress', function(event) {
event.preventDefault();
if((event.which > 47 && event.which < 58) || (event.which > 96 && event.which < 123) || event.which == 32) {
typed_string = typed_string + String.fromCharCode(event.which);
$('#typedtext').html(typed_string);
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green').first().addClass('selected').css('background-color', 'red');
$('#typedtext').select();
}
if(event.which == 13) {
alert('Selected item: ' + $('.selected').html());
$('#typedtext').select();
}
});
$(document).keyup(function(event) {
event.preventDefault();
if(event.which == 38 || event.which == 37) {
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green');
$('.selected').removeClass('selected').prev().css('background-color', 'red').addClass('selected');
}
if(event.which == 39 || event.which == 40) {
$('#testlist li').css('background-color', '#ffffff');
$('#testlist li:contains('+typed_string+')').css('background-color', 'green');
$('.selected').removeClass('selected').next().css('background-color', 'red').addClass('selected');
}
});
function clearInput() {
typed_string = '';
}
And I'm using this HTML:
Press any key to save text.<br /><br />
<div id="typedtext" style="border: 1px solid #09F; padding: 5px;"></div>
<br /><br />
Let's test to filter some items from the li. (use up/down or left/right keys to select next item)
<ul id="testlist">
<li>item</li>
<li>test</li>
<li>more test</li>
<li>another item</li>
<li>test item</li>
<li>more item</li>
<li>foo</li>
<li>foo bar</li>
<li>bar</li>
<li>more foo</li>
</ul>
I think it's easy enough for you to change the HTML code to fit your needs.
What's the reason you don't want to use an input, is it just so if JS isn't available you can graceful fall back to the select? If so this might do what you want, I've used the select as a basis and taken the values from there although I have ended up putting an input in there.
Following on from Neal's answer, I think autocomplete is fairly similar to what you need, but if you want to display the results differently I've got a second approach in the same example that displays the filtered results.
Full example version here:
http://jsfiddle.net/R7APm/9/
Here's the JS from it:
$opts = $('option', '#myselect');
//Grab the text from the select (could use option values instead with .val()
var values = [];
$.each($opts, function(i, opt) {
values.push($(opt).text());
});
$div = $('<div/>');
//Autocomplete version
$input = $('<input/>').autocomplete({
source: values
});
//Filter in div version
$wordlist = $('<div id="wordlist"/>');
$wordlist.text(values.join(", "));
$input.keyup(function() {
matches = $.grep(values, function(el, i) {
if (el.toLowerCase().indexOf($input.val().toLowerCase()) >= 0) {
return true;
} else {
return false;
}
});
$wordlist.text(matches.join(", "));
});
//Add new elements to wrapper div
$div.append($input);
$div.append($wordlist);
//Replace select with wrapper div
$('#replaceme').replaceWith($div);
$input.focus();
If you don't want to use a hidden dropdown (which i still strongly advise) i suggest following:
Make the DIV focusable
This works thanks to the "tabindex" workaround found at
http://snook.ca/archives/accessibility_and_usability/elements_focusable_with_tabindex
Capture only the keystrokes on your custom dropdown, NOT just all on the whole document. First, it's unusual behavior. Second, how would you deal with more than 1 custom dropdown?
Store the filter string via jQuery's data container
Check out the full working demo with a simple language dropdown at http://jsfiddle.net/aWE8b/
The demo contains:
Custom Dropdown
Supported keys:
Backspace
Enter
Escape
Left, Up
Right, Down
2 Modes:
Filter: remove unmatched items
Select: highlight first matched item