My text/value in textarea it's not static - I'm chaning it. I can't get the current value.
E.g
1
<textarea>
Lorem ipsum
</textarea>
//it's defalut in html file
2
Putting into textarea:
Dolores is lorem ipsum
Alert is only showing 1 version("lorem ipsum"), but not second ("Dolores is lorem ipsum"). I'm trying to do it in jquery:
var variable = $("#selector").val();
alert(variable);
What I'm doing wrong?
EDIT
I want to catch it to variable :) Not to alert. Alert is only my test :)
var text = $('#textareaID').val();
$('#textareaID').change(function() {
text = $(this).val();
});
when ever you want text just reference it :)
EDIT:
If your using tabs UI please review the docs and the event management:
Place This outside of bound scope:
var text = $('#textareaID').val(); OR var text = '';
$('#example').bind('tabsselect', function(event, ui) {
// Objects available in the function context:
// ui.tab anchor element of the selected (clicked) tab
// ui.panel element, that contains the selected/clicked tab contents
// ui.index zero-based index of the selected (clicked) tab
// INSIDE HERE IS WHERE YOU CAN PUT THE CODE IN THE ABOVE EXAMPLE
$('#textareaID').change(function() {
text = $(this).val();
});
});
NOTE: $('#example') would be the parent div that holds the tabs and content
Further optimization recommendation.
If you think $('#textareaID') will be called often you may want to cache a reference to it so the selector engine does not have to find it on every instance, this would be done like:
var textarea = $('#textareaID');
var text = $('#textareaID').val();
For this line:
var textarea = $('#textareaID');
Make sure it is inside of a $(document).ready(function() {}); Call and the element is exists
you could check for this by doing:
var textarea = $('#textareaID') || false;
And wrap the code above like this:
$('#example').bind('tabsselect', function(event, ui) {
// Objects available in the function context:
// ui.tab anchor element of the selected (clicked) tab
// ui.panel element, that contains the selected/clicked tab contents
// ui.index zero-based index of the selected (clicked) tab
// INSIDE HERE IS WHERE YOU CAN PUT THE CODE IN THE ABOVE EXAMPLE
if(textarea) {
textarea.change(function() {
text = $(this).val();
});
}
});
Hope this helps!
$('textarea').change(function() {
alert($(this).val());
});
Try to tie the alert() to an event:
$('textarea').change(
function(){
alert($(this).val());
});
JS Fiddle demo.
References:
change().
The error is somewhere else.
The code you are using is correct. Check a demo
It sounds like you are trying to assign the .val() to a variable before the value changes. You are correct in that you want to use .val(). Try this jsfiddle to see the differences that are produced by the variable, .val(), .text(), and .html().
Related
How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/
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 know that the solution is the jQuery.on-function but it don't work as I expect it would do.
Following problem:
I pull via Websocket(JSON) data and build my page up inside the document ready function (for connection reasons).
That means I add several input fields via the jQuery.append()-function and try to access the select-input when the SET button is pressed. Accessing the select input fails.
I have selected the body as parent element, every other form field should be in it.
For demo reasons I removed the Websocket-Functions. I have hardcoded the form as it would be in real. The debug-messages are displayed in the firebug-console.
Here is the fiddle: http://jsfiddle.net/gLauohjd/
This is the way I am accessing the select input
$("body").on('click', ':button', function () {
console.log( $( this ).text() ); //Value of the pressed button
var ip = $(this).attr('ip');
var selectvalue = "#" + "modeselect" + ip;
console.log(selectvalue); //Print the selector to verify it is ok
console.log($(selectvalue).val()); //fails ->not found in DOM
Any help on that is very appreciated!
To select a tag with jQuery, use just the tag name.
$("body").on('click', 'button', function () { .. } // any button clicked on body
As for actually retrieving the values, you won't be able to do so unless you escape the dots.
$("#modeselect127\\.0\\.0\\.1").val();
You could use something like:
var selectvalue = "#" + "modeselect" + ip.replace(/\./g, "\\\\.");
Hope this helps.
I'm trying to allow users to edit the text of a paragraph in a website. I take a paragraph and replace the <p> tags with <textarea> tags using the .replaceWith() function. When I try to take the value of the textarea, it returns blank. Here's a JSfiddle.
HTML:
<p><a class="edit">Edit</a>I'm going to change this into a textarea field and retrieve the value.</p>
JS:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = object.val();
alert("Value: "+value);
});
});
});
I'm a programming beginner, so if you have style or implementation tips, feel free to share. This is just my gut reaction to solving the problem; there may be a simpler way to accomplish the same thing.
EDIT: I should also mention that in my website, each paragraph comes from a database table that I'm displaying using an AJAX function. When the user is done editing, he can click a button, and the website will take the new value of the textarea field and UPDATE *table* SET *text*=newText WHERE *text* LIKE oldText;
Try just using contenteditable='true' instead of changing to a textarea. It will make the <p> editable.
Like this:
<p contenteditable='true'><a class="edit">Edit</a>
I'm going to change this into a textarea field and retrieve the value.</p>
If you want to make your text area editable when someone clicks 'Edit', you can create a function that sets the contenteditable attribute to true and then gives focus to the <p> element.
Your code is not trying to get the value of the <textarea>. Your call:
object.replaceWith( ... )
does not change the value of the variable "object" — it's still the jQuery object for the <p> tag, but after that it's out of the DOM. <p> tags don't have a "value" property.
It's almost always a bad idea to set up event handlers inside another event handler (well, an event handler for interaction events anyway). Event handlers accumulate, so each "mouseenter" event will add another "click" handler.
ckersch is right about an easier method being to use contenteditable, but if you're looking to a solution for your specific problem, change your selector from this:
var value = object.val();
To this:
var value = $("textarea").val();
Full code:
$(document).ready(function() {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function() {
$('.edit').show();
object.on('click','.edit',function(){
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $("textarea").val();
alert("Value: "+value);
});
});
});
Fiddle
There are many ways you could make it more robust, including adding a class or id to your textarea, and then using it to be selected, such as this way:
object.replaceWith($("<textarea class='selectMe'>").val(oldText).css("width",object.css('width')).css('height',object.css('height')));
var value = $(".selectMe").val();
You are using the method replaceWith() wrong. The argument must be a string or a function that returns a string, not a jquery selector. Also, you should place the onclick event outside of the mouseenter event (this is valid for any event, never nest them)
$(document).ready(function() {
function makeTextarea(e) {
e.preventDefault();
var edit = $(e.currentTarget);
var parent = edit.parent();
edit.remove();
parent.replaceWith('<textarea>' + parent.text() + '</textarea>');
}
$('.edit').on('click', makeTextarea);
});
Fiddle: http://jsfiddle.net/U57v2/4/
"When the document is ready listen for clicks on .edit class. When clicked store a reference to the parent element (<p>) and then remove the edit element. Finally replace the parent element (<p>) with a textarea with the contents of the <p> element."
ckersh is absolutely right about the contenteditable, but if you're looking for a specific answer to your code, there are a few things you could improve.
There are a couple of issues with your code. First, you're rebinding the on('click') handler every time you mouse over the paragraph, so if you mouse over 5 times, you're executing the anonymous function 5 times. You only need to bind the on routine once. Second, the variable object never changes, so when you replace it with a textarea, you need a new selector to get the value.
I've updated your fiddle with the enhancements I've mentioned above. I also added a mouseleave event, because I figure you want to hide the "Edit" button when you leave the paragraph. The updated javascript can be seen below:
$(document).ready(function () {
$('.edit').hide();
var object = $('p');
object.on("mouseenter", function () {
$('.edit').show();
}).on("mouseleave", function () {
$('.edit').hide();
}).on("click", '.edit', function () {
var oldText = object.text();
oldText = oldText.substr(4); // Exclude the word 'Edit'
object.replaceWith($("<textarea>").val(oldText).css("width", object.css('width')).css('height', object.css('height')));
var value = $("textarea").val();
alert("Value: " + value);
});
});
I have a jQuery function:
$(function(){
function InitDialog(c,b){
/* some code */
}
$('a[name=dialog]').click(function(e) {
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
And also I have a link defined in html code like below:
<ul>
<li>something</li>
</ul>
My question is how can I pass the parameters (caption, bodyText) to Init() function via link?
I've heard about some method like below:
<li>something</li>
But I don't understand how can I get and parse it?
Thanks
Since you are using jquery, I would recommend that you do the following to store data on your element
Link Text
Then in your click function, you can access it as shown below
$('a#dialog').click(function(){
var me = $(this), data = me.data('params');
//console.log(data);
});
Edit - Fiddle added
Check the fiddle to see a working sample
using data-* attribute, you can:
<a name='dialog'
data-caption='this is the caption'
data-bodytext='this is the body'>klik</a>
and the javascript:
$(function() {
function InitDialog(c, b){
alert('the caption: ' + c);
alert('the body: ' + b);
}
$('a[name=dialog]').click(function(e) {
caption = $(this).data('caption'); // gets data-caption attribute value
bodyText = $(this).data('bodytext'); // gets the data-bodytext attribute value
InitDialog(caption, bodyText);
fadeInCommon(e,this);
});
});
tho instead of using name as the selector, i'd recommend class instead
So first, I think you want to say $('a[href="#dialog"]') to get the a tags, then in the click function, $(this).attr("name") will give you the some information, which you could store a json string...
My Text
$('a[href="#dialog"]').click(function() {
var data = JSON.parse($(this).attr("name"));
InitDialog(data.caption, data.bodyText);
});
But, I don't think that's the right way of going about what you're trying to do, would you be better to create the dialog in a div lower down the page, hide it, and only show it when you click the link? Because the term 'bodyText' implies it's going to be big...
Or just:
My Link