What is document.f.q.focus? - javascript

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.

Related

Find data* attribute without specifying tag using jquery

Playing around with making a small data binding javascript library but I'm a little newer to javascript. Is there a way to just find the element, and all enclosing elements that have the data-bind attribute defined?
<form data-bind="Customer">
<input type="text" id="name" data-bind="Name" data-bind-type="text" />
<input type="text" id="birthday" data-bind="Birthday" data-bind-type="text" />
<input type="text" id="address" data-bind="Address" data-bind-type="text" />
</form>
I want to define a function where I just pass in the "Customer" value and it will find the tag that has the data-bind = "Customer" (form in this case) and all tags within said containing tag that have the data-bind attribute defined. In this case it would return all 3 input tags so that I could examine them further.
Everything I've seen using jquery to do this is showing that I would need to know the "form" or the tag id to do this, but I'd prefer not to have to specify tag (like form) or id.
You can at all data-bind elements within a particular data-bind element in this way:
$('[data-bind="Customer"] [data-bind]');
If you want to wrap that in a function, for instance if you need to access other wrapper elements with a different data-bind attribute value, you could do:
function getBoundElms(name) {
return $('[data-bind="' + name + '"] [data-bind]');
}
$('[data-bind="Customer"]').children('[data-bind]')
look at this fiddle
http://jsfiddle.net/QBM5/M9eea/

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.

Getting hidden inputs in HTML (that has period in name) from a form using Javascript

I have the following HTML:
<body>
<form action="/test/interop/InteropServlet" method="post" id="formTester" name="formTester">
<input type="hidden" name="ApiName" value=""/>
<input type="hidden" name="test.userId" value="admin"/>
<input type="hidden" name="test.password" value="admin"/>
<input type="hidden" name="test.progId" value="CustomTester"/>
<input type="hidden" name="InteropApiData" value=""/>
<input type="hidden" name="TemplateData" value=""/>
and I would like to use Javascript to get these hidden values and set them on clicking a button. I have the following Javscript method:
function callAPI(myform) {
saveCookies();
myform.ApiName.value=document.getElementById("traceName").value;
myform.TemplateData.value=document.getElementById("templateXMLText").value;
myform.test.userId.value=document.getElementById("userIDText").value;
myform.test.password.value=document.getElementById("passwordText").value;
myform.action="http://"+document.getElementById("urlText").value + "/test/interop/InteropHttpServlet";
myform.submit();
}
and this works for the hidden inputs that do not have a period in the name (ie test.userId, test.password) as I get the error "Error: TypeError: myform.test is undefined". I am unable to rename these hidden inputs due to the fact I do not maintain the code I am calling out to and the variables must be named this.
Is there any way I can read hidden inputs that have a period in the name from a form?
Another option, preferable in my opinion, is to use querySelector() to get the specific element:
myform.querySelector('input[name="test.userId"]').value="whatever";
DEMO: http://jsfiddle.net/xjG6W/
For visual purposes, in the demo I changed test.userId to be type="text". Type in the second textbox and click the button - it will change the first textbox's value (really, it's a hidden input).
References:
https://developer.mozilla.org/en-US/docs/DOM/Element.querySelector
Use the square bracket notation for accessing elements with a period in the name. For ex:
myform['test.userId'].value
In your case, this would become:
...
myform['test.userId'].value=document.getElementById("userIDText").value;
myform['test.password'].value=document.getElementById("passwordText").value;
...

Setting a label's for attribute to a DOM element, not an ID in jQuery

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.

jQuery Selecting the first child with a specific attribute

I have a form in HTML with multiple inputs of type submit:
<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>
What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:
var name = $(this).find("input[type='submit']").val();
I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.
Try:
$(this).children("input[type='submit']:first").val();
how about the first selector
var name = $("input[type='submit']:first").val();

Categories