Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery UI to convert radio buttons into slider elements

I have a form which is rendered with radio buttons like so:

<h2>How long is your hair?</h2>
<input type="radio" name="71" value="98">Short 
<input type="radio" name="71" value="99">Medium 
<input type="radio" name="71" value="100">Long 

There are about 15 questions like this, and I would like to have the whole form rendered with sliders, using JQuery (Jquery UI seems like the most likely candidate).

I have found a few plugins for converting select boxes to sliders (e.g. selectToUISlider) but none for radio buttons.

I'm sure it is possible to roll my own somehow using the standard UI Slider, but I don't really know where to start. Has anyone already made a plug in to achieve this?

like image 848
jsims281 Avatar asked Dec 07 '22 02:12

jsims281


1 Answers

Here's the basic structure of one option, I'm not sure how your questions differ (do they all have 3 options?) so the styling would vary, just trying to demonstrate the concept.

I'm not sure what each question is contained in, so I put your content in a <div class="question">, then gave the inputs labels (degrades a bit better for non-JS users), like this overall:

<div class="question">
  <h2>How long is your hair?</h2>
  <label><input type="radio" name="71" value="98">Short</label>
  <label><input type="radio" name="71" value="99">Medium</label>
  <label><input type="radio" name="71" value="100">Long</label>
</div>

Then a bit of script to transform it into a slider, like this:

$(".question").each(function() {
    var radios = $(this).find(":radio").hide();
    $("<div></div>").slider({
      min: parseInt(radios.first().val(), 10),
      max: parseInt(radios.last().val(), 10),
      slide: function(event, ui) {
        radios.filter("[value=" + ui.value + "]").click();
      }
    }).appendTo(this);
});

You can give it a try here

like image 107
Nick Craver Avatar answered Jan 25 '23 10:01

Nick Craver