Trimmed input value displayed in div - javascript

I have an unknown number of input boxes with unknown IDs. I would like to be able to click on an input box and have a trimmed version of the value populate a div.
JSFiddle
My code all works as expected once the input field is edited, but I want to have the value displayed on first click/focus.
This is the JS function I wrote.
JS
$('input').each(function() {
var $tthis = $(this),
defaultValue = $tthis.val();
defaultValue = defaultValue.substring(keyed.indexOf("|") + 1);
defaultValue = defaultValue.substring(0, defaultValue.length - 2)
$("#target").html(defaultValue);
});
HTML
<input
id='thistext$index'
type='text'
onclick='this.select();'
onfocus="
document.getElementById('show_hide').style.display='block';
document.getElementById('show_hide2').innerHTML = 'Copy this text into the wiki, it will display as: ';"
onblur="document.getElementById('show_hide').style.display='none';" value='&#91[http://www.example.com/$dirArray[$index]|$dirArray[$index]]]' />
<div id='show_hide'>
<div id='show_hide2'>
</div>
<div id='target'>
</div>
</div>

I restructured your code a bit from the first fiddle.
I threw out all inline javascript and it's handlers, the onFocus, onBlur, onClick and replaced with jQuery equivalents and I think I got what you wanted.
I used jQuery's on() method to do the same thing which cleaned up the HTML a lot.
Then I used a function within show() to trigger a few other functions.
This could be more procedural but I thought it was nice and clean.
And lastly I extracted out the trimming and substringing to it's own function so that you can reuse it later on.
A fiddle here and the code below:
$('input').on('click', function() {
var $input = $(this);
$('#show_hide').show(function(){
$('#show_hide2').text('Copy this text into the wiki, it will display as:');
var text = trimInputValue($input);
$('#target').text(text);
});
});
function trimInputValue($input) {
var text = $input.val();
text = text.substring(text.indexOf("|") + 1);
text = text.substring(0, text.length - 2);
return text;
}
$('input').on('focusout', function() {
$('#show_hide').hide();
});
Now you might wonder where your select() went off to.
Don't worry, just include it in your on('click', function(){ select(); }); and it should execute.

Related

Changing a dynamically created label's text with keyup() issue

I am creating a form dynamically and therefore edit the form elements’ properties. When attempting to change the label, assigning an auto-generated id works fine but when changing this label using the generated id, the function or keyup() from jQuery keeps calling all the previously created label id(s). this means when i want to edit one label, it ends up editing every label.
HTML
<input type="text" id="change-label"><br><br>
<button id="add-button">add label</button>
<div id="add-label"></div>
JavaScript/jQuery
$('#add-button').click(function(){
var div = document.createElement('div');
var textLabel = document.createElement('label');
var labelNode = document.createTextNode('untitled');
textLabel.appendChild(labelNode);
textLabel.id = autoIdClosure();
$('#change-label').val('untitled');
div.appendChild(textLabel);
$('#add-label').append(div);
});
var autoIdClosure = (function(){
var counter = 0;
var labelId = "textInputLabel";
return function(){
counter += 1;
var id = labelId + counter;
editLabelWrapper(id)
return id;
}
})();
function editLabelWrapper(id){
function editLabel(){
var value = $(this).val();
$("#"+id).text(value);
}
$("#change-label").keyup(editLabel).keyup();
}
I’ve already found an alternative using onkeyup="$('#'+globaID).text($(this).val());", but I need to understand what I was doing wrong so I can learn from it.
JSFiddle
I think you are overthinking the matter...
Instead of using an unique id, rather use classes, makes it easier to handle.
So change <div id="add-label"></div> to <div class="add-label"></div>
Then what you want to do is, when a value is given in #change-label you want it in the last div.add-label.
So the function will become this:
$("#change-label").on('keyup', function() {
$('.add-label:last').text( $(this).val() );
});
Next what you want to do is bind a function to #add-button. Once it gets clicked, we want to add a new div.add-label after the last one. And empty the #change-label. You can do that by using this function:
$('#add-button').on('click', function() {
$('.add-label:last').after('<div class="add-label"></div>');
$('#change-label').val('');
});
Updated Fiddle

How to replace only the text of this element with jQuery?

