I am trying to move text from inside a div into the value from an input field but I'm getting [object Object] as the output. Can anyone explain why?
input = $('#input').contents();
$('#output').val(input);
Spencer.
The .contents() method won't give you the text, but an object with a collection of the elements it contains. You sould use:
val method:
The .val() method is primarily used to get the values of form elements
such as input, select and textarea.
text method:
The .text() method cannot be used on form inputs or scripts. To set or
get the text value of input or textarea elements, use the .val()
method.
The line you're looking for is:
$('#input').val($('#div').text());
and can be decomposed like this:
var textToMove = $('#div').text();
$('#input').val(textToMove);
Here is a full example:
function move(){
$('#input').val($('#div').text()); //copy text
$('#div').text(''); //erase text
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input' type='text' value=''>
<div id="div">Hello, Spencer</div>
<button onclick='move()'>Click to move text</button>
First get the text content with
$("#d").text()
Add this to input like
$("#y").val($("#d").text());
Now you can remove text of div like
$("#d").text("")
$("#y").val($("#d").text());
$("#d").text("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="d">text</div>
<input type="text" id="y"/>
Note:
Given a jQuery object that represents a set of DOM elements, the .contents() method allows to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements. and the results includes text nodes and comment nodes as well as HTML elements in the resulting jQuery object. Here
That's why you are getting object. you really need to use .text() here to get the text contents only.
The contents() you were trying to use is defined by the jQuery documentation as
To get the children of each element in the set of matched elements,
including text and comment nodes
So, contents() is returning en entire object with all those children, comments and etc... that's why: [Object Object]. If you use console.log($('#input').contents()) you will be able to see the entire object in the console.
So, in that case, it's better to use text(), that get only the text content of the element matched.
After getting the text, then set it to the input with val();
the example below shows this. (I added a timer just to better represent the code working, you can remove it and let only the code that is inside).
Also, if you want to keep the text in the div, remove the part where I used .text('');
setTimeout(function(){
input = $('#input').text();
$('#output').val(input);
$('#input').text('');
}, 1500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='' id="output">
<div id="input">Abcdef 1234567890</div>
Related
I need to get the value from a "p" element, I draw this "p" with jQuery and it's ok, then I have a button and when I click on it I want to display the value from "p" element but I don't get any information, here is a simple code example:
$(document).ready(function() {
$('#c').click(function() {
var p = $('#p1').val();
alert(p);
});
draw();
});
function draw() {
var html = "";
html += '<p id="p1">Hi</p>';
$('#d').html(html);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="c">Click</button>
<hr />
<div id="d">
</div>
How can I solve this? I don't get any console error.
Change :
var p = $('#p1').val();
To :
var p = $('#p1').text();
.val() only returns the value from input, textarea and select elements. If you just want to read the content of an element, you should use .text() or .html(). The first returns just the text, and the second – HTML content of an element.
Here is the quote from jQuery
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
So as #ehsan suggested, use .text() method if you want to get content as text.
.val() is used to get the value of input, select and textarea elements.
If you want to get the text inside an element (e.g: div, p, etc), you need to use .text().
So, in your case, you need to change this:
var p = $('#p1').val();
for this:
var p = $('#p1').text();
Note: If you want the full html code inside an element, you need to use .html().
Sources:
http://api.jquery.com/val/
http://api.jquery.com/text/
http://api.jquery.com/html/
you can also use var p = $('#p1').html();
I'm probably being especially dense about this, but I can't get an element to return using prev(). My basic HTML structure is:
<div>
<table></table>
</div>
<input type="button">
Where when I press the button, I want to get the previous element (the div element). To achieve this my button has a function attached to it with
var nearestDiv = $(this).prev();
When I've checked the contents of nearestDiv in the console it appears to be some kind of JQuery object rather than a HTML div. I've tried popping .val() at the end of .prev() but this comes back empty. How can I get the div element?
Note that my button is generated on the fly and doesn't have anything which identifies it.
you need to use jquery get function, to get a native html object and not the jquery wrapper:
$("input").on("click",function(){
console.log("jquery wrapper:",$(this).prev());
console.log("native html div object:",$(this).prev().get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table></table>
</div>
<input type="button">
If your html structure is same as you provided in the question, it will definitely return the div element. Note that there is no val() method for div element, you need to either use .html() or .text() inorder to get the contents.
$("input[type='button']").click(function () {
var div = $(this).prev();
alert(div.html());
alert(div.text());
});
Fiddle
You need to give .text() or .html() for standard HTML Elements. So your code should be:
var nearestDiv = $(this).prev().html();
var nearestDiv = $(this).prev().text();
When I am printing 'this' instance in alert box, it is printing something like this.
[object Object]
But the actual content in it is
<dl>
<dt>
my Name <span> John Krishna </span>
</dt>
<dd>
<span>My fathers name</span>
</dd>
</dl>
I want to display only 'my Name' instead of [object Object]. I mean what ever content of span in that 'dt' I want to display it in my alert box.
For this I tried out around in google, every where I am getting solutions like use child, or using inner html content and in some solutions someone written for loops. But I don't want to write any for loops around it which makes my code large.
Some one please suggest me some way that how can I print only "my Name" in alert box.
It depends on how you did the selection. If it is on the whole dl tag, than it should be something like this
alert($("dl").find("dt").clone().find("span").remove().end().html());
Where dl is an example selection. I don't know how you get it (by id, class etc.)
if you're selecting dt tag directly, than you should use a shorter version
alert($("dt").clone().find("span").remove().end().html());
It sounds to me like you're trying to alert an entire object. You'll need to make use of jQuery's text() method to display only the element's text.
If this is already selecting the span element you're after, you can simply use:
alert($(this).text()); // Instead of alert($(this));
I need only text inside 'dt' and content inside span should not be printed
For this we can use a regular expression to replace the <span> content from the dt element's HTML:
alert($('dt').html().replace(/<span>.*<\/span>/,''));
Here's a JSFiddle demo of this in use.
This is 96% faster than using cloning the element as some of the other answers below have suggested.
Add an id to the span (e.g. <span id="myname">Test Name</span>) and then match on the id in jQuery (using $("#myname")) and alert the text of that element to return what you need.
For example:
alert($("myname").text());
try to map : collecting them into an array instead of two calls to $:
var texts = $('span').map(function(){
return this.previousSibling.nodeValue
});
texts[0]; // "Some text followed by "
texts[1]; // " and another text followed by "
alert(texts[0]);
Hope it will help
you will need to use:
$(this).html();
try this:
var name=$(this).children('dt').children('span').text();
alert('name --->'+name);
Thanks
Use:
alert($(this).find("dt span").text());
Getting the text outside of the span is a little tricky in jQuery. I found this code here:
var myName = $(this).find("dt")
.clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text();
I have a javascript program to filter a list of things in a HTML select control by typing a regular expression into an input (text) box. I can do the following to correctly filter a specific select control:
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist(document.myform.myselect);
filter.set(this.value);
});
});
but I have used a custom attribute (something one can now do in HTML5) called data-filterable. The attribute will store the name of the select control that is to be filtered so that JS can use the name of the control to filter the list. This would be a good idea because I will have a general function to filter any select box rather than a specific one.
Any ideas how I do this? I need something like this in the HTML:
<input data-filterable='{"to":"#selectbox1"}' size="30" type="text" />
but I'm not sure exactly what I'm doing here and what to do with the JS.
Thanks guys :).
Try this:
<input data-filterable="#selectbox1" size="30" type="text" />
$(function() {
$('input[data-filterable]').keyup(
function() {
filter = new filterlist($($(this).data('filterable'))[0]);
filter.set(this.value);
});
});
To break down the expression $($(this).data('filterable'))[0]:
$(this) wraps this in a jQuery wrapper. In our context, since it's a jQuery keyup event handler, this references the <input> DOM node.
$(this).data('filterable') retrieves the contents of the data-filterable attribute as a string. In our case, it's #selectbox1.
After that this string gets passed in to jQuery as a selector: $($(this).data('filterable')).
Finally, we take the 0'th element of the returned array which should be the DOM element of the target selectbox. Of course, if there isn't a selectbox which fits the selector this will fail rather miserably. If you suspect that this is a real scenario, check the .length of the returned array first.
I have a string of html text stored in a variable:
var msg = '<div class="title">Alert</div><div class="message">New user just joined</div>'
I would like to know how I can filter out "New user just joined" from the above variable in jQuery/Javascript so that I can set the document title to just the message.
Like this:
document.title = $(msg).filter("div.message").text();
Note that if the message changes to be wrapped in an element, you'll need to replace filter with children.
EDIT: It looks like the div that you want is nested in other element(s).
If so, you can do it like this:
document.title = $("div.message", msg).text();
Explanation: $('<div>a</div><div>b</div>') creates a jQuery object holding two different <div> elements. You can find the one you're looking for by calling the filter function, which finds mathcing elements that are in the jQuery object that you call it on. (Not their children)
$('<p><div>a</div><div>b</div><p>') creates a jQuery object holding a single <p> element, and that <p> element contains two <div> elements as children. Calling $('selector', 'html') will find all descendants of the elements in the HTML that match the selector. (But it won't return the root element(s))
This is a hack and not very clean, but it should work:
add a div node and set its html to your text message,
get the text of the added element and store it in a variable
destroy the node
set the title with the contents of the variable in step 2