IE 8 and getElementById() that is dynamic throws error - javascript

I have a function that is called whenever a select changes. If the select had an ID of "foo" there'd be a text field with an ID of "foo_other" after it that by default is styled "display:none".
If a value of "Other" is picked from the select, the function is supposed to display the text field, and set focus to it. If anything other than "Other" is chosen, it should hide the field and remove anything entered.
Works in FF, IE throws an error "Object required". I was trying to avoid doing an eval() around the dynamic variable... Any help is appreciated.
Code:
function checkOther(inObj){
var other_form_id = inObj.name + "_other";
if(inObj.value == 'Other')
{
document.getElementById(other_form_id).style.display = 'inline';
document.getElementById(other_form_id).focus();
}
else
{
document.getElementById(other_form_id).style.display = 'none';
document.getElementById(other_form_id).value = '';
}
}

My guess is you are having multiple IDs in one document (which is invalid), and IE is more picky about it than FF is. Could that be?

The stupid idiots from microsoft are getting the first id OR NAME.
I have a dynamically generated javascript and name and id of one html element (input) are different. But instead getting the element with specified ID, the idiots of IE8 are getting the first element with that NAME.
I believed they are idiots even i was working 15+ years as windows (visual studio) developer, but i didn't expect such a stupidness ...
Even later,
Hope this will help someone else, not the author of the post.
My solution was to add "id_" prefix for the id tag in order to be sure that the idiots are going to get exactly the normal one, nad not another with with the same name. In my case i'm using id tag for javascript things and the name tag for saving to the DB when the form is sent.

Related

Add text to value of textarea on blur without jquery

So, I have a textarea in a form that records comments. I am attempting to append the identity of the user entering the comment to the end of the comment when entered.
Here is the PHP that checks the user session and gets the name of the user:
<?php
//getting username - displays John Doe
$user = Mage::getSingleton('admin/session');
$firstname = $user->getUser()->getFirstname();
$lastname = $user->getUser()->getLastname();
$append = " [name](by ".$firstname." ".$lastname.")[/name]";
?>
The JavaScript that should be appending to the value on blur:
<script>
function addedcomment(){
var commentby = document.getElementById("#history_comment").value;
var commentby = commentby + '<?php echo $append; ?>';
document.getElementById('#history_comment').value = commentby;
}
</script>
The textarea that comments are entered into:
<textarea name="history[comment]" rows="3" cols="5" style="height:6em; width:99%;" id="history_comment" onBlur="addedcomment()"></textarea>
The code appears on the page exactly in the order and manner that it has been shown here, so the PHP sets the value of $append before the JavaScript appears. I am getting three errors in the dom console:
Uncaught TypeError: Cannot read property 'value' of null
addedcomment
onblur
The CMS I am using works with Prototype, so jQuery does not work all of the time (it seems it is selectively called in) even in noConflict mode.
Things I have tried:
Putting the JS below the textarea.
onblur vs onBlur
jQuery solution
This is because you are adding an un-needed "#" symbol. document.getElementById() requires only the name of the element's id (history_comment). The error is basically telling you that it can't get the property "value" of something that doesn't exist, i.e an element with the id of "#history_comment".You don't need a jQuery solution, what you have here is fine except for the typos.
Uncaught TypeError: Cannot read property 'value' of null
That is because there is no element with the ID "#history_comment". Only one with the ID "history_comment".
Also, changing a textarea's value works by changing its .innerHTML opposed to .value.
Same for reading the value from a textarea.
Why do you want to do this via Javascript?
Wouldn't it be better to do that after the post is submitted via PHP?
The way you are doing it right now, if I "blur" the textarea several times the text you add gets added several times.
Just to continuation to above Answers...
Native JavaScript api document.getElementById just takes id as is where Jquery require the shortcut notations like '#', '.' internally it will use same native api like document.getElementById.
And as text area is a input element, it would have value property, where for other document elements like div, span table would innerHTML property. Even input elements will have innerHTML property but will just return empty.