I'm trying to make a kind of simple search engine, where
the user enters a string and if it's equal to the text inside
an element, that portion of text must be highlighted some way.
This is the html:
<input type="text">
<input type="button" value="Change text"><br>
Click here to get more info!
this is the css:
.smallcaps{
color:red;
}
and this is the jquery function that makes the search and replace:
$("input[type='button']").click(function(){
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
This is an example of how it looks like:
Everything works fine, until the search string is equals to the name of a node element, so for example if the search string is a, the html will be broken.
How can I avoid the replace of the html itself?. I just want to work over the text.
This is the codepen:
http://codepen.io/anon/pen/mefkb
Thanks in advance!
I assume that you want to only highlight the last search and not store the ones from before.
With this assumption, you can store the old value if it is the first call and use the stored value in the calls afterwards:
$("input[type='button']").click(function(){
// Escape the html of the input to be able to search for < or >
var textValue = $('<div/>').text($("input[type=text]").val()).html();
if(textValue === '') return;
$("a").html(function(_, html) {
var old = $(this).data('content');
if(!old) {
old = html;
$(this).data('content', old);
}
var replacer = function(match) {
return match.replace(new RegExp(textValue, "ig"), '<span class="smallcaps">'+textValue+'</span>');
};
if(/[<>]/.test(old)) {
return old.replace(/^[^<>]*</gi, replacer).replace(/>[^<>]*</gi, replacer).replace(/>[^<>]*$/gi, replacer);
}
return replacer(old);
});
});
Also i fixed two bugs I found when testing:
if you search for an empty string, everything is broken.
If you search for html characters like < or > nothing is found as in the text they are converted to < or >.
One thing is not solved, as it is not possible to easily implement it without destroying the subelement structure: It is not possible to search in different subelements, as you have to remove the tags, search then and insert the tags at the right position afterwards.
Working fiddle: http://codepen.io/anon/pen/KlxEB
Updated Demo
A workaround would be to restore <a> to original text, instead of complicating the regex.
Your problem is a form the <span> tag is getting replaced.
var init = $("a").text(); //save initial value
$("input[type='button']").click(function(){
$('a').text(init); //replace with initial value
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});

jQuery++, problems on .selection()

everybody.
I have a little problem; I'm trying to build a WYSIWYG, but I encountered some problems.
I have a contenteditable div with id = desc2, and some buttons. Let's take, for example, the button "bold".
<div class="magic" magic_id="desc2">
<div class="magicbutton one" magic="[b]%s[/b]">
<span style="font-weight:bold;">Bold</span>
</div>
</div>
And I have some jQuery++ selection application in:
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
console.log(text);
});
I have erased the other part of the script, because if I manage to get this to work, I'm done :D
So, as I was saying, if I do this, everything is good: I sleect a part on the div and on the console is outputted the content.
But this is not what I want to do. I wrote this:
$('.magicbutton.uno').on('click', function(){
var id = $(this).parent().attr("magic_id");
var selection = $("#"+id).selection(),
text = $("#"+id).text().substring(selection.start, selection.end);
console.log(text);
});
Everytime I click, it takes the ID of the div to change and should output the selected text, but it doesn't.
The code is the same, and i checked that $(this) in the first script is the same as $("#"+id) in the second.
What can I do? Thanks!
EDIT: jsFiddle
When DIV loses focus, selection is nullified. As a workaround, you could use data object:
DEMO
$('.magicbutton.one').on('click', function(){
var id = $(this).parent().attr("magic_id"); //id = desc2, i used this because i could have multiple forms in a page
var selection = $("#"+id).data('selection');
alert(selection);
}); //This doesn't work
$('#desc2').on('mouseup', function() {
var selection = $(this).selection(),
text = $(this).text().substring(selection.start, selection.end);
$(this).data('selection', text);
});

Jquery get readout of text area live

