2

I have a form that has multiple input, select, textarea elements. With jQuery, How can I get the name attribute values of each element? I have tried the following but its not working:

var names = $('[name]');
names.each(function(){
    console.log(names.attr('name'));
})
0

7 Answers 7

5

You need to use this within the each() to refer to the element within the current iteration. Your current code is attempting to get the name of a set of elements which is logically incorrect. Try this:

var names = $('[name]');
names.each(function(){
    console.log($(this).attr('name'));
})
Sign up to request clarification or add additional context in comments.

Comments

3

You are still using names within your each function. Try this:

var names = $('[name]');
names.each(function(index, name){
    console.log($(name).attr('name'));
})

Comments

0

This should loop around all the required elements and output the name and value to the console.

$('input,select,textarea').each(function() {
  var thisname = $(this).attr('name');
  var thisval = $(this).val();
  console.log('name = ' + thisname);
  console.log('value = ' + thisval);
});

Comments

0

You can try this way too.

var $name = $("[name]");
$name.get().map(function(elem,index){
    console.log($(elem).attr("name"));
});

Comments

0

Add a class to all the elements you wish to get the names of. Then you get all the elements from that class and iterate them to get their names.

formElements = $('.form-element');
for(key in formElements) {
      name = formElements[key].attr('name');
      // do what you wish with the element's name
}

P.S. You may need to wrap formElements[key] in $(), have not tested it.

Comments

0
    // Selects elements that have the 'name' attribute, with any value.
    var htmlElements = $("[name]");

    $.each(htmlElements, function(index, htmlElement){
        // this function is called for each html element wich has attribute 'name'

        var $element = $(htmlElement);

        // Get name attribute for input, select, textarea only
        if ($element.is("input") || 
            $element.is("select") ||
            $element.is("textarea")) {
            console.log($element.attr("name"));
        }
    });

Comments

-3

Give your input ID then call attr() method

$("#id").attr("name");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.