I wanted to pick one for consistency ( though i don't think it matters ) and went with id....via document.getElementById().
no longer use
name attributes for js access
form array access
There are multiple posts on this...but just to make life easy and not think about it any more..I'm using ids only.
Are there any issues with this choice?
I don't care so much about N5 and N6 and W3 specs.
Here are some similar posts:
Best Practice: Access form elements by HTML id or name attribute?
In case of usage of id for each form input when you have multiple forms with multiple inputs on one page you'll should care about uniqueness of identifiers for each input.
So the identifiers could became long like "my-form-user-name" and "my-other-special-form-user-name", etc.
So I would suggest to give an id to form element, retrieve the form by id and then refer to its elements by name. It's easier to create unique and readable identifiers for a few forms than for 50 fields of 5 forms with 10 fields in each.
And probably the code will be more readable.
<h4>Article form</h4>
<form id="article-form" method="post">
<label>Title:</label>
<input name="title" type="text" />
<label>Text:</label>
<textarea name="text"></textarea>
<input type="submit" name="submit" value="Comment" />
</form>
<hr />
<h4>Support form</h4>
<form id="support-form" method="post">
<label>Title:</label>
<input name="title" type="text" />
<label>Text:</label>
<textarea name="text"></textarea>
<input type="submit" name="submit" value="Submit issue" />
</form>
<script type="text/javascript">
var article = document.getElementById('article-form'),
ticket = document.getElementById('support-form');
article['title'].value = 'My Article';
article['text'].value = 'The text of my article...';
ticket['title'].value = 'I found bug at your site';
ticket['text'].value = 'Bug description...';
</script>
Fiddle
But if you're using labels like in my example and want to use attribute for in them to bind them to inputs, then you'll need have identifiers for that inputs anyway.
ID is suppose to be used for unique id's of every element on the page. so it's invalid to have more then once in the same document.
BUT... the NAME attribute can be repeated legally within the html standard. When name is used on a form input item, the values that the cgi recieves is based on name=value pairs. ID doesn't have an inherent name to it.
In all honesty.. I think your mixing apples and oranges here, as the two have very different purposes.
Related
I am reworking on a code of an old developer and I'm trying to do a form for reservation.
I've looked across the whole code the only thing called reservation is the name and the id of the form.
Form who's is in style : display:none ...
So two question in one : First of all what the heck is supposed to do
document.reservation.submit(); Is it suppose to get the form by his name ?
Shouldn't it be something like document.getElementById('reservation').submit() instead ?
And my second question is : How the form can be sent if all the value are set to display:none I tough it couldn't work and if you want to hide them you shall use hidden property...
I need a bit of help on this guys pls :)
Form for beter comprehension :
<form name='reservation' action='http://xxxx/reservationFormAction.to' method="POST" id="reservation">
<input type="hidden" id="productLive" name="product" value="{$product.info.code}"/>
<input type="hidden" name="complementaryParameters" value=""/>
<input type="text" name="depCityCode" id="depCityCode" style="display:none" />
<input type="text" name="dateDep" id="dateDep" style="display:none" />
<input type="text" name="nightDuration" id="nightDuration" style="display:none" />
<input type="text" name="dayDuration" id="dayDuration" style="display:none" />
<input type="text" name="provider" value="{$product.tourOperator.code}" style="display:none" />
<input type="text" id="toProduct" name="toCode" value="{$product.info.toProductCode}" style="display:none" />
<input type="text" name="catalogCode" value="{$product.info.code}" style="display:none" />
{if $ecall}
<input type="text" name="reservationProfileChannelCode" value="ECALL" style="display:none" />
{else}
<input type="text" name="reservationProfileChannelCode" value="ADV" style="display:none" />
{/if}
<input type="text" name="nbAdults" id="nbAdults" style="display:none" />
<input type="text" name="nbChildren" id="nbChildren" style="display:none" />
<input type="text" name="nbBabies" id="nbBabies" style="display:none" />
<input type="text" name="productUrl" id="productUrl" style="display:none" value="http://www.xxxx.com/{$product.slug}_{$product.info.code}.html" />
<input type="text" name="homeUrl" id="homeUrl" style="display:none" value="http://www.xxxx.com" />
<span id="ageChild" style="display:none"></span>
<div class="update-search clearfix">
document.reservation gets the HTMLFormElement for the form with the name reservation. Then calling submit submits the form (without triggering the submit event).
So why not document.getElementById? That would also work, but document.reservation works because the document object gets various properties created on it automagically, including properties referring to forms by their name. This is covered in ยง3.1.3 of the HTML5 spec *(you have to scroll down a fair bit):
The Document interface supports named properties. The supported property names at any moment consist of the values of the name content attributes of all the applet, exposed embed, form, iframe, img, and exposed object elements in the Document that have non-empty name content attributes, and the values of the id content attributes of all the applet and exposed object elements in the Document that have non-empty id content attributes, and the values of the id content attributes of all the img elements in the Document that have both non-empty name content attributes and non-empty id content attributes.
The value of those properties is the element the name or id came from.
The window object also gets properties for every element with an id, as described here:
The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:
the browsing context name of any child browsing context of the active document whose name is not the empty string,
the value of the name content attribute for all a, applet, area, embed, form, frameset, img, and object elements in the active document that have a non-empty name content attribute, and
the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.
Where again the value of those properties is the element the name or id came from.
In both cases, this is the HTML5 specification standardizing the previously-widespread-but-nonstandard practice most browsers had, which is widely used on pages in the wild.
How the form can be sent if all the value are set to display:none I tough it couldn't work and if you want to hide them you shall use hidden property...
It's best to ask one question per question.
The CSS display property has no effect at all on whether form fields are submitted; you're probably thinking of the field's disabled state: Disabled form fields are indeed left out of the form on submission.
the display none or hidden info will always be sent even that you can't see.... Usually we pass some info that the user doesn't need to know, like USER_ID=20 .....---- and the
document.reservation.submit
------- it submits the form with name="reservation"
I have a dynamic web page where the content may contain between 1 and 10 links, provided in text boxes, similar to the following:
<input size="50" id="link" value="http://Something.Something" type="text">
<input size="50" id="link" value="http://SomethingElse.Something" type="text">
I need javascript to be able to read all of the links, and be able to manipulate the data (store in array, output to screen, etc)
I know that I can read a single id using the following
var link = document.getElementById('link');
Which will return the first match - but, how can I do a loop or obtain all the values for all the links, bearing in mind that the number of links cannot be determined beforehand?
P.S. I have tried using getElementsByTagName('input') but there are more inputs on the page, which means it's getting more results than I'd like it to get.
You can make them all have names and search by name.
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
<input name="vrow" value="0" type="text"/>
Then you can get it with:
var vrows = document.getElementsByName("vrow");
alert(vrows.length);
Give them all a common class and access using document.getElementsByClassName('class').
IDs should be unique for each element. You could use document.getElementsByClassName or document.querySelectorAll(".class"); and then use the class name (assuming relatively modern browser). Or use document.getElementsByTagName() and then iterate through the elements comparing with the class.
Attach a jQuery lib and you will be able to do something like:
$('input[type=text]').each(function(i, val){
alert($(this).val());
});
I've got an assignment to pass data between 2 .htm pages, in a manner which the source gets copied to the destination.
sourcePage.htm contains a form. (it contains more controls this is just a sample)
<form id="myform" action="destPage.htm" method="get" >
<input type="text" name="user" />
<input type="submit" name="submit" value="Submit" />
</form>
and destPage.htm is blank.
Using JavaScript I am required to parse the data from the url, that part isn't the problem
, the problem is that I am also required that destPage would be an exact duplicate of sourcePage.
My question is, if there's a way to pass the form as an object or some way to pass the control types and their properties along side the data.
You specified in the answer of ek_ny, that you want to dynamically build the form, based on it's input.
You can do this, in fact, with the JavaScript DOM:
var i = document.createElement('input');
i.setAttribute('type', "text");
i.setAttribute('name', "user");
var f = document.createElement('form');
f.setAttribute('action', "destpage.html");
// etc.
f.appendChild(i);
document.getElementById('container').appendChild(f);
The form will be added as a child in the <div id="container"> container.
Now you can use hidden input elements, which give, for instance, the specifics of the form:
<form>
<input type="hidden" name="x_type" value="input-text" />
<input name="x" type="text" />
<input type="hidden" name="y_type" value="select:[...]" />
<select name="y">
...
</select>
</form>
As far as I know, you won't be able to do a post between two pages. At least when I've attempted that you get an error-- it really doesn't make sense to have a post from one static page to the other (right?). What you can do is serialize the data you want to pass, put it on the url string to the next page and then deserialize that data and populate the controls on the destination page. If the html between the two pages is identical, then it should be pretty straightforward, if not it will be a little tricker. If you used jQuery it would be pretty easy, because you could serialize an entire form. If you need to come up with a generic solution (and you should, because it will help you learn) that's one thing, if you need to just get it working for this assignment and there are only a couple of form fields, you'll just need to encode the values you want to pass and pass them on a URL string with a get request.
Short Question:
How do you link a label element to an input element without using the input element's id using jQuery and javascript?
Long Question:
I am using jQuery to clone a form with possibly more than one instance of the form being available for the user to fill in.
A label's 'for' attribute is supposed to be set to the 'id' attribute of the input element that it is for. This works when the input element has a unique id.
Because I am cloning the same input element there will be multiple input elements with the same id in the document. Therefore I'm avoiding having id attributes for input elements but I'd still like to focus on the input element when the label is clicked. I also want to avoid generating random ids for fields or setting onclick events on labels.
Edit #1
Example mark up (note no ids)
<form>
<label>First Name:</label><input type='text' name='FirstName' /><br/>
<label>Last Name:</label><input type='text' name='LastName' /><br/>
</form>
Example cloning code:
var newForm = $('form').clone();
$(newForm).find('label').each(function(){
var inputElement = $(this).next('input');
// I'd love to set the label's for attribute to an element
$(this).attr('for', inputElement);
});
$(document).append(newForm);
Edit #2
There currently are three options:
Set onclick events for labels to focus on the input field they're for. Criteria for deciding which labels are for which inputs can be the next input element or something else
Embed the input fields in the label fields (might not be possible due to designer's choices)
Generate random ids while cloning each form
Well it would be nice to see the markup, but if i can assume that the markup will look somewhat like this
<form name="f1">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
<form name="f2">
<label>this is my label</label>
<input />
<label>this is my other label</label>
<input />
</form>
then you could do something like this
$('form label').live('click',function(){
$(this).next('input').focus();
});
you will need to use live or delegate since you're cloning the forms on the fly i'm assuming.
The simplest solution is to move the <input> tags inside the <label> tags and forgo the for attribute altogether. Per the HTML spec, <input> tags without for attributes are implicitly associated with their contents.
Try this:
<form>
<label>First Name: <input type='text' name='FirstName' /></label><br/>
<label>Last Name: <input type='text' name='LastName' /></label><br/>
</form>
(See: http://www.w3.org/TR/html401/interact/forms.html#h-17.9.1)
You shouldn't have multiple identical ids in the page. It defeats the purpose of the id attribute and is against the W3C spec.
Regardless, jQuery's $(this) could help you in this situation. Say you gave all your the "focusable" class. Then you could do:
$('.focusable').focus( function(){
$(this).doSomething();
});
This is really an HTML question. A label can be associated wtih a form control either by its for attribute having the same value as the associated control's id attribute, or by having the control as a child of the label, e.g.
<form ...>
<label for="nameField">Name:<input id="nameField" name="nameField" ... ></label>
<label>email:<input name="emailField" ... ></label>
</form>
I suppose in jQuery you need something like:
var labelAndInput = $('<label>text<input ... ></label>');
or whatever. Note that older versions of IE (and maybe more recent ones too) the label will not be associated with the control without the for attribute (or htmlFor property), there is no other way.
What is a common way to pass data for formula fields, to specify a quantifier. I would currently do as follows:
<input type="text" name="myfield" class="inputfieldstyle quantified" id="q_12" value="foo" />
where q_12 is generic.
But there some inherent problems with the approach:
What if i want to give it an id for some js/css reason?
q_12 is not easy to read with js:
var quant =
parseInt(element.id.split('_').pop())
id is not made for passing values
How should I handle this? Is there a common way? Is there a way suggested by w3c?
A good and simple way is to use hidden fields :
<input type="hidden" name="myname" value="my_value" id="my_id">
You could extend the hidden fields idea of Guillaume Lebourgeois. If you're worried about having two inputs for each, you could always adopt the "data-" attribute approach as detailed in the following link: http://ejohn.org/blog/html-5-data-attributes/
<input type="hidden" name="myname" id="my_id"
data-myData1="somedata" data-myData2="somemoredata" value="" >
and then use getAttribute to return the value (http://www.devguru.com/technologies/javascript/17457.asp):
document.getElementbyId("my_id").getAttribute("data-myData1")
document.getElementbyId("my_id").getAttribute("data-myData2")
Or if you are using jQuery:
$("#my_id").attr("data-myData1")
Of course, you would have to roll this up into the value before passing across pages, but its still a possiblity.