I was wondering if I could get a little help. I want to get a live preview of what is in my text area above it.
Each new line in the text area will display as a list above it, so something like this:
test
test2
test3
Text area:
test
test2
test3
How I want it to work is that on load it reads the contents of the text area and displays the contents above in a list. Then when the contents of the text area changes it also changes the list above it.
Here is my code: http://jsfiddle.net/spadez/9sX6X/
<h4>Placeholder</h4>
<ul id="tst"></ul>
<textarea rows="4" cols="50" placeholder="Test" id="test"></textarea>
This is how far I got:
$('#test').bind('input propertychange', function() {
if(this.value.length){
Rerender list to show contents
}
});
This is one of my first scripts so could someone please give me some guidance on how this should be achieved?
Fiddle
var list = $('#tst');
$('#test').on('keyup', function() {
list.empty();
if(this.value.length){
$.each(this.value.split("\n"), function(i, val){
list.append($('<li></li>').text(val));
});
}
});
$('#test').trigger('keyup'); // required to make it do the update onload
Because of my usage of .text(), this will handle special characters such as < and > without a problem. Also note how I have only selected the <ul> a single time, instead of re-selecting it over and over.
Side note: as of jQuery 1.7, .on() is preferred instead of .bind().
is this what you are looking for? http://jsfiddle.net/9sX6X/2/
CODE
$('#test').bind('keyup', function () {
if (this.value.length) {
var inp = this.value.split("\n");
$("#list").empty();
for(var x = 0; x < inp.length; x++){
$("#list").append("<li>"+inp[x]+"</li>")
}
}
});
Hope it helps
You could do this:
$('#test').on('change', function () {
var lines = $(this).val().split('\n');
$('#tst').empty();
for (var i = 0;i < lines.length;i++){
$('#tst').append('<li>' + lines[i] + '</li>');
}
});
Note: this code works on the change event of the textarea, thus you need to click outside of the textarea for the event to fire. If you want to do it on every key press, you should change the event from change to keyup. However, this does lead to far less performance.
You can see the updated fiddle here: http://jsfiddle.net/xv73p/

changing input text to textarea just like in facebook

i would like to replicate that you see a regular input text and when you click it changes into textarea.
is this a hidden layer or is it actually changing the input to textarea? how to do it?
I do believe it's always a textarea and on focus they just change the height of the textarea.
Edit: yes, it is. They use scripting to do everything with a textarea, there is no input field.
<textarea onfocus='CSS.addClass("c4b900e3aebfdd6a671453", "UIComposer_STATE_INPUT_FOCUSED");CSS.removeClass("c4b900e3aebfdd6a671453_buttons", "hidden_elem");window.UIComposer && UIComposer.focusInstance("c4b900e3aebfdd6a671453");' id="c4b900e3aebfdd6a671453_input" class="UIComposer_TextArea DOMControl_placeholder" name="status" title="What's on your mind?" placeholder="What's on your mind?">
What's on your mind?
</textarea>
One method that I found was to have a text area that begins with a smaller width and height and then to dynamically resize it.
function sz(t) {
a = t.value.split('\n');
b=1;
for (x=0;x < a.length; x++) {
if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
}
b+= a.length;
if (b > t.rows) t.rows = b;
}
then you would call your function with an onclick event
onclick="function sz(this)"
I found this here
Fellgall Javascript
One problem that he does mention is that this only functions on browsers that support it.
You can combine the jQuery widget you can find here with some coding
Example:
<div id="myform">
<form>
<textarea></textarea>
<button type="submit" style="display:none;">Post</button>
</form>
</div>
<script>
$(document).ready(function(){
var widget = $('#myform textarea');
var button = $('#myform button');
var tarea = widget[0];
// turn the textarea into an expandable one
widget.expandingTextArea();
var nullArea = true;
tarea.value = "What's on your mind?";
widget.focus(function() {
button.css('display', 'block');
if (nullArea) {
tarea.value = "";
nullArea = false;
}
});
widget.blur(function() {
if ($.trim(tarea.value) == "") {
tarea.value = "What's on your mind?";
button.css('display', 'none');
nullArea = true;
}
});
});
</script>
This code will hide by default the post button and will show it only when the textarea is focused or when you already have written something into it (you may want to hide/show a div instead or anything you want).
If jQuery is an option for you at all, there's a jQuery plugin that does just this called Jeditable.
Check out the demos here.
One way to do this is to code a dynamic textarea. This article explains how to do it: http://www.felgall.com/jstip45.htm
Another way to do it is to change the type of the object. Let's say you place your input text in a div tag (its ID being "commentBox". The code would then be:
//when you click on the textbox
function makeTextArea()
{
document.forms[0].getElementById("commentBox").innerHTML = "<textarea id=\"comments\" onBlur=\"backToTextBox()\"></textarea>";
document.forms[0].getElementById("comments").focus();
}
//when you click outside of the textarea
function backToTextBox()
{
document.forms[0].getElementById("commentBox").innerHTML = "<input type=\"text\" id=\"comments\" onFocus=\"makeTextArea()\"/>";
}

Categories

Resources