javascript name vs ID - javascript

As far as I know there are two ways to get the value from a textbox either
document.formName.textboxName.value;
or
document.getElementbyId('textboxId').value;
As I understand using form name would mean I have less code to write, as name can be used for posting data and getting the value (apart from using ajax). As where if I was just posting using a standard form I would use name to post but I cannot use id ?
e.g. in php I would use
$_POST['texboxName'];
If I where to have and ID on the textbox I cannot get the value using php ?
Which is the standard recommened way of doing this, and is using name browser friendly? Links if possible please, thanks.

The ultimate guide in this is the HTML specification.
Things that stand out there:
id is valid for any HTML element, while name only applies to a select few (a, input, textarea and maybe a few others).
An input (and textarea) element requires the name to be set if you want it to be submitted.

The name attribute is used during submitting the form, i.e. to create a name-value pair that will be processed to the server. The id attribute is used to locate and element in the DOM. Usually the name is used only on the form elements
References:
http://www.w3.org/TR/html401/interact/forms.html
http://www.w3schools.com/html/html_forms.asp

I typically use both. As you mentioned, name is useful for using the data via JavaScript and also once it has been submitted. Feel free to use additional characters in the name as needed: I tend to use []s in my names when the input will be used in an array server-side.
The id attribute can be used for accessing the element via JS/the DOM. It is also used by <label>'s for attribute. If you do this with checkboxes, for example, clicking on the label will cause the box to become checked. That's a big plus for usability.

I consider it good practice to have a name and id for each form element. The reason being that if you want to add labels, or styling via sytlesheets (which you should be doing), then it makes sense to have both.
As for accessing it with javascript: the better way would be to go with the element's id, becuase if you change the name of the form everything breaks. This does not happen when you use the id.

I prefer using IDs, as the "function" (i.e.: what you're trying to achieve) of your code isn't tied up with in the semantics. For me, .GetElementById('myid') stands out more, and is more readable that just having "myid" scattered among the code. Plus you can more easily rename elements. That's my 2p worth!

Related

Is "data-bind" a strictly knockout-only attribute?

I know that one can always define own custom attributes for an HTML tag.
I also know that data-bind is the keyword knockout.js chose as the HTML attribute that links the data to the UI.
So far so good.
What I am curious to know is whether when I come across HTML on some website and I see that it uses the attribute data-bind, does it always imply it uses knockout.js?
<span class="chk" data-bind="visible: selectedAnswers().length > 0" />
In other words, what is the likelihood that a website using the data-bind attribute is not using knockout.js?
No it's not... I've used data-bind in projects not involving knockout. As long as it makes sense as to what the data is going to be used for then you can use whatever string you want (within reason, see below)...
data-bind=""
data-binder=""
data-im-a-data-attribute=""
The data-* attributes consist of two parts:
1) The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
2)The attribute value can be any string
Info obtained from here
Knockout uses the data-bind attribute, but it's just a subset of the HTML5 data-* attributes. They allow for extra data to be stored in an element that don't follow standard HTML attributes.
From https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes :
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as classList, non-standard attributes, extra properties on DOM, or setUserData.
So anyone can use an attribute named data-bind, Knockout chose to use that because it made sense for them.

javascript - How to get "writable" HTML components?

My problem is that I want to create a Firefox AddOn, and I need to extract from the HTML document every "writable" (I mean: input, textarea or other ways to write text) to work with its value.
I know the method document.getElementByTagName(), but the case is that i don't know how many tags to input text exist (or a webpage usually have on it) to refer them this way; or even if this problem can be solved otherwise.
I really appreciate any help or idea to do this efficently, so I can go forward with this project.
You only have 2 possible tags: textarea and input. The problem is that with HTML5 the input tag has several kinds of types which you can insert text but you have also another ones that you can't (like submit or radio):
color
date
datetime
email
month
number
password
search
tel
text
time
url
You can use document.querySelectorAll function to retrieve those elements:
document.querySelectorAll("textarea input[type=text] input[type=email]");
Note that I have only include text and email in the selector but was just a sample mode. You should add all the types you think necessary retrieve.
Here you have all the possible types for input tag and the browser support of those, I recommend check out the documentation to have a better idea of what tags should be relevant for you.

Javascript/HTML: Using id vs. class when naming

