Welcome, Guest
Username: Password: Remember me

TOPIC: field validation and optional answer

field validation and optional answer 3 years 2 weeks ago #65327

Hi,

I'm using Version 1.91+ Build 10746 (on Linux) and would like to use the advanced input settings for basic field validation. Everything works fine on the numeric field I'm validating, but I have the additional requirement that the answer is optional.

The question is for example on the height of a person. the requirement states that the person has to taller than 45cm and cannot be taller the 250cm. That;s the easy part and that works out of the box. I have another requirement that stipulates that this question does not have to be answered. I'm not sure how to do this.

Thanks
The administrator has disabled public write access.

Re: field validation and optional answer 3 years 2 weeks ago #65339

  • tpartner
  • tpartner's Avatar
  • OFFLINE
  • LimeSurvey Team
  • Posts: 4192
  • Thank you received: 788
  • Karma: 359
You can use JavaScript to validate the response.

1) Set up your survey to use JavaScript.

2) Add the following script to the source of the numeric question. Replace "QQ" with the numeric question ID.

The script puts a listener on the numeric input. If a number lower than 45 or higher than 250 is entered, the respondent is alerted and the input is cleared.
<script type="text/javascript" charset="utf-8">
 
	$(document).ready(function() {
 
		var qID = QQ;
		var msg = 'The height must be between 45 and 250. Please re-enter it';
 
		$('#question'+qID+' input.text').change(function(){
			if($(this).val() && ($(this).val() < 45 || $(this).val() > 250)) {
				alert (msg);
				$(this).val('');
			}
		});
	});
 
</script>
Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.

LimeSurvey is open-source and run entirely by volunteers so please consider donating to support the project.
Last Edit: 3 years 2 weeks ago by tpartner.
The administrator has disabled public write access.

Re: field validation and optional answer 3 years 2 weeks ago #65351

Thanks for the quick reply.

I couldn't quite get it to work, but modified your code as follows, which works perfectly.

<script type="text/javascript" charset="utf-8">

$(document).ready(function() {

var msg = 'The height must be between 45 and 250. Please re-enter it';

$('#answer{SGQ}').change(function(){
if($(this).val() && ($(this).val() < 45 || $(this).val() > 250)) {
alert (msg);
$(this).val('');
}
});
});

</script>

For the uninitiated, what's the difference between #question and #answer

$('#question'+qID+' input.text').change(function() and
$('#answer{SGQ}').change(function()
The administrator has disabled public write access.
Moderators: ITEd
Time to create page: 0.100 seconds
Donation Image