Accessing Input element through input name in javascript - javascript

I want to access the following code using java script. Can anyone help me please? I'm a beginner to JavaScript.
<input type="text" name="username" />
I wish to access the element from its name property. An alert box needs to be shown if the length of element value is less than 6.

Use getElementsByName() method,
document.getElementsByName('username')
getElementsByName() returns an array of elements.

The getElementsByName() method returns a collection of all elements in the document with the specified name
var x = document.getElementsByName("username")[0].tagName;
Its better you can use id instead of name if it is unique.
<input type="text" id="username" />
var x=document.getElementById("username");

Try using document.getElementById(), need to specify unique id
var usrtxt = document.getElementById('usrtxt');
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" id='usrtxt' value='admin' />
Try using document.getElementsByTagName()
var inputArray = document.getElementsByTagName('input');//gives array
var usrtxt = inputArray[0];//get first element
alert(usrtxt.name + ": " + usrtxt.value);
<input type="text" name="username" value='admin' />

Probably the input is in a form like:
<form ...>
<input name="username">
...
</form>
and probably you want to validate it when the form is submitted, so in that case you likely have a listener on the form like:
<form onsubmit="return validate(this)" ...>
and in the validate function:
function validate(form) {
// get input as form.username
if (form.username.value.length < 6) {
alert('Username must be 6 or more characters long');
// Prevent form submission
return false;
}
}
You may want to be more sophisticated with the UI (your users will appreciate it), but the above shows the basics.

If you wish to identify particular element using Name then use getElementsByName function
Javascript:
var x = document.getElementsByName('username');
If you consider to use the Jquery then please use following code.
Jquery:
$('[name="username"]');
Learn more about Jquery Selectors
Update:
var x = document.getElementsByName('username'); // X is an array here as getElementsByName returns collection i.e. Array
var val = x[0];//get first element
if(val.value.length < 6) // Check if its value greater than 6
{
alert('boom !!');
}
}

Related

Insert the attribute value of input element in form

I have a form with no id or class. I need to insert attribute values for input elements.
<form>
<tr><td><input type="text" name="x"/></td></tr>
<tr><td><input type="text" name="y"/></td></tr>
<tr><td><input type="text" name="z"/></td></tr>
</form>
Here's jquery I tried:
var x = $('form').find('input').first().val("some_value");
var y = $('form').find('input').second().val("some_value");
var z = $('form').find('input').third().val("some_value");
// Is there another possible way?
var x = $("form").find('input[name="x"]').val("some_value");
You can use Attribute Equals Selector [name=”value”] to uniquely identify the inputs
$('input[name=x]').val("some_value1");
$('input[name=y]').val("some_value2");
$('input[name=z]').val("some_value3");
Although I wont recommend the method you used to assign values to input, I would suggest you to use find() once and use the returned object collection to assign values. This will reduce the processing time and increase performance.
var all = $('form').find('input');
all.eq(0).val("some_value1");
all.eq(1).val("some_value2");
all.eq(2).val("some_value3");
You can use
$("form").find('input[type="text"]]').each(function() {
$(this).attr("your attribute", "your value");
});
try with this
var x = $('form input[name="x"]').val("some_value_x");
// So you can search across the form for all input elements and then iterate to apply the attribute.
var allInputElements = $("form input[type='text']");
$.each(allInputElements,function(index, item){
$(item).attr("disabled","true");
// You can also use item.prop("any property or attribute","value");
});
If you're giving them all the same value, as it appears in your question, you can simply select them all:
$("form input").val("some_value");

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

How do I get a handle to a dynamically-generated field name in javascript?

I have a series of fields created dynamically based on database records. They will be named cardObject1, cardObject2, and so on for as many rows as necessary. I'm now trying to access a specific cardObject field in a function where the number is passed in, but am getting an error message.
The field looks like this:
<input name="cardObject241" value="2,$25.00,1" type="hidden">
The js code I'm using looks like this:
function deleteFromCart(id){
if (confirm("Are you sure you want to delete this item from your cart?")){
var voucherNbr = document.getElementById("voucherNbr").value;
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
var amtToDelete = cardObjectArray[1];
alert("need to delete " + amtToDelete);
}
}
And the error I'm getting is
document.getElementById("cardObject" + id) is null
on this line:
var cardObjectArray = document.getElementById("cardObject"+id).value.split();
How can I get a handle to the cardObject field that ends with the number passed in as the id param?
You need to add an id="" attribute with the same name as the name attribute.
<input id="cardObject241" name="cardObject241" value="2,$25.00,1" type="hidden">
Firstly, your input field needs an id as well as a name, so it would look like this:
<input name="cardObject241" id="cardObject241" value="2,$25.00,1" type="hidden">
Secondly, if you have an object that may or may not exist, it's always a good idea to check for existence before you start manipulating properties:
var tempObj=document.getElementById("cardObject"+id)
if(tempObj) {
var cardObjectArray = tempObj.value.split();
...do your stuff with cardObjectArray....
}
You can use document.getElementsByName() or (cross-browser back to the Stone Age)
document.forms[formIndexOrName].elements["cardObject" + id].value.split(",")

Categories

Resources