0

Why I can't get the updated text from two textarea elements that have the same class and default text?

For example, if I try to add new text to any of these textarea elements then hit the button I get only the old values.

This is my code:

HTML

<div class="tag-container">
  <textarea class="variables">s:asset:type, s:event:type, l:event:playhead, s:asset:video_id, s:asset:ad_id, s:user:mid</textarea>
  <button class="remove-tag">Remove</button>
  <hr/>
</div>

<div class="tag-container">
  <textarea class="variables">name, mid, pev3</textarea>
  <button class="remove-tag">Remove</button>
  <hr/>
</div>

<button class="validate">Validate</button>

JS:

$(document).on('click', '.validate', function() {

  var variables = "";
  $('.variables').each(function(){
    variables += $(this).text() + ",";
  });

  console.log(variables);
});

JSFIDDLE

Valip
  • 4,440
  • 19
  • 79
  • 150
  • 1
    use `$(this).val()` to get the current value. I believe `.text()` retrieves the DOM text, meaning what the text was on load. – Kramb Jul 17 '17 at 12:53
  • I'm logging the results with `.val()` and it isn't working – Valip Jul 17 '17 at 12:54
  • Use `$(this).html()` – Celestine Jul 17 '17 at 12:56
  • 1
    Are people just guessing what's the issue in the comments...? You're printing $('.variables').val() which would print the first textbox. Change your last console.log to console.log(variables); ... – Adrian Jul 17 '17 at 12:59
  • @Carrot--Show tried with `.html()` and still not getting the updated text – Valip Jul 17 '17 at 13:01
  • @Adriani6 changed it, and the variable `variables` is not getting updated with the new text – Valip Jul 17 '17 at 13:02
  • @Valip that's odd. the code is working for me. https://jsfiddle.net/vnujunnp/ – Celestine Jul 17 '17 at 13:03
  • @Carrot--Show type something in the second textarea and then hit the button. Your newly introduced text will be not displayed in the console.. – Valip Jul 17 '17 at 13:05
  • 1
    @Valip I have updated your snippet, have a look... https://jsfiddle.net/ntLvcwm9/5/ – Adrian Jul 17 '17 at 13:13
  • The problem was the second `+` from here `variables += $(this).text() + ","` – Valip Jul 17 '17 at 13:25

0 Answers0