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
Related
I'm trying to get the contents from a TinyMCE textarea to populate a button/div as I type. This is to show the client how the button/div will look like when it goes live. Everything else works dynamically, such as the button/div colour, the title and dropdown.
The issue lies with dynamically retrieving the contents from TinyMCE. If I use a standard textarea box it works fine. I want the client to be able to use some of the basic features of TinyMCE.
Kind of how this form field is working. As I'm typing in this box, I can see my text updating below.
My JS is:
$(document).on('change', '#ParentID', function() {
var NTxt = $('#ParentID option:selected').text();
var NVal = document.getElementById("ParentID").value;
NTxt = NTxt.replace(/ # /g,"<br/>");
if(NVal != "0"){
if(NTxt.value != null || NTxt.value != "0" || NTxt.value != undefined){
$("#LTxt").html(NTxt);
}
}else{
$("#LTxt").html('External Link Text/Quote Text');
}
});
$(document).on('keyup', '#Opt2', function() {
$('#LTxt').text($(this).val());
});
Here are some screen grabs:
1. Normal State:
2. Populated title and dropdown "internal link" text:
3. Textarea, populating same place (WITHOUT TINYMCE):
Anyone know how I can do this with TinyMCE? I've tried...
tinymce.get('content id').getContent()
...but it didn't seem to populate dynamically.
This is the key question: How to pass anything typed into the TinyMCE textarea into the button, at the bottom, as the user is typing?
Many thanks in advance,
Glynn
You need to use a variety of events that TinyMCE triggers to know when its content has changed. You can then grab the content from the editor and do whatever you need with it.
Here is an example that shows the actual raw HTML in a neighboring DIV. It can easily be adapted to insert the HTML into an elements so its actually rendered to the page.
http://fiddle.tinymce.com/Gegaab/5
The list of available events is documented here: https://www.tinymce.com/docs/advanced/events/#editorevents
The example uses the keydown and change events in particular but there are many to choose from if those don't fit your needs.
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 want to have an edit button which turns into a textarea when clicked. However, when I do click the button, the resulting textarea will not hold keyboard focus and I cannot edit it.
Javascript code:
var listEditHTML = "\
<textarea name='edit_text'> Enter a date </textarea>\
";
$(document).ready(function()
{
var App = { };
App.default_text = 'Enter a date';
$('button').click(function(){
$(this).html(listEditHTML);
});
});
HTML code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<button> edit </button>
Also the code was created with JFiddle so here's the fiddle if anyone's interested:
http://jsfiddle.net/wasingej/TT5nw/17/
note: I also tried running this code in the W3schools 'tryit' editor and it produced the same results so I doubt that the issue is with my Fiddle.
try this:
$('button').click(function(){
$(this).after(listEditHTML);
$(this).remove();
});
or as #Dan pointed out, use replaceWith
The problem is, you're putting the text field inside the button (you can see the button-y background in your original fiddle). You want to put the field after the button, then remove the button.
You are creating a text area inside the button,
you need to do #
$(this).parent().html(listEditHTML);
look here
http://jsfiddle.net/SdJrX/
Warning: this will replace all the content of the button: if there were chidren inside it they will be lost.
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
I need some kind of textbox control that can host buttons along the text strings. Basically I want to create a textbox with names that enables the user to remove some names after addition. How can this be accomplished in javascript ?
Thanks in advance.
Just add SPANs before the textbox in your element. Format the SPANs as colored boxes with the text and maybe an X for deleting the entry and you're good to go.
Using JQuery this is really easy. Or do you want a Webforms-Control which is able to do that?
Edit:/
The Inline-Element could look like that:
<span id="my-filterbox">
<input type="text" name="next-filter" />
</span>
And then your JS to add a key-event handler. Im using JQuery in this case:
$('#my-filterbox').keyup(function(event) {
if(event.keyCode == '13') { // 13 = key code for enter
var value = $(this).val();
$(this).val('');
$('#my-filterbox').prepend('<span class="filter-elem">' + value + '</span>');
}
});
This way you add the filter to the span my-filterbox everytime the user hits enter. Per CSS you're able to format the span at the left side of the input box.
This code is untested but I think you get the idea.