Search code examples
javascriptjqueryjquery-uislideruislider

How do you replace values chosen with a word?


I'm very new at javascript and am attempting to create a slider scale that outputs a phrase instead of a value. The coding looks like this so far. I used the slider code from jqueryui as a base to learn.

$( function() {
		$( "#slider" ).slider({
			value:1,
			min: 1,
			max: 7,
			step: 1,
			slide: function( event, ui ) {
				$( "#amount" ).val( ui.value );
			}
		});
		$( "#amount" ).val( $( "#slider" ).slider( "value" ) );
	} );
  

I was thinking of adding an if / else statement, but I don't know how to implement it. I want each number to have a separate phrase attached to it. Is there a way to replace the output value (ex. 1, 2, 3, etc) with a word?


Solution

  • You would want to add cases up to your max number for the slider..

    var determineWord = function(value) {
      var word = "";
      console.log(value);
      switch (value) {
    
        case 1:
          word = "test";
          break;
    
        case 2:
          word = "test2";
          break;
      }
      console.log(word);
      return word;
    };
    
    $(document).ready(function() {
      $("#slider").slider({
        value: 1,
        min: 1,
        max: 7,
        step: 1,
        slide: function(event, ui) {
          $("#amount").val(determineWord(ui.value));
        }
      });
      $("#amount").val($("#slider").slider("value"));
    });
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <body>
      <div id="slider"></div>
      <br/><br/>
      <div id="amount"></div>
    </body>