Last Option In Array (Numbers) (Checkboxes) Row Excludes All Others

  • mktfan
  • Avatar de mktfan Autor del tema
  • Invitado
  • Invitado
6 años 1 mes antes - 6 años 1 mes antes #99048 por mktfan
Hi,

I need your help with a javascript code.

I have an array question with checkboxes. I am trying to exclude all other options in a row if the user the last one. I've this article where you can find a javascript code to do it:

manual.limesurvey.org/Workarounds:_Manip..._Excludes_All_Others

The code proposed is:
<script type="text/javascript" charset="utf-8">
 
        $(document).ready(function() {
 
                // Call the exclude function using question ID(s)
                excludeOpt (QQ);
 
                // A function to make the last option in each array row exclusive
                function excludeOpt (qID) {
 
                        // Add some classes to the checkboxes so we can manipulate them
                        $('#question'+qID+' table.question tbody td').addClass('normalOpt');
                        $('#question'+qID+' table.question tbody').each(function(i) {
                                $('td:last', this).removeClass('normalOpt').addClass('exlusiveOpt')
                        });
 
                        // A listener on the checkbox cells
                        $('#question'+qID+' table.question tbody td').click(function (event) {
 
                                // Set some vars
                                var el = $(this).parent();
                                var optLength = $('td', el).length
 
                                // Uncheck the appropriate boxes in a row
                                if ($(this).hasClass('normalOpt')) {
                                        $('td:last input[type=checkbox]', el).attr('checked', false);
                                }
                                else {
                                        $('td', el).each(function(i) {
                                                if (i < (optLength - 1)) {
                                                        $('input[type=checkbox]', this).attr('checked', false);
                                                }
                                        });
                                }
                        });
 
                        // A listener on the checkboxes
                        $('#question'+qID+' table.question tbody td input[type=checkbox]').click(function (event) {
 
                                // Set some vars
                                var el2 = $(this).parent().parent();
                                var optLength = $('td', el2).length
 
                                // Uncheck the appropriate boxes in a row
                                if ($(this).parent().hasClass('normalOpt')) {
                                        $('td:last input[type=checkbox]', el2).attr('checked', false);
                                }
                                else {
                                        $('td', el2).each(function(i) {
                                                if (i < (optLength - 1)) {
                                                        $('input[type=checkbox]', this).attr('checked', false);
                                                }
                                        });
                                }
                        });
                }
        });
</script>

I've used it, but something weird happens. Please, have a look to my survey here:

enquestas.com/sv/index.php/333559/lang-es

Code only works in the last row, but not in the 2 first one.

I am using Limesurvey V2.0

Can you help me, please?

Many thanks in advance

Regards

Víctor
Última Edición: 6 años 1 mes antes por mktfan. Razón: faltaba URL

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

LimeSurvey Partners
Más
5 años 11 meses antes #99988 por w0928
I'm having the same problem. Can someone please post the code that actually works? I've tried manipulating the code myself but I am having no luck whatsoever.

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
5 años 11 meses antes #100005 por tpartner
Try this. Note that if using 1.92+, you do not need to replace "{QID}" - this tag will automatically insert the question ID:

<script type="text/javascript" charset="utf-8">	
	$(document).ready(function() {
		// Call the exclude function using question ID
		excludeOpt ({QID});
	});
 
	// A function to make the last option in each array row exclusive
	function excludeOpt (qID) {
 
		var thisQuestion = $('#question'+qID)
 
		// Add some classes to the checkbox cells
		$('table.question tbody td', thisQuestion).addClass('normalOpt');
		$('table.question tbody tr', thisQuestion).each(function(i) {
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt')
		});
 
		// A listener on the checkbox cells
		$('table.question tbody td', thisQuestion).click(function (event) {
 
			// Set some vars
			var thisRow = $(this).closest('tr');
 
			// Uncheck the appropriate boxes in a row
			if ($(this).hasClass('normalOpt')) {
				$('.exlusiveOpt input[type=checkbox]', thisRow).attr('checked', false);
			}
			else {
				$('.normalOpt input[type=checkbox]', thisRow).attr('checked', false);
			}
		});
 
		// A listener on the checkboxes
		$('table.question tbody td input[type=checkbox]', thisQuestion).click(function (event) {
 
			// Set some vars
			var thisRow = $(this).closest('tr');
			var thisCell = $(this).closest('td');
 
			// Uncheck the appropriate boxes in a row
			if ($(thisCell).hasClass('normalOpt')) {
				$('.exlusiveOpt input[type=checkbox]', thisRow).attr('checked', false);
			}
			else {
				$('.normalOpt input[type=checkbox]', thisRow).attr('checked', false);
			}
		});
	}	
