简体   繁体   中英

Set attributes for all form elements

How can I set the attributes for all form elements that was saved in a variable? I have tried with .attr() and it's working if I use one .attr() for each input field. I want to select the form and then add all attributes in the same object.

Something like this (but this isn't working):

var form = $("#myForm"),
    name = $("#name"),
    age  = $("#age");

form.attr({ 
  name: { 
    type: "text", 
    required: true, 
    placeholder: "Please enter your name.", 
    maxlength: 20, 
  },
  age: {
    type: "number", 
    required: true, 
    placeholder: "Please enter your age.", 
    maxlength: 2, 
  }
});

How should I do to make something like above?

You need to apply those objects to the elements directly, not through the form variable. Try this:

var $form = $("#myForm"),
    $name = $("#name"),
    $age  = $("#age");

$name.attr({ 
    type: "text", 
    required: true, 
    placeholder: "Please enter your name.", 
    maxlength: 20
});

$age.attr({
    type: "number", 
    required: true, 
    placeholder: "Please enter your age.", 
    maxlength: 2
});
name.attr ( {
    type: "text", 
    required: true, 
    placeholder: "Please enter your name.", 
    maxlength: 20
} );

age.attr ( {
    type: "number", 
    required: true, 
    placeholder: "Please enter your age.", 
    maxlength: 2
} );
var arrtibuteData = { 
  name: { 
    type: "text", 
    required: true, 
    placeholder: "Please enter your name.", 
    maxlength: 20, 
  },
  age: {
    type: "number", 
    required: true, 
    placeholder: "Please enter your age.", 
    maxlength: 2, 
  }
};  
form.data('you attribute name', arrtibuteData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM