How to lock the first word of a textarea? - javascript

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

Related

Trigger function on input event if selected text is within input

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.

Change the title of a page while typing

As an exercise for myself I'm trying to make a blog posting application using JavasScript, JQuery and PHP. What I want to happen is that, when you're typing, the title of the page changes. With this, I mean the title declared within the <title></title> tags. A good example of this is StackOverflow: when you're asking a new question, you type in the title of that post, and the page title (the one declared inside the <head>) changes to the title you are typing.
How is this effect done? Is it possible using only JavaScript/JQuery or do you need AJAX for it?
You can just change the title with JS:
document.title = 'New title';
About the effect you are looking for you can probably do something in the lines of:
$(document).ready(function() {
$("input").keyup(function() {
var text = $(this).val();
document.title = text;
});
});
I'm not sure but I think you want to change the page title to whatever is typed in a input tag, For example
something like this?
$(document).ready(function () {
$('#myInput').keyup(function () {
$(document).attr('title', $('#myInput').val());
});
});
the above will track the changes of key up (on keyboard) and get the value of the text input and set it as page title :
here a working fiddle: http://jsfiddle.net/ZLPfM/show
To change the page title, you can do one of two things:
//plain javascript
document.title = 'My JavaScript title!';
//jQuery
$(document).attr('title', 'My jQuery Title');
In order to change it while typing, hook up an keyup event:
$(document).keyup(function(e)
{
//Check the keycode using e.keyCode
});
This will bind it to the document, which means anytime a key is pressed, within an input or otherwise, your event will fire. You could also bind it to a textbox so that it will only fire when you type within the input (which is probably what you want to do).
If you bind to the document, like shown above, you'll have to check the keyCode and append the value onto your title. If you bind to an input, you can grab the input value and set the title to the new value:
$('#myinput').keyup(function(e)
{
var text = $(this).val();
document.title = text;
});

"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 + ' ');
}

Formatting text in dynamicaly created textboxes

I have jquery that generates textareas with different id's. Now i need to make some buttons that will format text inside that textareas. For example: when user clicks in certain textarea, enter text, and click "bold" button, only text inside of that textarea will become bold (in other will be normal). I did manage to make something like this with JS, but it was too primitive (text was formated in all of textboxes) :(
Here is some sample code for this:
<button id="bold">B</button>
<textarea id="ta_1">Some test text</textarea>
<textarea id="ta_2">Some test text</textarea>
What i want to say: one button, multiply text boxes. Entering text in ta_1 and clicking bold, should bold only text in that txtarea. Additional info: all id's starting with same word, just different number at the end.
I feel there is some simple solution, just cant figure it out :D
Actually this is a really bad practice, but you can do that like this,
var activeEl;
$("textarea").focus(function() {
activeEl = $(this);
});
$("#bold").click(function() {
$("textarea").css("font-weight", "");
activeEl.css("font-weight","bold");
});
​
​
DEMO
UPDATE-1: I don't know why you are trying to do this, but I suggest to you use a WYSIWYG Editor like elRTE
UPDATE-2 : You can costomize your toolbar in elRTE, if you want your editor has just a "bold" button, yes you can do that,
$(document).ready(function() {
elRTE.prototype.options.panels.web2pyPanel = ['bold'];
elRTE.prototype.options.toolbars.web2pyToolbar = ['web2pyPanel'];
var opts = {
toolbar: 'web2pyToolbar',
}
var rte = $('#our-element').elrte(opts);
});​
DEMO FOR elRTE
I'm not sure this is a great idea for user functionality, but it can be done. You'll just need to record the "active textarea" somwhere. I would suggest using .data(). jsFiddle
//disable the button until we have a target textarea to avoid confusion
$('#bold').attr('disabled','disabled');
//Record a new 'activeElement' each time user focuses a textarea
$('textarea').focus(function(e){
$('#bold').data('activeElement',e.target)
.removeAttr('disabled');//this first time we will enable the bold button
});
//retrieve the stored 'activeElement' and do something to it
$('#bold').click(function(){
var activeElement = $('#bold').data('activeElement');
$(activeElement).css('font-weight','bold');
});
Most people expect a "text formatting" button to work on their selection. Selections and ranges are out of the perview of jQuery and quite complicated to work with. As has been suggested already, I would advise using one of the many wonderful WYSIWYGs like tinyMCE.
Use document.activeElement
var activeEl;
$('#bold').mousedown(function()
{
activeEl = document.activeElement
});
$("#bold").click(function() {
//check activeElement
if(......){
activeEl .css("font-weight","bold");
}
});
Don't forget check that activeElement exactly textarea

Adding input in jQuery and problem adding several input with a click

Why after a click on add, adding several input together?
I want once times add input in each click on add.
you see yourself : my code
Try this js fiddle I think I have done wat you wanted.
http://jsfiddle.net/539LR/6/
Here is the js code
$('a.add_input').live('click', function (e) {
e.preventDefault();
var $column = $(this).closest("div.column");
var input = $column.prev("div.column").clone().wrap("<div />").parent().html();
$column.before($(input));
});
This is probably what you want. It grabs a column, duplicates it, sets the input to "" and inserts it before the "add" button
http://jsfiddle.net/n4YFK/1/
Use var input = $(".ai_service").find(":eq(0)").html(); instead. See http://jsfiddle.net/539LR/4/ for reference

Categories