</script>


I have updated the workaround - manual.limesurvey.org/Workarounds:_Manip..._Excludes_All_Others

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Official LimeSurvey Partner - partnersurveys.com
El siguiente usuario dijo gracias: w0928

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 9 meses antes - 4 años 9 meses antes #114688 por MVT
Hi,

I tried this but...
On some lines, the last column is "unchecked" after one or more other check-boxes checked.

I've a check-box matrix where the responses are mandatory.
I tried your snippet alone and with one other (check one column by default to avoid validation problems, I mean I've add a column on the right named "N/A" (NSP in French), and this colomn is checked by default on load.

It should be easier with the test survey.

Archivo Adjunto:

Nombre del Archivo: Test_Check...9228.lss
Tamaño del Archivo:27 KB


Limesurvey Release : 205plus-build141113

May be I did something wrong ?

Thanks for your help

<EDIT>
because of my insufficient knowledge in javascript, I suppose I did somme errors.
I've corrected the script in order to make it more "correct" but it doesn't work well
 < script type = "text/javascript" charset = "utf-8" >
	$(document).ready(function () {
 
		// Call the function with a question ID and column number Once
		var wQuit = true;
 
		if (wQuit) {
			checkedDefault({
				QID
			}, 12);
			wQuit = false;
		};
 
		// Call the exclude function using question ID
 
		excludeOpt({
			QID
		});
 
	});
 
// A function to pre-check a column of an array
 
function checkedDefault(qID, column) {
	var checkedCol = column - 1;
	$('#question' + qID + ' tr.subquestions-list').each(function (i) {
		if ($('input.checkbox:checked', this).length == 0) {
			$('input.checkbox:eq(' + checkedCol + ')', this).prop('checked', true);
			$('input.checkbox:eq(' + checkedCol + ')', this).parent().find('input[type="hidden"]').val(1);
		}
	});
}
// A function to make the last option in each array row exclusive
 
function excludeOpt(qID) {
 
	var thisQuestion = $('#question' + qID)
 
		// Add some classes to the checkbox cells
		$('table.subquestions-list tbody td', thisQuestion).addClass('normalOpt');
	$('table.subquestions-list tbody tr', thisQuestion).each(function (i) {
		$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt')
	});
 
	// A listener on the checkbox cells
 
	$('table.subquestions-list tbody td', thisQuestion).click(function (event) {
 
		// Set some vars
		var thisRow = $(this).closest('tr');
 
		// Uncheck the appropriate boxes in a row
		if ($(this).hasClass('normalOpt')) {
			$('.exlusiveOpt input[type=checkbox]', thisRow).attr('checked', false);
		} else {
			$('.normalOpt input[type=checkbox]', thisRow).attr('checked', false);
		}
	});
 
	// A listener on the checkboxes
 
	$('table.subquestions tbody td input[type=checkbox]', thisQuestion).click(function (event) {
 
		// Set some vars
		var thisRow = $(this).closest('tr');
		var thisCell = $(this).closest('td');
 
		// Uncheck the appropriate boxes in a row
		if ($(thisCell).hasClass('normalOpt')) {
			$('.exlusiveOpt input[type=checkbox]', thisRow).attr('checked', false);
		} else {
			$('.normalOpt input[type=checkbox]', thisRow).attr('checked', false);
		}
	});
}
 
<  / script >
Adjuntos:
Última Edición: 4 años 9 meses antes por MVT. Razón: modifications

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 9 meses antes - 4 años 9 meses antes #114732 por tpartner
Okay, so you want the last column to be checked by default and the last column is also exclusive.

Here's a simplified script to do that:

<script type="text/javascript" charset="utf-8">	
	$(document).ready(function() {
 
		// Identify this question
		var thisQuestion = $('#question{QID}');
 
		//// Check the last option in each row by default ////
		$('tr.subquestions-list', thisQuestion).each(function(i) {
			if ($('input.checkbox:checked', this).length == 0) {
				$('input.checkbox:last', this).prop('checked', true);
				$('input.checkbox:last', this).parent().find('input[type="hidden"]').val(1);
			}
		});
 
		//// Make the last option in each array row exclusive ////
		// Add some classes to the checkbox cells
		$('table.subquestions-list tbody td', thisQuestion).addClass('normalOpt');
		$('table.subquestions-list tbody tr', thisQuestion).each(function(i) {
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt')
		});
		// A listener on the checkboxes
		$('input[type=checkbox]', thisQuestion).change(function (event) {
 
			var thisRow = $(this).closest('tr');
			var thisCell = $(this).closest('td');
 
			if ($(this).is(':checked') && thisCell.hasClass('normalOpt')) {
				$('.exlusiveOpt input[type=checkbox]', thisRow).prop('checked', false);
				$('.exlusiveOpt input[type="hidden"]', thisRow).val('');
			}
			if ($(this).is(':checked') && thisCell.hasClass('exlusiveOpt')) {
				$('.normalOpt input[type=checkbox]', thisRow).prop('checked', false);
				$('.normalOpt input[type="hidden"]', thisRow).val('');
			}
		});
 
    });
</script>

And a working 2.05 survey:

Archivo Adjunto:

Nombre del Archivo: limesurvey...8_TP.lss
Tamaño del Archivo:27 KB

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Official LimeSurvey Partner - partnersurveys.com
Adjuntos:
Última Edición: 4 años 9 meses antes por tpartner.
El siguiente usuario dijo gracias: MVT

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 9 meses antes #114743 por MVT
Ok, thanks.

I'll try it on my new survey.
I've to redesign it in order to simplify the job for my respondents... if I want to have answers !

The best way should be to chain surveys in a conditional mode, I mean, to show the first part (participation after inscription), save some data and, at the end of the first survey, send an invitation for the second part (survey) with some data completed. But it is for "the future".

This first snippet should simplify the job for my first survey.

Regards

Michel

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 9 meses antes #115493 por MVT
Hi tpartner,

Sorry, I'm very late... I've to redesign my survey (reorder the questions... to put the questions that need more reflection at the beginning and the easiest ones at the end of the survey)

Your script works very well.

For the respondents, I've activated the save option. It should be better for them to have a look at the "pdf" release before answering the survey on line. So I hope I will not have to split the survey in 3 parts and have to look at a complex (for me)JavaScript management !

Thanks

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120467 por AndrejL
Hi!

I would like to alter the script from the first post to make exclusive last 2 (not just last one) elements in each array row. It sounded simple at first but as I'm no javascript expert I don't know how to do it myself.

Does anybody know how I can change the code to make it work?

Thanks,

Andrej

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120474 por tpartner
Try this to make the last two columns exclusive:

<script type="text/javascript" charset="utf-8">	
	$(document).ready(function() {
		// Call the exclude function using question ID
		excludeOpt ({QID});
	});
 
	// A function to make the last option in each array row exclusive
	function excludeOpt (qID) {
 
		var thisQuestion = $('#question'+qID)
 
		// Add some classes to the checkbox cells
		$('table.question tbody td', thisQuestion).addClass('normalOpt');
		$('table.question tbody tr', thisQuestion).each(function(i) {
			// Last two coluns are exclusive
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
		});
 
		// A listener on the checkboxes
		$('table.question tbody td input[type=checkbox]', thisQuestion).change(function (event) {
 
			if($(this).is(':checked')) {
				// Set some vars
				var thisRow = $(this).closest('tr');
				var thisCell = $(this).closest('td');
 
				// Uncheck the appropriate boxes in the row
				if ($(thisCell).hasClass('normalOpt')) { // Non-exclusive
					$('.exlusiveOpt input[type=checkbox]', thisRow).each(function(i) {
						$(this).prop('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
				else { // Exclusive
					$('input[type=checkbox]', thisRow).not(this).each(function(i) {
						$(this).prop('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
			}
		});
	}
</script>

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Official LimeSurvey Partner - partnersurveys.com

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120480 por AndrejL
I'm afraid it's not working. Now even last answer is not exclusive :(

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120483 por tpartner
What version of LimeSurvey are you using? Please give a link to a small test survey.

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Official LimeSurvey Partner - partnersurveys.com

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes - 4 años 4 meses antes #120485 por AndrejL
Of course.

We are using 2.00+,. And can not upgrade at this point.

I exported just this question here zadovoljstvo.sparslovenija.si/limesurvey...x.php/784886/lang-sl

First example uses first script and second one uses modified script.
Última Edición: 4 años 4 meses antes por AndrejL.

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120486 por tpartner
2.00+ uses an old version of jQuery so you'll need to use this:

<script type="text/javascript" charset="utf-8">	
	$(document).ready(function() {
		// Call the exclude function using question ID
		excludeOpt ({QID});
	});
 
	// A function to make the last option in each array row exclusive
	function excludeOpt (qID) {
 
		var thisQuestion = $('#question'+qID)
 
		// Add some classes to the checkbox cells
		$('table.question tbody td', thisQuestion).addClass('normalOpt');
		$('table.question tbody tr', thisQuestion).each(function(i) {
			// Last two coluns are exclusive
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
		});
 
		// A listener on the checkboxes
		$('table.question tbody td input[type=checkbox]', thisQuestion).click(function (event) {
			handleCheckboxes($(this).closest('td'))
		});
 
		// A listener on the checkbox cells
		$('table.question td.question-item', thisQuestion).click(function (event) {
			handleCheckboxes($(this));
		});
 
		function handleCheckboxes(thisCell) {
			// Set some vars
			var thisRow = thisCell.closest('tr');
			var thisInput = $('input[type=checkbox]', thisCell);
 
			if(thisInput.is(':checked')) {
 
				// Uncheck the appropriate boxes in the row
				if ($(thisCell).hasClass('normalOpt')) { // Non-exclusive
					$('.exlusiveOpt input[type=checkbox]', thisRow).each(function(i) {
						$(this).attr('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
				else { // Exclusive
					$('input[type=checkbox]', thisRow).not(thisInput).each(function(i) {
						$(this).attr('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
			}
		}
	}
</script>

Cheers,
Tony Partner

Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Official LimeSurvey Partner - partnersurveys.com

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
4 años 4 meses antes #120492 por AndrejL
I works perfect!

Thank you Tony!

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

Más
1 año 4 meses antes - 1 año 4 meses antes #167867 por krosser

tpartner escribió: Try this to make the last two columns exclusive:

<script type="text/javascript" charset="utf-8">	
	$(document).ready(function() {
		// Call the exclude function using question ID
		excludeOpt ({QID});
	});
 
	// A function to make the last option in each array row exclusive
	function excludeOpt (qID) {
 
		var thisQuestion = $('#question'+qID)
 
		// Add some classes to the checkbox cells
		$('table.question tbody td', thisQuestion).addClass('normalOpt');
		$('table.question tbody tr', thisQuestion).each(function(i) {
			// Last two coluns are exclusive
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
			$('.normalOpt:last', this).removeClass('normalOpt').addClass('exlusiveOpt');
		});
 
		// A listener on the checkboxes
		$('table.question tbody td input[type=checkbox]', thisQuestion).change(function (event) {
 
			if($(this).is(':checked')) {
				// Set some vars
				var thisRow = $(this).closest('tr');
				var thisCell = $(this).closest('td');
 
				// Uncheck the appropriate boxes in the row
				if ($(thisCell).hasClass('normalOpt')) { // Non-exclusive
					$('.exlusiveOpt input[type=checkbox]', thisRow).each(function(i) {
						$(this).prop('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
				else { // Exclusive
					$('input[type=checkbox]', thisRow).not(this).each(function(i) {
						$(this).prop('checked', false);
						$(this).closest('td').find('input[type="hidden"]').attr('value', '');
					});
				}
			}
		});
	}
</script>



I also have this issue in multiple choice when I need to make two last columns to deselect/cancel answers in the other columns. Unfortunately, this code does not work in LS 3.6-3.7.
Does someone have a working solution for it?

The example question attached to the post.

I'm using the latest LS 3.17 hosted on LS servers, not installed locally.
Adjuntos:
Última Edición: 1 año 4 meses antes por krosser. Razón: LSQ files are not allowed to attach... Had to zip it.

Por favor, Identificarse o Crear cuenta para unirse a la conversación.

¡Comenzar ahora!

Simplemente cree una cuenta y comience a usar LimeSurvey hoy mismo.

Registrarse ahora
¡Únase a nuestro boletín informativo!

Iniciar sesión