简体   繁体   中英

Jquery select a input filed from a form using wildcard selector

I would like to select a input field from a form on the fly, which mean, I don't know which form it would be. consider the following code: ( Suppose the input field id is always 'input1' across all forms)

$('[id^=myform]').submit(function(){
   var formId = $(this).attr('id');
   var result = $('#' + formId + ' input#inputl').val();
   ...
});

I am looking for a better solution for my purpose. Is there any?

You'd be better off using the name attribute of the element (having multiple elements with the same ID is invalid in HTML), and making sure those names are kept consistent across forms:

$('[id^=myform]').submit(function(){
  var result = $(this).find('[name="email"]').val();
  ...
});
$('[id^=myform]').submit(function(){
   var result = $(this).find('#input1').val();
});

Although like commented above. Ids are supposed to be unique across the entire page so you might need to change the id attribute into a name attribute for all of those input fields.

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