Get a Div Value in JQuery - javascript

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>

Related

How to call an div's attributes value using a function if there are many div's with the same function?

I have the following code:
function openCanviewer() {
var cid = $(this).data('cid');
alert(cid);
}
And the HTML:
<div onclick="openCanviewer();" data-cid="ID OF CAN FROM DATABASE"></div>
My problem is that when I click the element with the onclick function, which I have many of because they get inserted from the database, the alert is just showing "undefined" instead of the contents of the data-cid attribute. Does someone have any idea what I have done wrong, or what I am missing here?
To capture the exact element, pass this from the element's click event handler
function openCanviewer(element) {
var cid = $(element).data('cid');
alert(cid);
}
<div onclick="openCanviewer(this);" data-cid="ID OF CAN FROM DATABASE"></div>
^^^ you have a typo here
Snippet
function openCanviewer(element) {
var cid = $(element).data('cid');
alert(cid);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div onclick="openCanviewer(this);" data-cid="ID OF CAN FROM DATABASE">Click</div>
$('#mi').click(function() {
var cid = $(this).data('cid');
alert(cid);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mi" data-cid="ID OF CAN FROM DATABASE">hello</div>
In general you shouldn't use inline events like onclick="openCanviewer();", you should always keep js, css and html separate.
For your problem you could use delegate event listening:
function openCanviewer() {
var cid = $(this).data('cid');
alert(cid);
}
$(document).on('click', '[data-cid]', openCanviewer)

How can I add my own <divs> to a container dynamically?

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

How to select textarea and check if it is readonly?

I am struggling with jQuery. I want to write a script which checks if the text area sharing the same parent (list item) with the button is read-only when that button is clicked. Here is the HTML:
...
<li>
<h1>Title</h1>
<button type="button" onclick="javascript:confirmDelete();">Delete</button>
<button type="button" onclick="javascript:toggle();">Toggle</button>
<textarea class="readOnly" readonly="true">Some text</textarea>
</li>
...
And the script:
<script language="JavaScript">
<!--
...
function toggle()
{
var textArea = $(this).parent("li").children("textarea");
var isReadOnly = textArea.attr("readonly");
if (isReadOnly == "true") {
alert('It\'s read-only.');
} else {
alert('It\'s not read-only.');
}
}
//-->
</script>
It appears that I cannot get passed the var textArea = ...
Update 1:
OK, I broke apart the selection in order to help myself analyze the problem:
...
var btn = $(this);
console.log(btn); //returns value, but not sure what exactly
var li = btn.parent();
console.log(li); //returns value, but not sure what exactly
var textArea = li.children('textarea');
console.log(textArea.prop('tagName')); //returns unidentified
So, there's the error. I can't seem to understand what is actually wrong, as I cannot really learn much if all the output I get from the debug is an object (and I don't even know what it represents; is it an element, or array ...) or unidentified. jQuery is not exactly intuitive.
The property is case sensitive. Try instead
var isReadOnly = textArea.attr("readOnly");
if it is the only you likely need:
...find("textarea")[0];
not
...children("textarea");
or simply $(this).siblings("textarea")[0];
OR select directly
var mylist = $(this).siblings("textarea.readOnly");
if (mylist.length > 0)//true if it is
There are some errors in here.
Firs of all, turns out that when the attribute "readonly" is active, it doesn't have a "true" value, but a "readonly" value.
On the other hand, if you invoque a function by onclick (and I'm not 100% sure), you cannot use $(this). I'd recommend you to do (after giving some ID to the trigger button, or anything to identify it):
$(function() {
$("button#my-button").bind("click", function() {
if ($(this).siblings("textarea").attr("readonly") == "readonly") {
alert("It's readonly");
} else {
alert ("It's not");
}
});
});

Finding elements in an object that started as a string

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/

how to get tinyMCE editable for a cloned textarea by cloneNode(true) function

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.

Categories