Textarea field is returned blank after sending

I have a simple question as part of a form. If the user answers β€œYes”, they are given the opportunity to enter more detailed information.

When the user answers β€œYes” and enters more detailed information into textarea , upon sending, he returns empty. I can’t understand why. I feel that this is probably something small that I am missing.

Example: https://jsfiddle.net/sq8awxyk/

HTML

 <form> <div id="name-form"> <label for="name"><strong>Is this the correct name?</strong></label> <input type="radio" value="yes" name="name-choice" />Yes <input type="radio" value="no" name="name-choice" />No </div> <input id="submit" type="submit" value="submit" /> </form> 

JQuery

 // Name Input var nameFormLimit = 20; var nameInput = 'input[name=name-choice]'; var nameInputValue = $('input[name=name-choice]:checked').val(); var response; $(nameInput).on('click', function(e) { var nameInputValue = $('input[name=name-choice]:checked').val(); if (nameInputValue === 'yes') { var nameDiv = document.getElementById('name-form'); nameDiv.innerHTML = '<label for="name"><strong>Please type the correct name:</strong></label> ' + '<textarea id="textarea" name="name" rows="1" maxlength="' + nameFormLimit + '"></textarea> <div id="textarea_feedback"></div>'; $('#textarea_feedback').html(nameFormLimit + ' characters remaining'); $('#textarea').keyup(function() { var text_length = $('#textarea').val().length; var text_remaining = nameFormLimit - text_length; $('#textarea_feedback').html(text_remaining + ' characters remaining'); }); response = $('#textarea').val(); } else if (nameInputValue === 'no') { response = nameInputValue; } }); $('#submit').on('click', function(e) { alert(response); e.preventDefault(); }); 
+5
source share
1 answer

You need to read the contents of the text area again and set it to the response variable in the send event before using it.

 var response=""; $('#submit').on('click', function(e) { response = $('#textarea').val(); alert(response); e.preventDefault(); }); 

Here is the working jsFiddle

Or you need to set the value of the response variable in the keyup event in the text area.

 $(document).on("keyup","#textarea",function() { var text_length = $('#textarea').val().length; var text_remaining = nameFormLimit - text_length; $('#textarea_feedback').html(text_remaining + ' characters remaining'); response = $('#textarea').val(); }); 

With this change, you do not need to read it in the send event.

Here is a working model for this.

+6
source

Source: https://habr.com/ru/post/1238330/


All Articles