Geting a value from select box using jQuery - javascript

I've got a simple select input and I'm using jQuery's .val() to get the selection from it.
For some reason, it is throwing a "Object doesn't support this property or method" error in Internet Explorer 8, the first error I've ever seen jQuery actaully throw.
I've replicated this error at http://jsfiddle.net/gWvwS
What am I doing wrong? Seems pretty straight forward to me...

Try:
var isplay_entry_form = $('#display_entry_form').val();
alert(isplay_entry_form);
display_entry_form on the global window is actually the element. It's much less known, because it's really bad and shouldn't be used. So you are overwriting it in IE.
Fixed Example for IE8: http://jsfiddle.net/gWvwS/7/

Javascript variables with the same name as DOM elements are not supported by IE. It appears that IE uses a common mechanism for addressing DOM elements by id and addressing javascript variables. Which means that whichever object (DOM element or javascript var) is declared later in the source is the one that gets used. This will likely cause an "object does not support this property or method" error when you try to access your javascript variable. (source)
This should work:
display_entry_form_value = $('#display_entry_form > option:selected').val();
alert(display_entry_form_value);

Your document contains an element with name display_entry_form. In IE, named elements are globally accessible through their name. So, you have to either use var (to declare a new, local variable[Need verification]), or choose another name.
var other_name = $('#display_entry_form').val();
alert(other_name);
Fiddle http://jsfiddle.net/gWvwS/5/

I suppose it has to do with, that value belongs to option, not to select.
Try
$('select#display_entry_form option:selected').val();

I updated jsfiddle to correct code:
http://jsfiddle.net/gWvwS/6/

The <select> tag doesn't have a value attribute, but rather a selectedIndex attribute.

Related

JavaScript document.getElementById(“id”) and element id attribute

