Is this.form.sel2 similar to document.getElementById('sel2')?
My select tag is as follows:
<select size=5 id="sub_player_ids" name="sub[player_ids][]">
And when I am putting the name of the tag, i.e, sub[player_ids][] in my javascript code, am getting a syntax error.
I am trying to find a workaround so that instead of using the name of the element, i want to use the id.
However using document.getElementById('sub_player_ids') is not working.
Thanks for any suggestion provided.
Please see my javascript code below:
<input type="button" value="-->"
onclick="moveOptions(this.form.sel1, this.form.sel2);" /><br />
<input type="button" value="<--"
onclick="moveOptions(this.form.sel2, this.form.sel1);" />
The id of your element is sub_player_ids, not sel2. So document.getElementById("sub_player_ids") would work.
You may also find that this.form["sub[player_ids][]"] would work. Using the quoted form lets you use things that you can't use in the literal form.
Something to beware of is that IE7 and earlier have a broken version of getElementById that will find things that use the given string as a name, rather than as an id, even if something later on the page actually uses it as an id. (Yes, really; more here.) Some libraries will work around that for you (jQuery does, for instance). And actually, speaking of libraries, a good library really can help work around all sorts of browser inconsistencies and provide a lot of handy utility functionality, letting you concentrate on your actual business problems. You might consider looking at jQuery, Prototype, YUI, Closure, or any of several others.
You can use bracket notation instead:
this.form['sub[player_ids][]']
...or getElementById(), with the right ID:
document.getElementById('sub_player_ids')
Use document.getElementById('sub_player_ids') to get that element.
You have the wrong id
document.getElementById('sub_player_ids')
verify that your options contains id, it would only be containing name with sel2
Related
I've got a hidden value in my jsp:
<html:hidden property="user.strRegistered" value="user.strRegistered"/>
How can I access it in my js file? I have:
var regChk = $('[name="user.strRegistered"]');
alert(regChk);
but that doesn't work. I've also tried these two:
var regChk = $('user.strRegistered');
alert($('#user.strRegistered').val());
but they both come up as undefined.
The value in the html is correct though, and when I look, it shows:
<input type="hidden" name="user.strRegistered" value="yes">
Complementing developerwjk response as I can't comment.
When you use:
$('user.strRegistered');
You are trying to find a type of element "user" with the css class strRegistered.
If you use:
$('#user.strRegistered');
You are trying to find an element with id "user" and the css class strRegistered. The dot (.) on a jQuery selector means you want an element with a certain class.
If you want to use dot (.) on a jQuery selector, remember to escape it with two backslashes. So for that to work you would use:
$('#user\\.strRegistered');
Only old non-standard versions of IE (i.e. IE 6) let you access an html tag by name attribute with document.getElementById (which is used behind the scenes by JQuery's $()). In fact, I may even be remembering that incorrect, as IE 6 might not even let you do this.
For anything standards compliant, you need an id attribute to use document.getElementById:
<input type="hidden" id="user.strRegistered" name="user.strRegistered" value="yes">
Now the question is how to get your framework's <html:hidden to give this thing an id attribute....You didn't tag the framework you're using, so I can't help you on that.
In my page I want to change the class name of the div whose id is answer1 in div id=question. How can I do that? Thanks.
$('question1 answer1').addClassName('new_name');
<div id="question1">
<div id="answer1" class="old_name">
</div>
</div>
<div id="question2">
<div id="answer2" class="old_name">
</div>
</div>
So, as it has been pointed out, any selector method requires an iterator of some sort, so you can not just apply a method to all objects returned. You will notice in the documentation for Element.select that this is supposed to alleviate having to explicitly convert the object to an array, but I have not had luck with this on jsfiddle. However, I did try the following:
$('answer2').addClassName('new_name');
And it worked just fine. I don't know if the issue is that you are trying to traverse the DOM in your original element object (by using question1 answer1) and this requires the object/array iterator, or if it's just a hiccup elsewhere in the code. But in your specific example, since you know the id of the actual element you want to change the class of, the above code should work fine without specificing the parent element or using an array index of any kind.
I will admit that prototypejs threw me off because they use the same method names for the Element objects as Enumerable objects, so I saw the first instance of select and thought it looked pretty straight forward. Having now seen that almost every class/method requires you to set up a selector and convert it or manually traverse it, I will definitly say that this would be much easier with jquery and that your initial comment that they are almost the same is specifically not true in this scenario. Perhaps protojs offers some features that jquery does not, perhaps your code is tied to protojs (I worked on a project for a year that had to use YUI, which is a much bigger nightmare, trust me), but jquery is set up to play nice with prototypejs, so in cases like these, I'd consider using both. In jquery, the code would have been:
jQuery.noConflict(); // Avoids $ fight between jquery and prototypejs
jQuery( '#question1 #answer1' ).addClass('new_name');
or, to remove the old one first:
jQuery.noConflict(); // Avoids $ fight between jquery and prototypejs
jQuery( '#question1 #answer1' )removeClass('old_name').addClass('new_name');
Also, prototype has a toggleClass method that is probably also unnecessarilly esoteric, but maybe you should read up on: toggleClassName
And I wouldn't be this pissy about wasting my time on this (because I don't like to consider getting stuck learning a new framework a waste of time) except that their documentation, while attractive, has the worst examples I've ever seen. They all assume you have some fundamental idea without ever a friendly real world example or hyperlink to the difference between an instance and a class, and their examples distinguishing the two are identical. I'm definitely going to take some time out later today to find the real best answer to your question, out of spite and pride, if nothing else, but if it really comes down to having to iterator every time, just use vanilla js and use this framework when it's actually useful.
Simply $('answer1') will get you a reference to the div element that you want. The $ function returns an element with the given id string (or null if none was found). Note that you don't use a selector string when using $ - it only operates on ids.
The $$ function takes in a CSS selector string and returns an array of all matching elements, or an empty array if nothing matched. If you wanted or needed to go that route, you could locate the same div like this:
$$('#question1 .answer1')[0]
Once you have your element reference using either of the above methods, you can use addClassName or removeClassName or any other element methods available.
First post on stackoverflow. Hope everything is right!
I'm thinking of attaching an ID value to the HTML element itself via JavaScript, instead of using the HTML id attribute.
For instance, say that JavaScript variable htmlElement is a div. So htmlElement.cssName would tell us its CSS class.
Now, how about doing
htmlElement.idProperty = "someValue"
in JavaScript instead of doing <div id="someValue">? Then I can use the idProperty in say event handlers.
this.idProperty
That simple!
Is there something wrong in doing so?
EDIT: Thanks for yor answers! Very helpful and instructive. I wish I could check green on all of them!
no, you can do it the way you like it, if you are dynamically creating this item you should use this method, if you are doing this inside html I recommend you to just put the name of the id in html too.
However a small note. Use element.id instead of idProperty.
element.id = 'my-id';
You can use the createAttribute method to add an id to the element like this:
id = document.createAttribute('id');
id.value = "someValue";
htmlElement.setAttributeNode(id);
What you're doing there is adding a runtime property (in your case, called idProperty) to an HTMLElement object instance. You can get away with doing that in your JavaScript code (the Prototype library does it all the time). Makes me uncomfortable, but it does work on all major browsers.
If you want to be able to specify these in HTML markup as well, though, I'd use attributes instead. You can create attributes with any names you want, although to be careful I'd use names like data-xyz (e.g., use a data- prefix) as that's the HTML5 standard way of using your own attributes. Then you use getAttribute to get the value and setAttribute to set/update the value.
Im working on a form and getting null or not an object errors in ie.
<form action="#" method="post" name="adv_search">
<input class="inputbox" type="text" name="keyword1" value="none" id="keyword1"/>
</form>
<script>
document.adv_search.keyword1.focus();
document.adv_search.keyword1.select();
</script>
//whereas if I use
<script>
var key1 = document.getElementById('keyword1');
key1.focus();
key1.select();
</script>
//everything is fine
i would like to understand why.
i would like it to work without having the id tag for the input field
thanks in advance
shouldnt the document.formname.fieldname.focus();
and document.formname.fieldname.select();
work?
Your particular example works for me, but if I add another field with the same name:
<input type="text" name="keyword1" />
<input type="text" name="keyword1" />
Then document.adv_search.keyword1.focus() will fail with the error you specify.
The reason is that:
document.adv_search.keyword1
is a shortcut for this syntax (which goes back to DOM Level 0 and the Netscape 2 days!):
document.forms.adv_search.elements.keyword1
(Incidentally, it is better to use this full syntax, instead of relying on the behaviour of the ‘document’ and ‘form’ objects being indexed on names: if a new method is added to HTMLDocument or HTMLFormElement, that might clash with the control name you are using. This is less of an issue when you use the document.forms or form.elements collections. Also, IE mistakenly dumps all names and ids into ‘document’, so if you've got an element with id="adv_search" in addition to the form with that as a name, document.adv_search will return the wrong one.)
Anyway, the DOM Level 0 scripting methods behave slightly curiously when you access an element by name like this. If there is a single matching element, you'll get that one as a standalone object. If, on the other hand, there are more than one, you'll get a list of objects. You can't call focus() or select() on an array-like list, which is why the error appears; you'd have to do something like keyword1[0].focus() when the list was returned.
So you have to decide whether you're going to be using old-school DOM Level 0 methods to access your form controls — in which case you're going to have to cope with sniffing for single-or-multiple-controls — or move to the ID-based methods introduced by ‘DOM Level 1’:
document.getElementById('keyword1').focus();
The ID-based methods are generally a bit more typing (in the script and to add ‘id’s to all elements you wish to access this way, if they don't already have them), but they are simple and unambiguous. (Also you can then drop the name on the <form> itself.)
The ID approach really is best but if you want to go by name, use getElementsByName.
In this case, it might look like this:
<script>
// retrieves array of objects with the name 'keyword1'
// and takes the first one
var key1 = document.getElementsByName('keyword1')[0];
key1.focus();
key1.select();
</script>
I've found that given a form in a HTML page like this:
<form name="form">
<input type="image" name="foo"
src="somewhere.gif" alt="image" value="blah"/>
<input type="text" name="bar" value="blah"/>
</form>
When accessing the elements via the DOM in Javascript, there is no element for the image input! It is just omitted. So, document.forms[0].elements.length is 1, and document.forms[0].element[0].type is "text".
This seems to be the case in Firefox, and IE. I can't find this fact documented anywhere in my reference books or on the web. All I can find is a throwaway comment here:
https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4
Which suggests it "just is like this". If so, well so be it - but is it really not documented anywhere? Is it a historical mistake, or is there a reason for it?
It looks like that's the behavior of the elements property in all browsers.
However, you should still be able to access it through the DOM in JavaScript using the childNodes property.
For your example:
document.forms[0].childNodes.length; // equals 5 (2 inputs and 3 text nodes).
document.forms[0].childNodes[1]; // This is your input with type='image'
Interesting... the DOM 1 spec defines .elements as:
elements
Returns a collection of all control elements in the form.
The HTML 4 spec part 17.2.1 doesn't list "image" types, so I guess that's the answer.
Indeed, I see a comment: "The DOM is supposed to work that way, that's how it works in Mozilla, NS4x, and IE. We can't change that even if we wanted to, lots of sites would break." so I would lean toward an historical error. Image element is already in HTML 2 DTD...
Perhaps that's for that and possible other culprits that authors discourage using Dom hierarchy like that in favor of getElement[s]ByXxx functions (or XPath!).
Been bitten by it myself. It's stated in the MSDN DHTML docs.