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">
0

5 Answers 5

8

To do this the correct selector is

$('input[name=fname]')
Sign up to request clarification or add additional context in comments.

1 Comment

$('input[id=fname]')
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/

Comments

0

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

$('input[name=fname]').on('blur', function() {
 //your code ...
});

Comments

0

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

1 Comment

a brief explanation as to why the answer works goes a long way to help others in the community
0

you can see demo here DEMO

$("input[name='fname']").blur(function(e){
   alert('blur')
});

Comments