javascript: get contents of textarea, textContent vs. innerHTML vs. innerText - javascript

I am having trouble getting the contents of a textarea with js. I feel like I've done this many times before without problems but something is throwing it off or I have a mental block.
html
<textarea id="productdescript">test copy..asdfd</textarea><button value="Enter" onclick="addProduct()">
js
function addProduct() {
var descript = document.getElementById('productdescript').textContent;
alert(descript);
}
Firefox is the only browser I have currently.
When I use textContent, the alert box appears but it is blank.
When I use value, the alert box appears and says "Undefined"
When I use innerHTML, all the HTML appears including the tags.
Also, I understand that textContent only runs in FF and for cross browser compatibility you need to do something like innerText and textContent but textContent is not working in FF. There is no jquery on this app
What is the correct cross browser way to get contents of textarea! Thanks for any suggestions.

For textarea, you could only use .value in your scenario (I tested your given code and it works fine).
.
Also,
1) keep in mind that you call this function addProduct() ONLY after your element is mentioned in the code, otherwise it will be undefined.
2) there must not be another element with id as productdescript
3) there must not be a JS variable called productdescript

This are your code?
you write document.getElementByID.... and the "D" should be written lowercase "d"
document.getElementById('productdescript').textContent;

Related

getElementsByClassName not working on firefox

I was trying to print a anual report but i need to change 2 texts around the page, one of them has only a class attribute. Im new at js so i made this.
<div id="formBusqPresElec:dtResBSPE_paginator_bottom" class="ui-paginator ui-paginator-bottom ui-widget-header">
<span class="ui-paginator-current">Mostrando 1-20 de 1626 registros</span>
</div>
And the other has an id.
<div id="fBusqSPE">Mostrando 20 de 1626 registros</div>
I made it work on Chrome
function imprimir() {
var oldText = document.getElementById('fBusqSPE').innerText;
document.getElementById('fBusqSPE').innerText = document.getElementsByClassName('ui-paginator-current')[0].innerText;
window.print();
document.getElementById('fBusqSPE').innerText = oldText;
}
But in firefox throws
[10:48:48.330] TypeError: document.getElementsByClassName(...)[0] is
undefined
Edit: So let me explain more.
Actually im working inside 2 iframes, which the first one is for the menu, and the other one is for more options. Then the central iframe is used to show the actual report.
Maybe I must define which iframe I want to retrieve those elements.
There are 2 problems here. The first causes your error of document.getElementsByClassName(...)[0] is undefined and once overcome, the second is that Firefox does not support innerText
The only way to generate the specified error in Firefox is for no elements with the specified class being present on the page. This is demonstrated by the following code
<div class="a-test"></div>
// on page load
document.getElementsByClassName("b-test")[0].innerHTML="Test";
JSFiddle:http://jsfiddle.net/UL2Xs/
If you watch the console when running the above fiddle, you'll see the same error as you get.
Is it possible that your javascript is running before the page has finished loading?
The second, and more minor issue is that FireFox does not support innerText. You should use .textContent or possibly .innerHTML.
You probably should use:
iframe.contentDocument.getElementsByClassName(...)
(see: contentDocument for an iframe)
Basically .innerText will not work in FF. FF uses textContent property.
var text = element.textContent;
element.textContent = "this is some sample text";

replace text function not working in explorer

I have a js replace function to replace text next to two radio buttons on a pre set form.
Script is as follows.
document.body.innerHTML=document.body.innerHTML.replace("Payment by <b>Moneybookers</b>
e-wallet<br>","");
document.body.innerHTML=document.body.innerHTML.replace("Maestro, Visa and other credit/debit cards by <b>Moneybookers</b>","Pago con Diners Club, Mastercard o Visa");}onload=x;
The script works fine in Chrome and Firefox, however, the script is not actioned in Explorer.
I believe it has something to do with there being , / - within the text I am replacing? When I use the function to replace text with no , / - in the text - it works fine in explorer, however, for example when I try to replace text.. - "Maestro, Visa and other credit/debit cards by Moneybookers" this does not work in explorer.. I'm assuming because of the coma and forward slash. Honestly I've tried everything but just can not get this to work. Any help would be greatly appreciated!!
Not sure whether it's related (I'm a Mac user without IE) but you shouldn't use multiline strings. Use \n instead.
What is returned by innerHTML varies from one browser to an other, because there is no standard about it (the content will be the same, but the way it's displayed can be different). Doing replace like that is likely to fail on some browser. You should just take an other approach to do your replace.
A better approach would be to wrap the text you want to replace with a span, this way you can more easily target the content you want to replace.
<span id="thatFirstThing">Payment by <b>Moneybookers</b>e-wallet<br></span>
An after you can do
document.getElementById("thatFirstThing").innerHTML = "";
P.S.: Doing innerHTML replace on the body also has a huge side-effect. Since you are replacing the content of your hole page. All the event handler that where bind on your page will disappear.
Edit: If you can't modify the HTML page, it's a little bit more tricky, because the DOM is not well adapted to do such thing. What you could do is to target parent element by navigating through the DOM with document.getElementById and childNodes. And once you have your parent element just write the new content you want, without doing replace.
In the end it would look something like this :
document.getElementById("someSection").childNodes[0].childNodes[1].childNodes[0].innerHTML = "";

Inserting <style> tags from a string in Internet Explorer

I'm loading a string via AJAX that reads like
<style>[some definitions]</style>
<h1>Lots of Markup</h1>
<p>follows here</p>
Using Webkit/Gecko everything works as expected — the markup is inserted, styles are applied. In IE (8) though the style-definitions are ignored. Actually, if you use the developer tools they are gone.
You can see in this JS-Fiddle that it doesn't work: http://jsfiddle.net/J4Yzr/
Also, I've seen that trick that you create a temporary DOM-Object, set it's innerHTML to your markup and extract your markup as DOM-Objects from your temporary element. That doesn't work with style tags (if I did it right, I'm using prototypeJS):
var text = '<style>h1{color:red;}</style> style added',
el = new Element('div').update(text);
console.log(el.firstChild);
//is a HTMLStyleElement in Webkit but a [object Text] in IE
Does anyone have a suggestion how to properly apply the <style> in IE if you get it from such a string?
I had the same problem, so I tried your solution, but guess what? When I stripped the out after rendering markup retrieved via Ajax, the tags disappeared from the DOM! Back to square one.
So my solution is to prepend this instead:
<hr style='display:none'/>
Which did the trick nicely. Thank you so much for solving this issue.
Ok, it's crazy. Add a <br/>-Tag in front of your string and it works in Internet Explorer.
<br/><style>[some definitions]</style><h1>Lots of Markup</h1>
You don't even need to create that temporary DOM-Object to insert code into. Just append it in your site.
What I'm doing now it insert the code with a <br/>-Tag and remove the <br/> afterwards. It's messy but it works.

