I found a lot of info about this, but I haven't foundanything that could help me yet.
My problem is that I have got a div with its id and it supposes to be a container (#cont_seguim).
I have a menu on the right side which contains circles (made by css and filled with text), like following:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
where b and n are the format for background and text.
When I click a circle, this one must be added to the container (notice that each circle has got its own text), but I can't get that.
I made and array and used alert() to test that click works, and it does, but append() doesn't even work to print text, and I don't know why.
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append(text);
});
return text;
});
</script>
Thank you for your responses!
Your code seems to work fine (if you fix the different class name used in html vs script circulo_menu vs circle_menu)
Demo at http://jsfiddle.net/7jbUj/
To add the whole circle append the whole element and not its text by using .append(this)
$(".circle_menu").click(function() {
$("#cont_seguim").append(this);
});
Demo at http://jsfiddle.net/7jbUj/1/
To add a copy of the circle, so you can add multiple of them use the .clone() first..
$(".circle_menu").click(function() {
var clone = $(this).clone(false);
$("#cont_seguim").append(clone);
});
Demo at http://jsfiddle.net/7jbUj/3/
Inside the click handler, this refers to the clicked element. And since you bind the click handler on the circle_menu element, this refers to that. You can use it directly for the appending or clone it to make a copy first..
unable to understand properly, hope below one can help you.
<script type="text/javascript">
$(document).ready(function() {
$(".circulo_menu").click(function() {
var myText = $(this).html();
alert("calling " + myText);
$("#cont_seguim").html(myText);
});
});
</script>
make sure classname and id name will remain same as html
Try using html() instead of text().
Try this: Demo
HTML:
<div class="circle_menu b">
<div class="text_menu n">ECO</div>
</div>
<div id="cont_seguim"></div>
Javascript:
$(document).ready(function() {
$(".circle_menu").click(function() {
var text = $(this).html();
console.log("calling " + text);
$("#cont_seguim").append(text);
});
});
Try this:
$( ".container" ).append( $( "<div>" ) );
source
use
$("#container").append($("<div/>", {id:"newID",text:"sometext"}));
You could try
<script type="text/javascript">
var arrayS = new Array();
$(document).ready(function() {
$(".circulo_menu").click(function() {
var text = $(this).text();
alert("calling " + text);
$("#cont_seguim").append($(this).html());
});
return text;
});
</script>
By this way the clicked circle element get added to div
Related
<div class="albumclass">
<img width="100" height="100" data-assigned-id="9" src="/Content/images/fold.png">
<p>15Sep2015</p>
</div>
The above code is generated dynamically through jQuery. After that I need to display the content of <p> ie., '15Sep2015' by clicking on the above image. How can I get this? I used the below code:
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).closest("p").text();
alert(txt);
}
But that alerts nothing.It not possible to take content implicitly because a lot of similar div will be there.
The .closest() gets the parent. So use .siblings() or .next. I have used .next():
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).next("p").text();
alert(txt);
}
You can go up to parent div and find p using find() :
$('.album_inner').on('dblclick', '.albumclass img', function (e) {
var txt = $(this).closest("div").find('p').text();
alert(txt);
}
Hope this helps.
$('.albumclass').on('click', function(){
var p_text = $(this).children('p').text();
alert(p_text);
});
Why not try adding a class to the 'p' tag so that u can get the element by a class selector and see
var text = $('.class').text();alert(text);
or u may try
$(document.body).on('click','.class',function(){
});
I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed
I've got a textarea:
<p>
Input:<br>
<textarea name="text_input" id="text_input"></textarea>
</p>
I'm trying to treat the textarea value as a jQuery object to be able to find each hypertext link.
That textarea has some related script code:
<script>
$('#text_input').change(process).keyup(process);
function process(){
var html = $('#text_input').val();
$(html).find("a").each(function(i,elem){
alert('got here');
});
}
</script>
In that textarea, I paste, for example, the text:
<html>
<body>
hello
</body>
</html>
Problem is, the alert() never fires. What am I missing? I guess the $(html) line has issues.
Change $(html).find... into $('<div/>').append(html).find... and it will work.
http://jsfiddle.net/NQKuD/
If you want to treat the text as a complete HTML document, you'll have to parse it yourself rather than get jQuery to do it for you. Here's one approach:
function process() {
var html = $('#text_input').val();
var rgx = /<a [^>]*href\=\"?([^\"]+)\"?[^>]*>([^<]*)<\/a>/gi;
var result,url,link;
while (result = rgx.exec(html)) {
url = result[1];
link = result[2];
alert('url='+url+'\nlink='+link);
}
}
http://jsfiddle.net/NQKuD/2/
var html = $('#text_input').val(); <-- that is wrong
use var html = $('#text_input').html(); instead.
test code:
<textarea id="t123">text<something more</textarea>
<script>
window.alert($("#t123").val());
window.alert($("#t123").html());
</script>
also pay real close attention to what you get in the alert.
update:
okay, so difference would be that .html() would refer to the original content of the text area, where as val() would use with value entered/changed.
so, this would fix the problem:
$(document).ready(function(){
$('#text_input').change(function(){
var html = $('#text_input').val();
var dummy = $("<div></div>").html(html);
dummy.find("a").each(function(i, elem){
window.alert(elem);
});
});
});
You can create an invisible html placeholder and insert the html there (this sounds like a very dangerous method though, :P but I see no other way to use jquery to parse input text).
http://jsfiddle.net/y6tt7/1
<div id="placeholder" style="display:none"></div>
$("#placeholder").html(html).find("a").each(function(i,elem){
alert('got here 2');
}).html("");
If you are having trouble firing the event when pasting using "Paste" in the OS menu, try the input event:
$('#text_input').bind('input', process);
Also, to be able to parse the input content using jquery, you should probably append it to a DOM node:
$('#text_input').bind('input', process);
function process(){
var html = $('#text_input').val();
$('<div>').html(html).find('a').each(function(i, elem) {
alert('got here');
});
}
Example: http://jsfiddle.net/5npGM/9/
jQuery will strip out the html and body elements from your HTML string, the find function will then fail to find any a elements as it is searching inside a single a element.
See this question - Using jQuery to search a string of HTML
To prove the point, the following JavaScript will work if you put it inside a document ready block -
$('#text_input').change(process).keyup(process);
function process() {
var html = $('#text_input').val();
$('<div>' + html + '</div>').find("a").each(function(i, elem) {
alert('got here');
});
}
Demo - http://jsfiddle.net/Y5L98/4/
When I try to clone a textarea by using cloneNote(true), the cloned textarea is not editable. Does anyone know how to resolve the problem? The sample codes show as following:
<html>
<head>
<script type="text/javascript" src="/javascripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
theme : "advanced",
mode : "textareas",
});
</script>
<script type="text/javascript">
testclonenode = {
addAbove : function (element) {
var rowEl = element.parentNode.parentNode.parentNode;
var rowElClone = rowEl.cloneNode(true);
rowEl.parentNode.insertBefore(rowElClone, rowEl);
return false;
}
};
</script>
</head>
<body>
<table>
<tr><td>
<textarea name="content" style="width:100%">this is a test </textarea>
<p> <button onclick='return testclonenode.addAbove.call(testclonenode, this);'> Add above </button>
</td></tr>
</table>
</body></html>
It does not work that way. Also, it is impossible to move a tinymce editor using dom manipulation.
The tinymce wiki states the following:
mceAddControl
Converts the specified textarea or div
into an editor instance having the
specified ID.
Example:
tinyMCE.execCommand('mceAddControl',false,'mydiv');
So when you clone a textarea there is another problem: You will have the same id twice which will result in errors accessing the right tinymce instance.
I got this to work by using an ID which is incremented each time my clone function is triggered, so
var insertslideID = 0;
function slideclone() {
$('<div class="slides"><textarea name="newslide['+insertslideID+'][slide_desc]" id="mydiv'+insertslideID+'"></textarea></div>').insertAfter('div.slides:last');
tinyMCE.execCommand('mceAddControl',false,'mydiv'+insertslideID);
insertslideID++;
}
$('input[name=addaslidebtn]').click(slideclone);
Seems to work.
A wee bit tidier, I just use a number for my id - copy1 is the name of my button - I add the new element to the end of my container.
var count = 0;
$("#copy1").click(function(){
var newId = count;
$( "#first" ).clone().appendTo( "#container" ).prop({ id: newId, });
tinyMCE.execCommand('mceAddControl',false,newId);
count++;
});
I ran into a similar problem, except my element IDs (not just textareas) could be anything, and the same ID was always appearing twice. What I did is supposed to be horribly inefficient but there was no noticeable performance loss with dozens of elements on the page.
Basically I removed the TinyMCE ID first (uses jQuery):
$(new_element).find('.mce-content-body').each(function () {
$(this).removeAttr('id');
});
Then I reinitialized TinyMCE for all relevant elements.
I have a page containing the following div element:
<div id="myDiv" class="myDivClass" style="">Some Value</div>
How would I retrieve the value ("Some Value") either through JQuery or through standard JS? I tried:
var mb = document.getElementById("myDiv");
But the debugger console shows "mb is null". Just wondering how to retrieve this value.
---- UPDATE ----
When I try the suggestion I get: $ is not a function
This is part of a JQuery event handler where I am trying to read the value when I click a button. The handler function is working but it can't interpret the jQuery value it seems:
jQuery('#gregsButton').click(function() {
var mb = $('#myDiv').text();
alert("Value of div is: " + mb.value);
});
$('#myDiv').text()
Although you'd be better off doing something like:
var txt = $('#myDiv p').text();
alert(txt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>
Make sure you're linking to your jQuery file too :)
myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
alert ( myDivObj.innerHTML );
}else{
alert ( "Alien Found" );
}
Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]
function showDivText(){
divObj = document.getElementById("myDiv");
if ( divObj ){
if ( divObj.textContent ){ // FF
alert ( divObj.textContent );
}else{ // IE
alert ( divObj.innerText ); //alert ( divObj.innerHTML );
}
}
}
if you div looks like this:
<div id="someId">Some Value</div>
you could retrieve it with jquery like this:
$('#someId').text()
your div looks like this:
<div id="someId">Some Value</div>
With jquery:
<script type="text/javascript">
$(function(){
var text = $('#someId').html();
//or
var text = $('#someId').text();
};
</script>
You could use
jQuery('#gregsButton').click(function() {
var mb = jQuery('#myDiv').text();
alert("Value of div is: " + mb);
});
Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.
You could also use innerhtml to get the value within the tag....
You can do get id value by using
test_alert = $('#myDiv').val();
alert(test_alert);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"><p>Some Text</p></div>