Submit form and return result to same page with javascript

Im trying to write a small js script that will let a user input a string of text and then output it wrapped in some html to the page.
I know how to do this with php, but it seems a little bit of an overkill for such a simple action, plus im always keen to learn something new.
I was playing around using document.myform.submit(); but i wasnt sure how to submit the form value to a variable and then output that var to the screen using document.write();
Any ideas how i would do this ?
Ive created a jsfiddle of the problem here - http://jsfiddle.net/pudle/axcLz/
There are many ways to do it. Here is the code that shows one of them:
document.getElementById("myform").onsubmit = function (event) {
var link = document.getElementById("mylink");
var textField = document.getElementById("text");
link.href = textField.value;
textNode = document.createTextNode(textField.value);
if (link.hasChildNodes()) {
link.removeChild(link.lastChild);
}
link.appendChild(textNode);
event.preventDefault();
};
jsfiddle: http://jsfiddle.net/TMJGH/5/
I added an id attribute to the a element to make things easier.
First line says that we want to change the function that handles "onsubmit" event in our form and then we define that function. The "event" argument is used only to call .preventDefault() in the last line which basically means that we don't want the form to be actually submitted.
We need to get access to DOM elements in the javascript code, so I used document.getElementById. Then I set the href attribute to the value of the textField. To change the actual link text I created a new text node with the value of the textField (it is possible to use textNode.innerHTML but that won't escape HTML code if someone inserts it in the text field). Then I check if our a element already has some text in it - if yes, it has to be removed. Finally I append the text element as a new child to our a element.
If you want to append more HTML nodes inside a node you can easily create them with document.createElement('element name') and append them to link. I also have to mention that jQuery makes playing with DOM a lot easier.

Adding Values to a DOM element after the element has been created

I'm looking over some pretty extensive code for a web page that is generated from XML/XSL and then has Javascript generate the layout on the fly. What I am having troubles with is that it seems IE (v.10 specifically) is showing that elements are Empty Text Nodes if there is no value, and then regular text (no editable field) if there is a value.
This seems to change the behavior of to be just straight un-editable text.
From what I can see, the first step is for the Javascript to generate elements via the DOM
input = document.createElement("input");
input.setAttribute("id", "blah");
input.setAttribute("type", "text");
Then it will append it to the parent.
Then what seems to happen is that a function is executed that runs through the page again and inserts any values that these fields have.
input.value = "Hello World";
Chrome and Firefox will display the input fields properly with their fields populated, but IE10 will only show the value as if it was just plain text.
I've never worked with this sort of web page generation and hoping someone might be able to help me figure this out so I can troubleshoot this. Changing the way this works (at the time) is not an option so I'm trying to correct it so that IE is happy too.
Thanks
This specific code sequence works in all browsers I've tried it in (Chrome, IE, Firefox):
var elem = document.createElement("input");
elem.type = "text";
elem.id = "test";
document.body.appendChild(elem);
elem.value = "This is some text";
If your exact code is deviating from this, then you should examine the differences or post your exact sequence of code that demonstrates the problem in IE so we have a better idea how to debug or advise.
You can see a working demo of this in any browser you want to try it in here: http://jsfiddle.net/jfriend00/z2FpP/
Things to watch out for in your code:
Is any code setting .innerHTML of a parent which could be wiping out or resetting the child elements.
Is any code setting .innerHTML of the input field itself. This should not be done. Code should use .value to set the text of the input field.
Are there any code errors when the code runs in IE? Check the error console or debug console (hit F12 in IE to get to the debugger where you can see the error console).
Are there any other attributes being set in the input field that might make it read-only instead of editable?

Javascript: Un-able to create new hidden input element

I was following the code found in here to create a secure login page. The trouble is, it can't create the hidden input element.
function formhash(form, password) {
// Create a new element input, this will be out hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden"
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
I have read through saying that it only works for IE and not for gecko. Is this true or I just missing something?
Update:
The formhash function works when I place the javascript into the login page. When it is move to an external file, the problem starts again.
#asprin Noted. The reason I place php is because the code was based on php implementation
#Henrik Will do that. Thanks
#RenePot Yup, it was called on the process_login.php page
#MarkGarcia Thanks for the suggestion. Notice it say's that the function wasn't declare
#WernerVesterås Not sure but I think after.
#Quentin Thanks for the suggestion. Will do that :D
Likely, form is simply not set to what you think it is, a jsfiddle.net would probably help us and you debug. I set a working version up at http://jsfiddle.net/JPTyj/ Comment out hidden to actually see it work. Note that you will not the the hidden input field in "view source" in the browser as it is dynamically added to the dom! Use firebug or the chrome dev tools to see it.
Also, most likely you will want to use a library to make it easier for you to develop platform independent code instead of writing bare javascript.
In IE8 (at least), you need to set the type attribute before appending it using setAttribute():
var p = document.createElement("input");
p.setAttribute("type", "hidden");
form.appendChild(p);
http://jsfiddle.net/BePGD/ Tested in IE7, IE8, Chrome.

Problem with jQuery - error when trying to find 2 tags

I have the following DOM structure:
/*:DOC += <div id='testDiv' class='testDivClass'><div id='innerTestDiv'></div></div><span id='testSpan' class='testSpanClass'><span id='innerTestSpan'></span></span>
Now I tried to run jQuery select against them as follow. The first one returned alright, but the second one failed:
// works
var result = $('#testDiv')[0];
alert(result.id);
// failed: id is null or not an object
var result2 = $('#testSpan')[0];
alert(result2.id);
I tried selecting id instead of class and got the same results.
My question is: how can I get the second select to work? Is there some sort of invisible iterator/pointer in jQuery which I need to reset to the beginning of the DOM before the second select?
Thanks.
EDIT: Ok this is the official "does not work" version. testDiv matched, but testSpan did not, hence I got an error saying id is null or not an object error in the second alert.
UPDATE: I did a test by swapping testDiv and testSpan in the html. Now BOTH select failed.
UPDATE2: I have changed the html back to what it used to look like. I'm using JsTestDriver to write up the test, but it is actually not calling anything at the moment. The actual html looks messier than this (more nested tags). I'm trying to get this simplified version to work first. It appears that jQuery was able to get into the first select, whether it'll be span or div, but couldnt get out of it to do the second select. I've replaced jQuery.js and jsTestDriver.jar to no avail.
Thanks.
The .className selector matches by class, not ID.
Therefore, $(span.testSpan) won't match any elements.
You need to change it to $('span.testSpanClass') ot $(span#testSpan') (using the #id selector, which matches ID).
For more information, read the documentation.
I don't know why, but for me your code worked well.
I added $(document).ready(function() { before that code, and when I opened the test page, the alert box showed up perfectly, both of them! I don't know when do you want this alert box showed, but if it is when visitor open the page, just add that code. Otherwise, add
function objectid() {
var result = $('#testDiv')[0];
alert(result.id);
var result2 = $('#testSpan')[0];
alert(result2.id);
}
That code worked well for me, too.
PS: Sorry if you don't understand my bad english.
More than likely, there is something else wrong with the HTML you're actually using. Since you're posting only a tiny bit of the html, we can't actually test your problem. Post the entire page, or at least the smallest piece of it that actually has the problem when you run your test.
I tested the jQuery code you reported on JS Bin, and the code worked fine. As the code is very basic, I don't think the problem is caused by the version of jQuery used.
What I ended up doing is wrapping the entire html with a div or span tag. I found that jQuery could not get out of a div/span tag once it gets into one (in my above example), so I just make it to go into a div/span tag once.
Not sure whether this is a patch or ugly fix, but it solved my problem for now.
Thanks for all the help!
Use "#" to select by id, use "." to select by class...

Categories

Resources