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.
Related
How can I get a collection of elements by specifying their id attribute? I want to get the name of all the tags which have the same id in the html.
I want to use ONLY getElementById() to get an array of elements. How can I do this?
I know this is an old question and that an HTML page with multiple identical IDs is invalid. However, I ran into this issues while needing to scrape and reformat someone else's API's HTML documentation that contained duplicate IDs (invalid HTML).
So for anyone else, here is the code I used to work around the issue using querySelectorAll:
var elms = document.querySelectorAll("[id='duplicateID']");
for(var i = 0; i < elms.length; i++)
elms[i].style.display='none'; // <-- whatever you need to do here.
The HTML spec requires the id attribute to be unique in a page:
[T]he id attribute value must be unique amongst all the IDs in the element's tree
If you have several elements with the same ID, your HTML is not valid.
So, document.getElementById should only ever return one element. You can't make it return multiple elements.
There are a couple of related functions that will return a list of elements: getElementsByName or getElementsByClassName that may be more suited to your requirements.
Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:
function whywouldyoudothis() {
var n = document.getElementById("non-unique-id");
var a = [];
var i;
while(n) {
a.push(n);
n.id = "a-different-id";
n = document.getElementById("non-unique-id");
}
for(i = 0;i < a.length; ++i) {
a[i].id = "non-unique-id";
}
return a;
}
However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.
EDIT: Given a valid document, the same effect could be achieved thus:
function getElementsById(id) {
return [document.getElementById(id)];
}
document.querySelectorAll("#yourId"); returns all elements whose id is yourId
It is illegal to have multiple elements with the same id. The id is used as an individual identifier. For groups of elements, use class, and getElementsByClassName instead.
The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.
As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the document object and to window on Internet Explorer. Refer to:
Do DOM tree elements with ids become global variables?
If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.
Class is more than enough for refering anything you want, because it can have a naming with one of more words:
<input class="special use">
<input class="normal use">
<input class="no use">
<input class="special treatment">
<input class="normal treatment">
<input class="no special treatment">
<input class="use treatment">
that's the way you can apply different styles with css (and Bootstrap is the best example of it) and of course you may call
document.getElementsByClassName("special");
document.getElementsByClassName("use");
document.getElementsByClassName("treatment");
document.getElementsByClassName("no");
document.getElementsByClassName("normal");
and so on for any grouping you need.
Now, in the very last case you really want to group elements by id. You may use and refer to elements using a numerically similar, but not equal id:
<input id=1>
<input id="+1">
<input id="-1">
<input id="1 ">
<input id=" 1">
<input id="0x1">
<input id="1.">
<input id="1.0">
<input id="01.0">
<input id="001">
That way you can, knowing the numeric id, access and get an element by just adding extra non-invalidating numeric characters and calling a function to get (by parsing and so on) the original index from its legal string identifying value. It is useful for when you:
Have several rows with similar elements and want to handle its events
coherently. No matter if you delete one or almost all of them.
Since numeric reference is still present, you can then reuse them and
reassign its deleted format.
Run out of class, name and tagname identifiers.
Although you can use spaces and other common signs even when it's a not a requirement strictly validated in browsers, it's not recommended to use them, specially if you are going to send that data in other formats like JSON. You may even handle such things with PHP, but this is a bad practice tending to filthy programming practices.
This is my solution:
<script type="text/javascript">
$(document).ready(function () {
document.getElementsByName("mail")[0].value = "ex_mail1";
document.getElementsByName("mail")[1].value = "ex_mail2";
});
</script>
Or you can use for-loop for that.
You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.
Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.
you can use
document.document.querySelectorAll("#divId")
we can use document.forms[0].Controlid
If you're using d3 for handling multiple objects with the same class / id
You can remove a subset of class elements by using d3.selectAll(".classname");
For example the donut graph here on http://medcorp.co.nz utilizes copies of an arc object with class name "arc" and there's a single line of d3, d3.selectAll(".arc").remove(); to remove all those objects;
using document.getElementById("arc").remove(); only removes a single element and would have to be called multiple times (as is with the suggestions above he creates a loop to remove the objects n times)
This is my code:
var chk="checked";
document.getElementById("chk").chk=true;
where I used variable to set attribute in the second line.
but this is not working with no error.
Please help me to find this.
You might want:
document.getElementById("chk").setAttribute(chk, true);
which will set it as HTML attribute (not the object property - for that you'd use [] brackets). This is what you're probably looking for because you're operating on an HTMLElememnt.
To clarify:
setAttribute - set's an attribute on an HTML element. It will turn this: <div> into that: <div checked="true"> (assuming the element under question is a div)
[] - use for plain JS objects. In that case the name 'property' is rather used, not 'attribute'
Also note that if the element is <input>, both approaches will work. That's because HTMLInputElement contains the 'checked' attribute. See HTMLInputElement MDN page for details.
Use like this.
document.getElementById("chk").setAttribute(chk, true);
Try this:
document.getElementById("chk")[chk] = true;
This one sets the property
or use the .setAttribute property
document.getElementById("chk").setAttribute(chk, true);
This will set the attribute. If you are using it on HTML elements then this one is a better pick for you as this will set the HTML attribute.
Try,
document.getElementById("chk")[chk] = true;
You can add variables to any JavaScript object which is why the code will run without an error, but -- as you've observed -- it won't have any side effects if the property is not a predefined, semantically meaningful one. For that, you should read some documentation for the given element. For the checkbox element, the name of the property you are looking for is checked. (Note that using the dot syntax treats the text to the right as the name of the property, it does not evaluate it, first. For dynamic evaluation of the property name, use the [] syntax for normal objects and setAttribute for HTML attributes).
chk is a javascript variable in your case. When you getElementById, it refers to the HTML document and the tags in it. Example,
<input id=appleId type="radio" name="fruit" value="Apple" />
In JS, you can then say,
document.getElementById("appleId").checked = true;
Refer to How can I check whether a radio button is selected with JavaScript?
I looked at selectors and has attribute seems to be the closes choice however i cant seem to make it work.
what i am trying to do i select an element with certain id that also has a certain rel value..
for example:
<input value="Needthisvalue" rel="15" value=wahtever" id="pickthisID" type="hidden">
to find out that input with that id and that rel. what I've tried so far is :
TabID contain the 15.
$('#pickthisID[rel="'+TabID+'"]').val();
Thanks in advanced.
Firstly, your id's have to be unique, otherwise your HTML is erroneous and will throw loads of JS bugs. As for you problem, simply use
$('#pickthisID[rel='+a+']').val();
jQuery is optimized so that, if you provide an ID selector (e.g. #pickthisID), it will stop looking after its found the first matching element. This is because the id attribute is supposed to be unique per page.
However, this would work:
$('[id="pickthisID"][rel="'+TabID+'"]')
As suggested by OP, there is an error in your HTML.
<input value="Needthisvalue" rel="16" id="pickthisID" type="hidden">
console.log($('input[rel=16]').val());
I think your code should work. But you've some problem with html markup.
You use value attribute twice.
<input value="Needthisvalue" rel="15" value=wahtever" id="pickthisID" type="hidden">
But value should one time:
<input value="Needthisvalue" rel="15" id="pickthisID" type="hidden">
jQuery
var TabID= 15;
alert( $('#pickthisID[rel='+ TabID +']').val() )
DEMO
Note
rel is not valid attribute for input. If possible use data-rel.
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
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>