Changing content using innerHTML with a non-standard element in Internet Explorer

I have the non-standard element
<testele></testele>
In every browser except IE, this bit of JavaScript will successfully change the content of the above element
document.getElementsByTagName("testele")[0].innerHTML = 'hi';
However, if I change the <testele> to just a <span> (in the HTML and the JavaScript), it now successfully changes the content of the element in every browser, including IE.
Is there any fix? I have searched around and tried a bunch to no avail.
Use document.createElement("testele") before it is rendered. This script must be included before the document encouters a <testele>:
http://jsfiddle.net/gilly3/LjwbA/
document.createElement("testele");
window.onload = function() {
document.getElementsByTagName("testele")[0].innerHTML = 'hi';
};
If you try to do document.createElement("testele") after a <testele> has been parsed by the browser, it's too late.
Take a look at innerShiv, a Javascript plugin which aims to solve this.

Changing input text value with Javascript doesn't change display

I'm trying to change the value of a text input field based on user actions. I'm doing it like this:
document.getElementById(textFieldID).value = newValue;
It isn't quite working -- the original text in the field remains on the screen, unchanged. However, when I submit the form, it behaves as though the value was indeed changed correctly. (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.) Anybody have any insights? Is there something I need to be doing to redraw the input element?
Edit: Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:
<script LANGUAGE="JavaScript" TYPE="text/javascript">
function changeText(changeSelector)
{
var myindex = document.getElementById(changeSelector+"Recent").selectedIndex;
var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
document.getElementById(changeSelector).value = SelValue;
document.getElementById("historicalText").value = SelValue;
document.getElementById("historicalTextSelect").value = changeSelector;
}
</script>
<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">
<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.
Edit 2: It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses. (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.) It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away. If it doesn't ... should be interesting.
Edit 3: Yup. Fscking JSpell. Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed. My thanks to everybody who tried to help; +1's all around, wish I could give more.
I have confirmed that the culprit is indeed JSpell, and that the precise trouble spot is this line:
window.onload=jspellInit;
Despite the prayers mentioned in Edit 2 above, making sure it was configured correctly did NOT make the problem go away. And this line is indispensable to JSpell's functionality. I don't know if JSpell always hoses Javascript functionality this way, or if there's some sort of perfect storm of factors that's causing it to pick a fight with my page, but that is indeed the source of my problems.
My thanks to everybody who tried to help. This was obviously a bit of a no-win in terms of getting the right answer, since it was caused by a component that was seemingly entirely unrelated and thus didn't get mentioned by me, but you at least confirmed that I was (in theory) doing things right and not simply going insane.
Is the document's id actually "textFieldID" or is "textFieldID" a javascript variable that contains the ID of the text input to change? If it is not a variable, I believe you should make it:
document.getElementById('textFieldID').value=newValue;
It's hard to debug this without the context, since the code you have ought to work fine. Can you confirm that you've got the right node by doing something like:
document.getElementById(textFieldID).style.border = "4px solid red";
What does any other element on the page have a name attribute that is the same as the id?
Internet Explorer 8 and later. In IE8
mode, getElementById performs a
case-sensitive match on the ID
attribute only. In IE7 mode and
previous modes, this method performs a
case-insensitive match on both the ID
and NAME attributes, which might
produce unexpected results. -
http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx
Try alerting your the nodeName and id ofr the returned element and make sure its the input you expect.
Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.

Categories