Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea field returns empty upon submit

I have a simple question as part of a form. If the user answers "Yes", they are given the option to enter more details.

When a user does answer "Yes", and enters more detail in the textarea, on submit it returns empty. I can't figure out why. I feel like this is probably something small that I'm 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();
});
like image 239
kaoscify Avatar asked Dec 16 '15 03:12

kaoscify


1 Answers

You need to read the text area content again and set it to the response variable in the submit event before using it.

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

Here is a working jsFiddle

Or You need to set the response variable value on the keyup event of 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 agin in the submit event.

Here is a working sample for that.

like image 107
Shyju Avatar answered Oct 17 '22 13:10

Shyju