简体   繁体   中英

Why is that only one element triggers the action even though I used .each?

I'm using this to take the value of an input and put it into another one at the end of the page:

jQuery( document ).ready(function() {
  jQuery('.free-lesson input[type="text"]').each(function () {
    jQuery(".free-lesson input[type='submit']").click(function(e) {
      e.preventDefault();
      var freeLessonContent = jQuery(this).val();
      jQuery("#mce-EMAIL").val(freeLessonContent);
    });
  });
});

there are many .free-lesson divs but strangely only the last one works (the others don't put any value to the input in the form.

How to fix this?

This is the site: http://www.chineselearnonline.com/amember/signup40.php

You don't need to add the foreach in there. The this you reference in the foreach is not th element you need. Try this out.

jQuery('.free-lesson-form [type="submit"]').click(function(e){
  e.preventDefault();
  jQuery('#mce-EMAIL').val(jQuery(this).prev().val()); //find the element previous to the one that was clicked. 
  //You may also want to use .parent() and find the input as this is more reliable if you move the markup around
});

What I've done here is to bind to the click event of all submits inside the free-lesson-form div. And then capture the value of the text input that is next to the button that was clicked. Tried this out on your site and it works for the current markup.

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