Insert the attribute value of input element in form - javascript

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");

Related

Accessing Input element through input name in 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 !!');
}
}

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 to get the value of textbox using id in javascript

I want to get the value of input boxes based on id and name.
Since my id is having comma its not accepting. When i remove comma and one of the id,it shows perfectly.
But, I will get the id as "Text,Demo_1" only. How can i get the value based on this id??
here is the code
HTML
<div id="Text,Demo_1" class="span12">
<label>Notes or Concerns</label>
<div class="control-group">
<input type="text" value="hi" name="view1" class="recommend">
<input type="text" value="hi2" name="view1" class="recommend">
<input type="text" value="hi3" name="view1" class="recommend">
</div>
</div>
Js part
$(function() {
var values = $('#Text,Demo_1 input[name="view1"]').map(function() {
return this.value;
}).get();
alert(values);
});
Get value by Name :
$("[name='view1']").val()
Get value by ID :
$("#[textbox_ID]").val()
Get all text values in array
var inputTypes = [];
$('.control-group input[name="view1"]').each(function(){
inputTypes.push($(this).val());
});
Use an array,
$(function () {
var values = [];
$('#TextDemo_1 input[name="view1"]').each(function () {
values.push($(this).val());
});
console.dir(values);
});
You should escape your comma with \\
var values = $('#Text\\,Demo_1 input[name="view1"]').map(function () {
return this.value;
}).get();
Demo: http://jsfiddle.net/M8Jmz/
But while it works you should consider changing an id to a proper identifier.
Use jQuery selectors to match the begining and end of the ID:
var values = $("div[id^='Text'][id$='Demo_1'] input[name='view1']").map(function() {
...
Edit: Explanation.
[id^='Text'] => Every element which id starts with "Text"
[id$='Demo_1'] => Every element which id ends with "Demo_1"
Putting them together will select every element that match both rules.
var values = $('input[name="view1"]').val();

array input text get value

i want to get input text value of array in javascript
this is my code :
Item : <input id="t_item" name="t_item[]" type="text" class="teks3">
Cost : <input id="t_cost" name="t_cost[]" type="text" class="teks3">
<input type="button" id="tb_more_item" class="add_file"/>
and the js code is :
$("input#tb_more_item").click(function(){
var new_file = $("
Item : <input id='t_item' name='t_item[]' type='text' class='teks3'/>
Cost : <input id='t_cost' name='t_cost[]' type='text' class='teks3'/>
");
$("div#div_item").append(new_file).fadeIn();
});
i try to get more item value with this code :
var item_value = [], cost_value = [];
$("input#t_item").each(function() {
$thisItem = $(this);
item_value = $thisItem.val();
});
$("input#t_cost").each(function() {
$thisCost = $(this);
cost_value = $thisCost.val();
});
alert(item_value +"-"+ cost_value );
the result is get the last value value i've typed in the input text.
does anyone have the solutions?
thanks
You're creating invalid html by appending elements with duplicate ids. Update the .each() selectors to use the name attribute instead.
Also, inside the .each() functions you are overwriting the array variables with the value of the current item - that is, the array gets thrown away and replaced with the value, which is why that variable holds only the last value after the .each() finishes. What you want to do is add the value of each input as a separate element in the array:
$('input[name="t_item\\[\\]"]').each(function() {
item_value.push(this.value);
});
And similar for t_cost.

jQuery access input hidden value

How can I access <input type="hidden"> tag's value attribute using jQuery?
You can access hidden fields' values with val(), just like you can do on any other input element:
<input type="hidden" id="foo" name="zyx" value="bar" />
alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());
Those all mean the same thing in this example.
The most efficient way is by ID.
$("#foo").val(); //by id
You can read more here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Writing_efficient_CSS
https://developers.google.com/speed/docs/best-practices/rendering?hl=it#UseEfficientCSSSelectors
There's a jQuery selector for that:
// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );
// Filter those which have a specific type
hidden_fields.attr( 'text' );
Will give you all hidden input fields and filter by those with a specific type="".
To get value, use:
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
var valueOfHidFiled=$(this).val();
alert(valueOfHidFiled);
}
});
or:
var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);
To set value, use:
$('input[type=hidden]').attr('value',newValue);
There is nothing special about <input type="hidden">:
$('input[type="hidden"]').val()
If you want to select an individual hidden field, you can select it through the different selectors of jQuery :
<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/>
$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class
If you have an asp.net HiddenField you need to:
To access HiddenField Value:
$('#<%=HF.ClientID%>').val() // HF = your hiddenfield ID
To set HiddenFieldValue
$('#<%=HF.ClientID%>').val('some value') // HF = your hiddenfield ID
Watch out if you want to retrieve a boolean value from a hidden field!
For example:
<input type="hidden" id="SomeBoolean" value="False"/>
(An input like this will be rendered by ASP MVC if you use #Html.HiddenFor(m => m.SomeBoolean).)
Then the following will return a string 'False', not a JS boolean!
var notABool = $('#SomeBoolean').val();
If you want to use the boolean for some logic, use the following instead:
var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }
Most universal way is to take value by name. It doesn't matter if its input or select form element type.
var value = $('[name="foo"]');

Categories

Resources