Getting <textarea> value with jQuery not working as expected - javascript

There are quire a few "jQuery getting element value" questions on here, but I was unable to find one that helped in my situation. Please read before marking as a duplicate, although I am more than happyto be pointed to another question which successfully answers my question.
I have the following <textarea>
<textarea id="comment_text" class="comment" onblur="if(this.value == '') { this.value = 'Comment...'; nocomLeft() }" onfocus="if(this.value == 'Comment...') { this.value = ''; comLeft() }">Comment...</textarea>
This adds placeholder text, removes it when it has focus, and adds it backs again if nothing is entered.
Now at various points, like when I click a button, I do:
var comment = $('#comment_text').text();
Which no matter what returns the value Comment... even if I have typed in the text area, clicked somewhere else to remove the focus, and can clearly see my new text still in the text area - $('#comment_text').text()' always comes backComment...`
I am stumped, all help appreciated.
Thanks

Use .val()
$('#comment_text').val();
Also, save some JS, and use the placeholder attribute.

.val() would be the proper method to call. So in your example, it would be
var comment = $('#comment_text').val();
Note that you can even set the text of the textarea by doing something like
var comment = $('#comment_text').val('this is a test');

Try using the .val() method
$('#comment_text').val();

Related

Input field with attached text to the right

I'm doing a fancy comment list on my project, structured like this:
As you see, there's a comments list and at his bottom there's an input field (textarea) to submit a comment. Note that there's the current username attached to the right (let's call it a simple static appended text).
I just found this little JS to make an input field resize automatically by adapting it to the content.
function resizeInput() {
$(this).attr('size', $(this).val().length);
}
$('input[type="text"]').keyup(resizeInput).each(resizeInput);
But it's not enough. I need it for a textarea and I want it to behave correctly when a comment is long enough to wrap on another line. By definition, the input field is a box, and it obviously acts badly compared to what I want:
Instead, this should be the right behavior:
I looked everywhere and I can't think any way to implement this. Can somebody help me?
Here is a good plugin for textarea. But it using jQuery.
usage simple as always.
$(document).ready(function(){
$('textarea').autosize();
});
You could use the contenteditable attribute:
<span contenteditable="true">comment</span> by <span class="userName">someone</span>
It is supported in practically all browsers. Using the right CSS, you can underline the content and also limit the width.
I think you mean this
NOTE: No check for selection and bound to document. Exercise for the reader to bind to a specific field and swap it for a span
FiDDLE
$(document).keypress(function(e) {
var char = String.fromCharCode(e.which);
if (e.which==13) char = '<br/>'; // needs to handle backspace etc.
$("#textfield").append(char);
$("#hiddenfield").val($("#textfield").text()); // or .html if you want the BRs
e.preventDefault();
});
using
<span id="textfield"></span> - by My Username
If you make the field contenteditable you will get this in Chrome so some additional CSS may be needed
Use a <span> with contenteditable (supported in IE too). Here is a fiddle: http://jsfiddle.net/goabqjLn/2/
<span contenteditable>Insert a comment...</span> by My Username
Then, using JavaScript, attach an event listener that mirrors the inner text of the span into a hidden input field, so it gets submitted with your <form>.
Edit: I have updated the fiddle to also include the JS code. Here is the updated code:
<span class="editor" id="editor" contenteditable data-placeholder="Insert a comment...">Insert a comment...</span> by My Username
<!-- Hide this textarea in production: -->
<textarea type="text" id="comment"></textarea>
And the JS:
function mirror() {
var text = $('#editor').html().trim()
.replace(' ', ' ')
.replace(/<br(\s*)\/*>/ig, '\n') // replace single line-breaks
.replace(/<[p|div]\s/ig, '\n$0') // add a line break before all div and p tags
.replace(/(<([^>]+)>)/ig, ""); // remove any remaining tags
$('#comment').val(text);
}
$('#editor').focus(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text('');
}
}).blur(function () {
var editor = $(this);
if (editor.text() == editor.attr('data-placeholder')) {
editor.text(editor.attr('data-placeholder'));
}
}).blur(mirror).keyup(mirror);

How can I append Form text to a URL in JQuery, in the following example:

I've seen a few similar posts, but nothing explains a method which fits into my example.
I'm looking to take what has been typed into a Form with the ID "searchbox", and append it to the following script:
Form:
<form method="get">
<span><input type="text" class="search rounded" placeholder="Search..." id='searchbox' autofocus></span>
</form>
JQuery:
$(function(){
$('input[type="text"]').keyup(function(){
var searchText = $(this).val().toLowerCase();
var appendedText= $(this).val();
$('ul > li > a').each(function(){
var currentLiText = $(this).attr('class')
showCurrentLi = currentLiText.indexOf(searchText) !== -1;
$(this).toggle(showCurrentLi);
if (event.which == 13 || event.keyCode == 13) {
chrome.tabs.create({url:'http://www.exampletestsite.com/'+appendText});
return false;
}
return true;
});
});
Most of the code simply filters a list of preset options, pressing enter will load the url appended with the typed text instead of using a clickable preset.
I'm trying to set the 'appendedtext' variable to get what has been typed into the search field, and on Enter press, load a URL with the appended text.
I thought this var would work, but it doesn't:
var appendedText= $('#searchbox').val();
I'm pretty sure I'm just an idiot though, since this seems incredibly simple. Any help would be really appreciated.
EDIT: Added form format for clarity. Fixed code snippet, added some information about the code.
The line var appendedText= $('#searchbox').val(); works perfectly well, as you can see in this fiddle (passing the event parameter isn't necessary, and certainly isn't the root of the problem). However, I got rid of the form and span elements, and the chrome.tabs stuff, so I suspect your issue lies in one of those.
I'm not sure how to help if that's not the actual problem, but as far as jQuery and .val() go, everything's fine.
It turns out my issue was with the $('input[type="text"]').keyup(function(){, specifically 'keyup'. Keyup would clear my searchbox content by default before sending the data which appended to the url. I merely changed it to keydown and everything worked perfectly.
Thanks for all your suggestions.

Placeholders with divs, not inputs/textareas

I have working on this problem for a couple weeks off and on. What I am trying to do is have placeholders to show users where they can type. When they do type, I want the placeholder to disappear, but reappear again when the div is empty.
Every thing I have found has to do with cross-browser placeholder support for inputs and textareas, and trying to apply the code for them to my issue results in failure.
I am using h1s for titles and standard divs for descriptions.
My code looks like this:
HTML
<div class="page-desc" contenteditable="true" data-placeholder="Write your description here."></div>
jQuery
var placeholder = '<span class="placeholder">Write your title here</span>';
$(this).html(placeholder);
I have more jQuery code, but it sucks. I am currently using keyup to hide the placeholder, and that's obviously not working. Can someone help me out?
I am totally open to using vanilla JavaScript as well.
You can have something like this:
$('#xdiv').html($('#xdiv').data('placeholder'));
$('#xdiv').keydown(function() {
if ($(this).html() == $(this).data('placeholder')) {
$('#xdiv').html('');
}
})
$('#xdiv').keyup(function() {
if ($(this).html() == '') {
$('#xdiv').html($('#xdiv').data('placeholder'));
}
})
Initially it sets DIV's HTML to placeholder text. Then when user begins to type (on keydown) it checks if DIV still has the placeholder text and if so - removes it. And since user can delete all the data - it checks (on keyup) if DIV is empty, and if so - restores placeholder's text.
Demo: http://jsfiddle.net/bP7RF/
there's a way to do it in css (modern browser only)
.pageDesc:empty:after {content : "Write your description here.";}
Javascript solution (not as pretty, but more cross-browser):
$("#in").keyup(function(){
if(!$(this).html()){
$(this).html($(this).attr('data-placeholder'));
$(this).attr('showing-placeholder',true);
}
});
$("#in").keydown(function(){
if($(this).attr('showing-placeholder')){
$(this).html('');
$(this).attr('showing-placeholder','');
}
});
Working Example: JSFiddle;
Why not use the Blur and Focus event handlers from jQuery and check the Text value of the Div?
Code for quick look:
$('[contenteditable="true"]').blur(function() {
var text = $.trim($(this).text());
var ph = $('<span/>',{ 'class':"placeholder"})
.text($(this).data('placeholder')||'');
if (text == '') {
$(this).html(ph);
}
}).focus(function() {
if ($(this).children('.placeholder').length > 0) {
$(this).html('<span> </span>');
}
});
Fiddle for example: http://jsfiddle.net/qvvVr/1/
Why can't you use the placeholder attribute of the input element.
It seems to do exactly what you want and it's very well supported
(http://caniuse.com/input-placeholder).
Sorry if I have missed something.

Setting input value to attribute value in JQuery

I have a number of <input /> boxes which I want to start off having a value of something like "Enter your name...".
When you focus them, the value becomes empty and you can type away. When you blur them, if nothing has been entered, then it goes back to "Enter your name...".
I thought of having something like this:
<input id="name" _startValue="Enter your name..." />
Then, something like this:
$(document).ready($("input").val($(this).attr(_startValue)));
This initially should set the value to _startValue but it does nothing. Replacing the line with:
$(document).ready($("input").val("hello"));
does work, however, so the problem must be with the $(this) or the attr().
First of all, how do I get this to work. Secondly, if I am trying to do this in a really retarded way, what is a good way to get this functionality?
I believe its better to use a placeholder like:
<input id="name" placeholder="Enter your name..." />
There are already libraries for this, and if you are already using jquery you should use them.
https://github.com/mathiasbynens/jquery-placeholder
just add the attribute "placeholder" and invoque the function:
<input placeholder="my placeholder">
<script type="text/javascript">
$("document").ready(function(){
$("input").placeholder();
});
</script>
Note that you only need to add the plugin if you need old browser support (in IE specially), otherwise, the attribute is enough.
Also, consider that if you code this, it will take you errors like submitting the default value of the form. What jquery plugins do generally is to make a <span> or whatever and place it on top of the input when the input is empty, and hide it when the input is not empty.
// v---you're not passing a function
$(document).ready($("input").val($(this).attr(_startValue)));
// `this` isn't magic-------^---- It doesn't just mean what you want
Should be more like this:
$(document).ready(function() {
$("input").val(function() {
return $(this).attr("_startValue");
});
});
A common way to mimic placeholders is to put the placeholder text in the element's value, then check the value on focus like:
if (this.value == this.defaultValue) this.value = '';
and then on blur:
if (this.value == '') this.value = this.defaultValue;
Please don't use placeholders instead of labels or onscreen help (e.g. format for dates). If a browser doesn't support the placeholder attribute, it's probably best not to emulate them if using it for the default value is an issue.
After all, placeholders are a "nice to have", they should not be fundamental to using the form correctly.

Is there a way to style textarea content as the user types with javascript and css?

I'm curious if there's a way to style content in a textarea as a user types.
For example:
<textarea>abcdefghijklmnopqrstuvwxyz</textarea>
Could I highlight all the vowels in the above textarea string on screen using javascript? But still only send the string when the form is submitted?
You can use a div with contentEditable attribute instead of textarea and to do the highlighting there.
https://developer.mozilla.org/en-US/docs/HTML/Content_Editable
You will still need to copy the content of this div to a hidden field of a form if you need to post it.
try this
<div contenteditable="true">
This text can be edited by the user.
</div>
give some id to textarea and bind its onkeyup event with jquery function.something like this
$('#id_of_textarea').bind('keyup', function() {
//for displaying vowels on screen
var str=$('#id_of_textarea').val();
var total_findVowels="";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i).match(/[a-zA-Z]/) != null) {
// findVowels
if (str.charAt(i).match(/[aeiouAEIOU]/))
{
total_findVowels=total_findVowels+str.charAt(i);
}
}
//use some label to display all vowels
$("#some_lbl").text(total_findVowels);
}//for
} );
You can see one of those questions for some inspiration. They talk specifically about live syntax highlighting so is it not exactly what you are asking about but maybe close enough, and syntax highlighting seems to be a more common problem so it's easier to find some ready solutions:
Textarea that can do syntax highlighting on the fly?
Are there any JavaScript live syntax highlighters?
https://stackoverflow.com/questions/1505761/textarea-with-syntax-code-highlighting
Live text color change in javascript
If beeing precise and answer only your question:
There is no way to do it, but as others said there are other ways to solve your task
I use the following snipplet:
$( "#yourtextarea" ).bind( "keyup input paste", parseAndReplaceContent );
My parseAndReplaceContent function calls jQuery's $( "#yourtextarea" ).val() to access and modify the data.

Categories

Resources