5

Is it possible to access an form input field using just the element name?

If I were attempting this with the ID, it would look like this:

<input type="text" id="fname">

$("#fname").blur(function(){
    var x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
});

Is there any way to get access the element using the name is the field were??:

<input type="text" name="fname">

5 Answers5

8

To do this the correct selector is

$('input[name=fname]')
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35
2

You can do

$('[name="fname"]')

But it is recommended to use an id/class that is more efficient that doing an attribute selector.

http://learn.jquery.com/using-jquery-core/selecting-elements/ http://learn.jquery.com/performance/optimize-selectors/

Taplar
  • 24,788
  • 4
  • 22
  • 35
0

See all the selectors you can use: https://api.jquery.com/category/selectors/

$('input[name=fname]').on('blur', function() {
 //your code ...
});
Sam Battat
  • 5,725
  • 1
  • 20
  • 29
0

You can use $("input[name=fname]")

zelitomas
  • 113
  • 8
0

you can see demo here DEMO

$("input[name='fname']").blur(function(e){
   alert('blur')
});
Prashant
  • 704
  • 10
  • 23