I have:
<div id="myDiv1"></div>
<div id="myDiv2"></div>
In JavaScript, I can set div innerHTML by writing:
myDiv1.innerHTML = "myDiv1, Hi!"
or
document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!"
Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?
thanks,
Mike
Why should I use document.getElementById when I can simply use element Id ?
To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id (so-called "automatic globals").
In contrast, getElementById only does what it says, finds an element by its id; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name attributes.)
when you write
myDiv1.innerHTML = "myDiv1, Hi!"
you are calling window object, so actual call is like this
window.myDiv1.innerHTML = "myDiv1, Hi!"
This behavior is deprecated now and to be avoided. Instead we should use
document.getElementById`

What is the difference between getElementById and simply using an element's ID as a variable?

Can someone tell me the difference between calling an HTML elment with id="myDomObect"?:
var myObj = document.getElementById('myDomObect');
&
var myObj = myDomObect;
Use the first form or a wrapper such as jQuery. The second form,
var myObj = myDomObect;
Translates to
var myObj = window["myDomObect"];
This "works" because of an old, old hack in which ID's were exposed as global window properties (IIRC this was a misfeature from the start) and thus we are still blessed with the behavior 20 years later.. and yes, it will work in the very latest Chrome.
However, such a shorthand should not be used for multiple reasons:
It will not work as originally written in "strict mode" (but it will work with the second form)
It does not convey the operation - namely that a DOM element is requested/fetched (by ID).
It does not work for IDs that collide with window properties; eg. <div id=history></div> would result in "unexpected behavior" if accessed this way. (This doesn't affect getElementById code that correctly uses local var variables in a function.)
Behavior is not defined when duplicate IDs exist in the document (which is allowed); the behavior for getElementById has been codified in by DOM 4: "getElementById(elementId) method must return the first element [with the ID], in tree order.."
See also:
Do DOM tree elements with ids become global variables?
The first is how the "real" DOM API works (another option is document.querySelector("#myDomObject")). The second is how browsers have started implementing automatic hoisting of id'd elements, since ids are supposed to be unique. In a twist of "what were you thinking", this can lead to hilarious conflicts where variables that have the same name as HTML elements with an id don't take precedence and the variable you though you were using is suddenly an HTML element.

Does jQuery create a globally scoped object for each element with an id?

I've noticed that, in Firefox at least, jQuery seems to create a global variable for each element on the page that has an id, and calls that variable whatever the id is. In this image from Firebug, see how I've got an element called querystring, but I also seem to have a global variable also called querystring:
The type of this variable HtmlInputElement, because the element is defined as:
<input id="querystring" ...>
Is this a global shortcut in jQuery, such that varname is the same as $('#varname'), or am I not understanding what I'm seeing here?
This is actually an HTML5 thing, not just jQuery.
This code shows a nice example of it:
<a id="yestheyreglobals">Are IDs globals?</a>
<script>
if ( yestheyreglobals ) {
document.write('Yes they\'re globals')
}
</script>
Paste it in an empty .html file and watch the magic. No jQuery required.
source: http://codepen.io/anon/pen/Arasd
Even though this works, it isn't supported in all browsers, so one should still rely on document.getElementById.
Also a link to the WHATWG standard in case anyone is curious: http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object

document is an alias name?

Is document an alias of Sys.UI.DomElement in JavaScript?
I have come across this example in msdn.
$addHandler(Sys.UI.DomElement.getElementById("Button1"), "click", toggleCssClassMethod);
I used to see only document.getElementById(id). So raised this question.Itmight be sound bad. But I am just kid in JS world.
No, the two are not the same. I think your confusion is probably coming from the common misconception that getElementById is a function only belonging to document. In fact, you can use getElementById on other DOM elements. Something like this works just fine:
document.getElementById("test").getElementById("test2")
http://jsfiddle.net/CNc2s/
Notice that the 2nd call of getElementById is being called on the DOM element returned by the first call. This will find an element with an id of test2 within an element with and id of test.
The reason you don't often see things like this is that ids must be unique within a document. So calling it on the document will get the same element as calling it on a containing element.
No, document is not an alias for Sys.UI.DomElement. This can be demonstrated with a quick experiment in the IE javascript console.
document.name = "hello";
console.log(Sys.UI.DomElement.name); // Prints undefined

`clone()` not working in Internet Explorer 6

I was trying to clone an element and append it to another child with following statement of jQuery:
$(userListJId).clone().appendTo(tempOwnJString);
Where userListJId and tempOwnJString are the id's of elements.
The above line of code works fine in Internet Explorer 7 and higher versions of it but does not seem to be working in Internet Explorer 6.
What could be the possible reason?
I used clone() on IE6 and so that should not be the problem.
Maybe you are creatong invalid HTML and IE6 which is less permissive than IE7 complains about this.
Can you show us your code and also the version of jQuery?
It's funny you should ask this because I had a quite similar problem (though it affected IE7 and probably IE6).
Also, not sure if you have done something special (i.e. defining variables) but perhaps you should refer to the objects as $('#userListJId') instead of just the element name. Again, I can't see the rest of the code, so you may have already defined those variables outside the document.* scope.
Basically, in IE, certain attributes cannot be modified after the object is created, an example being the ID attribute.
The work around is to not clone the object, at least through .clone(), but to take the outer HTML of the object you wish to clone as a string and do a regex .replace() on the id attribute, and then append the modified HTML into tempOwnJString.
Another gotchya in IE, is that sometimes (usually?) when it parses the HTML, it doesn't wrap quotes around attribute values if they contain only alphanumeric characters, so be mindful of this in your regex pattern.
Here is an example of some code I used.
if ($.browser.msie === true)
{
//unfortunately jQuery doesn't have an outerHTML function, so this is a hacky work around
templateHTML = $("#activityTemplate").clone().wrap('<div>').parent().html();
newHTML = templateHTML.replace(/id\=\w+/ig, 'id='+jsonObj.ContactLogID);
$(newHTML).prependTo($("#activityContainer"));
// in case i need to refer to newly created object
clone = $("#"+jsonObj.ContactLogID);
}
Again I can't say for certain if this is the issue you're having but with the information you gave and without any debug info (which IE6 doesn't really provide anyway) this is the best guess.
Echoing what #Foxtrot said, you need to ensure you set the id on the cloned element or you'll freak IE6 out. Afterall, all browsers follow the standard that ids must be unique. Their behavior when you violate this varies. You are experiencing variation.
As a trivial example:
var clone = $(userListIJD).clone();
clone[0].id = 'somethingElse'; // use a formula here, as presumably this is run over and over
// proceed with appending the clone

Categories