Skip to content

Getting a value by name in javascript/razor application

i have an asp application in which i have to use javascript to get the value of an element

@for(int i=0; i< Model.Count; i++) {
    <input type="text" value="@Model[i].age" name="age@(i)" />
    HtmlActionLink("new age","Change", new { age = "age" + i.ToString()

I need to get the value of each tag age : new { age = "age" + i.ToString() didn’t work and i have to replace it by a script javascript using document.getElementsByName method

How can i modify my code to do this task?


I would simply add a class to each input element that gives it some meaning (e.g. ‘input-age’):

<input class="input-age" type="text" value="@Model[i].age" name="age@(i)" />

And then you could select all of the inputs by class name and not need to rely on the dynamically assigned name from the view engine:

var ages = document.querySelectorAll('input.input-age');

Or if you need to find the value for a specific age index, without adding a class name:

var ageIndex = 4;
var age = document.querySelector('input[name="age' + ageIndex + '"]').value;

FYI, for IE, it will only work in versions 8 or higher because of the querySelectorAll function, but you could use other methods.

If jQuery was on the table, you could not change anything and use the “starts with” selector to get all “age” elements:

var ages = $('input[name^="age"]');

Or, after adding a class name:

var ages = $('.input-age');

Or, hunt down the value for a specific input:

var ageIndex = 4;
var age = $('input[name="age' + ageIndex + '"]').val();

With the last example, you don’t need to add the class name;