Action of a HTMLFormElement - javascript

Here is an HTML snippet to reproduce the problem:
<form id=foo action='https://[::1]/'>
<input type=hidden name=action value=xyz>
</form>
<script>
window.alert(document.getElementById('foo').action);
</script>
At first I was using jQuery .prop() so I thought that was the problem but it happens in pure JavaScript as well.
I'm expecting the result to be https://[::1]/ but for some reason it gives me [HTMLInputElement]. According to MDN, the action property of HTMLFormElement should be a DOMString reflecting the HTML action attribute, not an HTMLElement.
This behaviour is present in both Internet Explorer and Chrome so I don't think it's a bug with the browser's implementation. The HTML5 specification states:
The action IDL attribute must reflect the content attribute of the same name, except that on getting, when the content attribute is missing or its value is the empty string, the document's address must be returned instead.
Am I missing something here?

Here's what the specification says:
getter (RadioNodeList or Element) (DOMString name);
This means a form has properties referencing each input element by name: <input name="user"> will automatically define form.user. In your case, <input name="action"> causes form.action to be overridden, referencing that element instead of the form action attribute.
Just retrieve the attribute directly:
form.getAttribute("action");
Or rename your input:
<input name="control-action">

Use getAttribute()
alert(document.getElementById('foo').getAttribute('action'));
http://jsfiddle.net/qbgp7gne/
In your example it happens because you have a child element in your form with the attribute name of 'action'. The JS is returning a HTMLCollection for your form and .action is a child node of that. Forms are special.
Rename it to see your original JS working as expected:
<form id=foo action='https://[::1]/'>
<input type=hidden name=definitelyNOTaction value=xyz>
</form>
http://jsfiddle.net/qbgp7gne/1/

Related

GetElementById in Javascript

I want to getElementById of a certain form but it displays the error
Uncaught TypeError: Object # has no method 'getElementById'
here is my code
varForm = document.forms['newform'].getElementById("yellow");
an ID is unique -
so there is no difference (you get what you want), calling it directly(/correctly):
var Form = document.getElementById("yellow");
As others have pointed out, as far as Id is unique we have getElementById in document:
varForm = document.getElementById("yellow");
But if you still insist on finding a node based on a specific dom node, you can try:
varForm = document.forms['newform'].querySelector("#yellow");
Use following way to get input values from another form e.g.
Forms
<form id="form1">
<input id="txt1" type="text" value="111"/>
</form>
<form id="form2">
<input id="txt1" type="text" value="222"/>
</form>
Js
//get input value from current form i.e. form 1
alert(document.getElementById("txt1").value) //111
//get input value from other form i.e. form2
alert(document.forms["form2"].txt1.value) //222
Unlike some other element-lookup methods such as
Document.querySelector() and Document.querySelectorAll(),
getElementById() is only available as a method of the global document object, and not available as a method on all element objects in the DOM.
Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.
So Keep in Your mind about this method:
it is called on the document object
it returns a single item
var Form = document.getElementById("yellow");
this will get your form.
Consider this form:
<form id="myform"><input id="lala" type="text" value="123"/></form>
There are several ways to get the value of the "lala" input:
console.log(document.getElementById("lala").value)
console.log(document.forms[0].lala.value)
console.log(document.forms["myform"].lala.value)
console.log(document.forms.myform.lala.value)
Here is the Fiddle to play with.

What is document.f.q.focus?

What is document.f.q.focus?
Is this a java script code or not
whether I can use document.f.id.value?
what is the difference between this and document.getElementbyID()
The HTML looks like this:
<form name="f">
<input name="q" />
</form>
In such a case, document.f refers to the form, and .q refers to the input element of that form. .focus() places the focus on that input.
It's worth noting that such code is unnecessary now that HTML5 is around:
<input name="q" autofocus />
It needs a form to make it work, Try this:
<form name="f">
<input name="q" value="test" type="text"/>
</form>
javascript:
document.f.q.focus();
document.f.q.value = 1;
Here is DEMO
The id attribute inside a html is meant to be unique.name can be an array(file[]) and with html5 should be used only on form elements.
html5 removed the support of the name atrribute on most elements except form elements.
id and name are 2 different things.
document refers to the whole html inside a page.
to get an element by it's id you need to call document.getElementById(id);
to get an element by it's name (considering html5) so inside a form
you call document.forms[0].name. form[0] refers to the first form inside the document
In your case the form has also a name so appart from html5 the code is correct.
form is called f,input is called q. thats why document.f.q returns the input field.
if you want to add an id to your input field then you have to add an id:
<input name="q" id="q">
to get the element:
document.getElementById('q');
to return the content:
document.getElementById('q').value;
And focus(); is a native function that points the focus to the choosen element.
In your case when you load the page you will see the blinking pointer inside the searchflied.

