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();
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With