I am starting to learn some Javascript using Meteor and am looking at their examples.
One bug that tripped me up for a bit happened when I was adding a text-field for input with a button next to it; users would type in a name they wanted to add to a list and then click the button to actually add it.
My question is: why does it seem to be the case that in the html, the text field has to be named with id="..." while the button has to be named with class="..."?
For additional reference, in my javascript file, I am using textfieldname.value and 'click input.buttonname'. Does the id vs. class requirement stem from how I'm using them?
The "id" attribute is used to supply a globally-unique identifier for an element. The "class" attribute is used to categorize or typify an element according to its meaning, its intended use, its relationship to other elements, or whatever else your application requires.
Usually it's more flexible to use classes to identify things, because more than one element can be given the same class, and an element can have as many classes as are needed. Any single element may only have one "id", and the values must not be re-used in the same document. There are clear use cases for both attributes in which one or the other is obviously more appropriate, and many other cases where it's less clear and for which either could be used.
This isn't really a JavaScript issue so much as a "web application design" issue. How one labels HTML elements is dictated by the nature of the content (HTML), the needs of the presentation (CSS), and the intended behaviors (JavaScript).

Local id-s for HTML elements

I am developing a kind of HTML+JS control which can be embedded into various web pages. I know nothing about those pages (well, I could, but I don't want to). The control consists of one root element (e.g. DIV) which contains a subtree of child elements. In my script, I need to access the child elements. The question is: how can I mark those child elements to distinguish them?
The straightforward solution is using id-s. The problem here is that the id must be unique in the scope of the entire document, and I know nothing about the document my control will be embedded into. So I can't guarantee the uniqueness of my id-s. If the id-s are not unique, it will work (if used with care), but this does not conform with the standard, so I can meet problems with some new versions of the browsers, for example.
Another solution is to use the "name" attribute. It's not required to be unique -- that's good. But again, the standard allows the presence of "name" attribute only for a restricted set of element types. For example, the "name" attribute is invalid for DIV elements.
I could use, for example, the "class" attribute. It seems to be OK with the standards, but it's not OK with the meaning. "class" should be used for other purposes, and this may be confusing.
Can anybody suggest some other options to implement local id-s for HTLM elements?
You could use the HTML5 data-* attributes so you can give them a custom name with the right meaning:
https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes
Do something like:
<div id="element-id" data-local-id="id-value">
...
</div>
and get the value in JavaScript with:
const el = document.getElementById('element-id');
const { localId } = el.dataset;
If you use a prefix to all of your ID's and or classes such as myWidgetName_98345699- the likelihood of collisions is highly improbable.
<div id="myWidgetName_98345699-container" class="myWidgetName_98345699-container">
jQuery does have selectors that will search for part of an ID, so using common names like container would be smart to stay away from as well. Using a longish alphanumeric mix for the specific part of the ID would be smart also
Typically, including hidden information within the web page required creative approaches. For example:
Storing information within HTML element attributes such as id, class, rel, and title, thus overriding the attributes original intent.
Using <span> or <div> blocks that contain the information, while making such blocks invisible to the user through styling (style="display: none;").
Adding JavaScript code to the web page to define data structures that map to HTML ID elements.
Adding your own attributes to existing HTML elements (breaking the HTML standard itself, and relying on the HTML browser to ignore any syntax errors).
The approaches above are not elegant and are not good coding practice, but the good news is that jQuery has a facility that simplifies associating data to DOM elements in a clean, cross-browser manner.
Use the custom data attributes:
Any attribute that starts with "data-" will be treated as a storage area for private data (private in the sense that the end user can't see it - it doesn't affect layout or presentation.
Defining custom data via html:
<div class="bar" id="baz" data-id="foo">
...
</div>
Associating data-id to specific DOM elements (jQuery):
$('#foo').data('id', 'baz');
Retrieving an element with specific data-id:
var $item = $('*[data-id="baz"]');

setting value of name for an image in the DOM

I need to set the value of name for my image tag in the DOM. What is the correct property name? More importatnly how do I navigate the DOM, i.e. finding all the different properties and methods with out having to post each time I need one? I tried this search on Mozilla Developer
If, by "name", you mean the title of the image, then it would be the .title attribute on the image.
You navigate the DOM based on what you're trying to find and what identifiers there are in the DOM. You can find things by ID, by class name, by tag type or even by attribute. Which you would use depends upon how your HTML is strucutred, what you're looking for and what identifying information is in the HTML. If you post your HTML and which objects you're trying to locate, we can explain what your options are.
document.getElementById("xxxx") will find any object in the DOM by id.
document.getElementsByTagName("xxxx") will find a list of objects by tag name.
For more advanced methods of finding things, people generally use a selector library (such as Sizzle or what's in jQuery or YUI) that contains much more advanced logic.

Categories

Resources