When I click the button to insert bbcode to textarea The console alert : "Uncaught ReferenceError: myTextarea is not defined". Can you help me solve this problem ?
I have a code:
$(function(){
function formatText(el,tagstart,tagend){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
var newText='['+tagstart+']'+selectedText+'[/'+tagend+']';
if(document.selection){//IE
el.focus();
var st=getCaret(el)+tagstart.length+2;
document.selection.createRange().text=newText;
var range=el.createTextRange();
range.collapse(true);
range.moveStart('character', st);
range.moveEnd('character',selectedText.length);
range.select();
el.focus();
}
else{//Moz
var st=el.selectionStart+tagstart.length+2;
var end=el.selectionEnd+tagstart.length+2;
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
el.focus();
el.setSelectionRange(st,end)
}
}
function getCaret(el) { // IE mission is tricky :)
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
return rc.text.length + add_newlines;
}
$("elements").after('<form action="/post" method="post" name="myForm"><textarea placeholder="Comments..." name="myTextarea"></textarea><span class = "repbbcode" title = "Bold" value="b" style="font-weight:bold" >B</span></form>');
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
});
});
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
^^^^^^^^^^
});
myTextarea is not defined. There is no
var myTextarea = ....
in your code. You need something like
$(".repbbcode").on("click" , function(){
var myTextarea = $("[name='myTextarea']).get(0);
formatText(myTextarea,'b','b');
});
You need to add var myTextarea = document.getElementsByName('myTextarea')[0];
$(".repbbcode").on("click" , function(){
var myTextarea = document.getElementsByName('myTextarea')[0]; // added myTextarea
formatText(myTextarea,'b','b');
});
In this line of code:
formatText(myTextarea,'b','b');
You have to pass as the first argument a DOM element. You can't just pass the name of a DOM element. It's easiest to use document.getElementById("myTextArea") and then set id="myTextArea" in your element.
So, your textarea HTML would be <textarea id="myTextArea" ...>.
And, your code would be:
var textareaElement = document.getElementById("myTextArea");
formatText(textareaElement,'b','b');
If you want to get the DOM element by name, you can do that too:
var textareaElement = document.getElementsByName("myTextArea")[0];
formatText(textareaElement,'b','b');
What is different here is that document.getElementsByName() returns a list of potentially multiple elements so you have to reach into that list with [0] to get the first item in the list to pass to your function.
There are many different ways to do this (using name, class, id, etc...). Usually if you are trying to get one unique element in a page, you would give it an id and use document.getElementById() or the jQuery equivalent.
Related
hey i create an Element with id and an eventListener. so when i click a link i want to get the id.
But i don't have Control of this created Element. "cannot set property ... of null".
function insertLink(text,link,window,underline)
{
var doc = document.getElementById("iframe_editor").contentWindow.document;
var sel = doc.getSelection();
var count = parseInt(document.getElementById("counter").value);
if (sel.rangeCount > 0)
{
count ++;
document.getElementById("counter").value = count;
var range= sel.getRangeAt(0);
myParent=document.getElementById("iframe_editor").contentWindow.document.body;
alink=document.createElement("a");
var text = document.createTextNode(document.getElementById("linktext").value);
alink.href = document.getElementById("linkhref").value;
alink.id = "testid"+count;
alink.appendChild(text);
myParent.appendChild(alink);
range.insertNode(alink);
alink.addEventListener( 'click', function(){
loadElement(count.toString());
},count );
}
}
function loadElement(t)
{
alert(t);
document.getElementById("testid"+t).innerHTML = "<a href = ''>Test</a>";
}
When i check the variable t in loadElement i get back the right number. But i cannot Change this element with innerhtml.
why not?
The link you inserted does not exist in your actual web page, but inside your iframe. So, you have to access it from the iframe:
document.getElementById("iframe_editor").contentWindow.document.getElementById("testid"+t).innerHTML = "<a href = ''>Test</a>";
I have the following code:
var done = function(el) {
var tds = el.parent().parent().find('td');
for (var i in tds) {
tds[i].css('backgroundColor', 'green');
}
};
done($(this));
Where $(this) points to the element inside td tag - so I'm getting all nearby td tags and changing background color on them.
The problem is that it throws an error that tds[i].css function is undefined.
Doing this in clear javascript, with passing this, works perfectly, like so:
var done = function(el) {
var tds = el.parentNode.parentNode.getElementsByTagName('td');
for (var i in tds) {
tds[i].style.backgroundColor = 'green';
}
};
done(this);
What's wrong?
Maybe try this :
var done = function(el) {
var tds = el.parent().parent().find('td');
$(tds).each(function(){
this.css('backgroundColor', 'green');
});
};
done($(this));
I am trying to convert my script using addEventListener with getElementById on a var for a getElementByClassName but this doesn't work. How to fix it?
See my code
Javascript:
var input = document.getElementByClassName('myClass');
_slider.noUiSlider.on('update', function( values, handle ) {
var value = values[handle];
if ( handle ) {
input.value = Math.round(value);
});
input.addEventListener('change', function(){
_slider.noUiSlider.set([null, this.value]);
}, false);
HTML:
<input type="number" class="myClass">
This script work perfectly if I find my div with an ID, but not work with a CLASS.
There is no getElementByClassName. There is getElementsByClassName that returns a collection. If there is only one, than select the first index.
var input = document.getElementsByClassName('myClass')[0];
Other option is querySelector
var input = document.querySelector('.myClass');
My guess is that you do not have just one element, but multiple, than you need to loop over the collection.
var inputs = document.getElementsByClassName('myClass');
//or
//var inputs = document.querySelectorAll('.myClass');
for( var i=0; i<inputs.length; i++){
inputs[i].addEventListener("click", function() { console.log(this); } );
}
var input = document.getElementById('id_name')
...here addEventListener will work because "id" will unique but in case of "class" there might be same values entered...So you have to select which element you want to manipulate...example ==>
var input = document.getElementsByClassName('class_name')[0] // after this addEventListener will work.
Hope this might help you :)
So I'm trying to collect what people are selecting on our site. Currently, it works EVERYWHERE, and I don't want that. I only want it if they are selecting in a certain DIV.
it's basically a simple modification to a script I found.
<script type="text/javascript">
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
document.oncopy = appendCopyright;
I tried modifying selection = window.getSelection(); but it just broke it :(
Basically, I want the above code, ONLY to work in a certain div, not the whole body
Probably you shouldn't use document.oncopy, instead try using div.oncopy where div is the div element you are interested in.
var selection = getSelection().toString(); is your solution - getSelection() returns a Selection object and you can get the string just by using .toString() method. More properties and methods of Selection object could be found here: https://developer.mozilla.org/en-US/docs/DOM/Selection
According to the Mozilla JS docs the selection class has a method containsNode. The following should work.
function appendCopyright() {
var theBody = document.getElementsByClassName("sbReview")[0];
var selection;
selection = window.getSelection();
// HERE's THE GOODS
// set aPartlyContained to true if you want to display this
// if any of your node is selected
if(selection.containsNode(aNode, aPartlyContained)){
var copyrightLink = '<br /><br /> - Read more at: '+document.location.href+'<br />©2012 <? printf($product. ' & ' .$spOrganization); ?>';
var copytext = selection + copyrightLink;
var extra = document.createElement("div");
extra.style.position="absolute";
extra.style.left="-99999px";
theBody.appendChild(extra);
extra.innerHTML = copytext;
selection.selectAllChildren(extra);
window.setTimeout(function() {
theBody.removeChild(extra);
},0);
}
}
document.oncopy = appendCopyright;
I am trying to loop through all elements in a given div and output the results (C# code i will use later) to the screen for testing.
so if i have html like this:
<div id="testDiv">
<test>
<a>aVal</a>
<c>
<cc>ccVal</cc>
</c>
</test>
</div>
i am trying to produce this string value:
HtmlElement.CreateNode("test").AddNode(CreateNode("a").addText("aVal")).AddNode(CreateNode("c").AddNode(CreateNode("cc").addText("ccVal"))
Right now i ahve this jquery in place, but i am unsure of how to drill down into the other nodes:
var x = "HtmlElement.";
$('div#testDiv').children().each(function () {
var nodeNameStr = this.nodeName.toLowerCase();
var nodeText = $(this).text();
x += "CreateNode(nodeNameStr).addText(nodeText)"
});
jsFiddle Example
$('#testDiv').find('*').each(function() {
// do stuff
});
Here's a more complete example than previous answers:
http://jsfiddle.net/4QtS5/
// returns the 'AddNode(...)' method call for every child.
function addChildren(element){
var command = "";
$(element).find("> *").each(function(){
command += ".AddNode("+createNode(this)+")";
});
return command;
}
// if the element has text, add the text
function addText(element){
var elementText = $(element).clone().children().remove().end().text().trim();
if(elementText) {
return ".addText(\""+elementText+"\")";
} else {
return "";
}
}
// returns the 'CreateNode(...)' method call for a node and all its children.
function createNode(element){
var nodeName = element.nodeName.toLowerCase();
var csharpCommand = "CreateNode(\""+nodeName+"\")";
csharpCommand += addChildren(element);
csharpCommand += addText(element);
return csharpCommand;
}
// begin
$("div#testDiv > *").each(function(){
var csharpCommand = "HtmlElement."+createNode(this);
console.log(csharpCommand);
});
You are looping through the direct children of your div, rather than all the children. To do so, use this code:
$('div#testDiv *').each(function(){
// Your Code
});
You can use the div id to get all the children in the following way:
$('#youDivId').children().each(function(){
alert(this.value);
});