Setting the value of multiple inputs with the same id using jQuery?

Considering the following HTML:
<form id="upvoteForm" method="post" action="/post/upvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<input type="hidden" id="_postid" value="1"/>
I'm trying to set the two input fields with the name post_id to to value from _postid using this JavaScript and jQuery:
$(document).ready(function() {
$('#post_id').val($('#_postid').val());
});
However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.
Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have button inputs that I've styled the way I want but then I use the onclick to call the submit of the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.
id is always unique. you cannot select 2 elements with same id. select by name
$(document).ready(function() {
$('input[name=post_id]').val($('#_postid').val());
});
Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an input inside of a form with the name attribute set to post_id.

Relative form action resolves to absolute URL?

I am trying to get the actual string that is placed in a form action. The problem is when I do this, the action property resolves to an absolute path even though a relative path is in the HTML. How do I get the actual string that is in the action property?
Here is a sample of what I am referring to:
http://jsfiddle.net/MSY4s/
If you're already using jquery, I would use the .attr function rather than extracting the DOM element from the jQuery object. Like so:
$("form").attr("action");
That should give you literally what is in the action attribute. In the example you provided, that should look like "/somewhere". The second example in your jFiddle will show a full path since that's what is in the action attribute.
Relative URLs are always resolved to absolute ones on the base of the current document’s URL.
Try this:
Give both of your forms ids:
<form id="form1" action="/somewhere" method="post">
<input type="text" name="test" />
</form>
<form id="form2" action="https://fiddle.jshell.net/somewhere2" method="post">
<input type="text" name="test" />
</form>​
Then using these ids you can get the action attribute of each form:
$('#form1').attr('action');
$('#form2').attr('action');
You can also set the action attributes using the same tags:
$('#form1').attr('action', '[New Action Value]');
$('#form2').attr('action', '[New Action Value]');
Hope this helps.

Form not submitting with JS

I have the worlds most simple javascript function:
fnSubmit()
{
window.print();
document.formname.submit();
}
Which is called by:
<button type="button" id="submit" onclick="fnSubmit()">Submit</button>
All is well and good, the print dialog shows up, however after printing or canceling the print I get the following error:
"document.formname.submit is not a function"
My form is defined as follows: (obviously I am not using formname in the actual code but you get the idea)
<form name="formname" id="formname" method="post" action="<?=$_SERVER['SCRIPT_NAME']?>">
Obviously I am not trying to do anything special here and I have used similar approaches in the past, what in the world am I missing here?
In short: change the id of your submit button to something different than "submit". Also, don't set the name to this value either.
Now, some deeper insight. The general case is that document.formname.submit is a method that, when called, will submit the form. However, in your example, document.formname.submit is not a method anymore, but the DOM node representing the button.
This happens because elements of a form are available as attributes of its DOM node, via their name and id attributes. This wording is a bit confusing, so here comes an example:
<form name="example" id="example" action="/">
<input type="text" name="exampleField" />
<button type="button" name="submit" onclick="document.example.submit(); return false;">Submit</button>
</form>
On this example, document.forms.example.exampleField is a DOM node representing the field with name "exampleField". You can use JS to access its properties such as its value: document.forms.example.exampleField.value.
However, on this example there is an element of the form called "submit", and this is the submit button, which can be accessed with document.forms.example.submit. This overwrites the previous value, which was the function that allows you to submit the form.
EDIT:
If renaming the field isn't good for you, there is another solution. Shortly before writing this, I left the question on the site and got a response in the form of a neat JavaScript hack:
function hack() {
var form = document.createElement("form");
var myForm = document.example;
form.submit.apply(myForm);
}
See How to reliably submit an HTML form with JavaScript? for complete details
Given that your form has both an id and a name defined, you could use either one of these:
With the form tag's id:
document.getElementById('formname').submit();
With the form tag's name attribute:
document.forms['formname'].submit();
Try this:
fnSubmit()
{
window.print();
document.getElementById("formname").submit();
}
The most likely culprit is IE confusing JavaScript variables, ids, and names. Search in your source for something sharing the name of your form.
Place a input button inside your form.
Give tabindex="-1" on it.
Make It invisible using style="display:none;".
Like This
<input type="submit" tabindex="-1" style="display:none;" />

Categories