Home > Blockchain >  jQuery - I'm having trouble looping through elements by class and executing a function each tim
jQuery - I'm having trouble looping through elements by class and executing a function each tim

Time:07-08

Here is my jsfiddle:

https://jsfiddle.net/Lyt9o6b2/

HTML:

 <textarea  id="TextArea1">Text in block 1</textarea>
 <div  id="TextArea1PrintHelp"></div>
 <br/><br/><br/><br/><br/>
 <textarea  id="TextArea2">Text in block 2</textarea>
 <div  id="TextArea2PrintHelp"></div>

jQuery:

 function copy_to_print_helper(TextAreaID, PrintHelpID){
     $('#'   TextAreaID).text($('#'   PrintHelpID).val());
   }
   
 $('.TextArea').each(function(){
 copy_to_print_helper(this, this   'PrintHelp')
 })

On PageLoad, I want to loop through all of my textarea elements of class 'TextArea' and then execute the copy_to_print_helper() function to copy that textarea's text into the corresponding div. I have very little experience with jQuery but I'm guessing I'm not far off - any idea what I'm missing?

CodePudding user response:

The main issue is with your use of this in the jQuery event handler. That will hold a reference to the Element object. However in the copy_to_print_helper you expect this value to be a string which can be appended to the id of the element to form a selector, which is not the case. You would need to access the id property of the object for that to work - but even then there's a better approach.

Use the this reference of the object itself to get the properties of the textarea, and also to find the related element in the DOM. This completely avoids the need for any incremental id attributes which you dynamically target at runtime, making the HTML and JS code much more simple and reliable:

function copy_to_print_helper(textarea) {
  $(textarea).next('.PrintHelp').text(textarea.value);
}

$('.TextArea').each(function() {
  copy_to_print_helper(this)
})
.PrintHelp {
  margin-bottom: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea >Text in block 1</textarea>
<div ></div>

<textarea >Text in block 2</textarea>
<div ></div>

Taking this a step further, the logic can be made more succinct by providing a function to text() which returns the value to be displayed in each div using an implicit loop over every element in the collection:

$('.print-help').text(function() {
  return $(this).prev('.textarea').val();
});
.print-help { margin-bottom: 50px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea >Text in block 1</textarea>
<div ></div>

<textarea >Text in block 2</textarea>
<div ></div>

  • Related