0

I am struggling on how to make the result output into images like: image 1, image 2 so on... Is there way to store all those images in the javascript and then show them on the result?

Here's the script of what i am talking about, please bear with me, i am learning and i am not an expert.

function proRangeSlider(sliderid, outputid, colorclass) {
        var x = document.getElementById(sliderid).value;  
        document.getElementById(outputid).innerHTML = x;
        document.getElementById(sliderid).setAttribute('class', colorclass);
        
        updateTotal();
}

var total = 0;
function updateTotal() {
        var list= document.getElementsByClassName("range");
        [].forEach.call(list, function(el) {
            console.log(el.value);
            total += parseInt(el.value);
        }); 
        document.getElementById("n_total").innerHTML = total;
      
}
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('form').submit('click', function() {
        $(this).hide();
        $('html, body').animate({
     scrollTop: $("#anchor").offset().top
 }, 500);
        $("#result").empty().append(
            "<ul>" + Object.entries($('form').serializeObject()).map(e => `<li>${e[0]}: ${e[1]}`).join("") + "</ul>");
        $(".hidden-block").show();
        return false;
    });
});

$(document).ready(function(){
        $("#reset").click(function(){
            location.reload(true);
    });
});

Here's my project in case you would like to view the source: https://jsfiddle.net/archer201977/h9f6r21u/6/

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • _"i am learning and i am not an expert"_ - Why do you start with jQuery (are you even aware of that fact)? That script in your question uses some "advanced" techniques and uses a custom jQuery extension. – Andreas Feb 14 '22 at 08:13
  • No that's why i am here asking, and learning at the same time, this has been modified by me, but needs more modification hence the reason i am here to ask help to better understand and in turn take this as a lesson. Thank you! –  Feb 14 '22 at 08:16
  • Do you want to change all the e[1] into a relative image based on a scale? – Tlotli Otlotleng Feb 14 '22 at 08:38
  • I guess yes, if that's possible but i would like to retain also the number if that's possible, if not? that's ok. Thank you - That goes for every slide. –  Feb 14 '22 at 08:53
  • This is not an answer, but since you say you're learning, I suggest that you re-write the whole script on your side, renaming all the variables which are letters (meaningless) into whole words having a meaning and a real connection to what each variable is really holding. Trust me it helps a lot comprehending algorithms (even for advanced programmers) – wiwi Feb 14 '22 at 09:26
  • What wiwi wants to say, is: rename `o` to `ob` :D – Roko C. Buljan Feb 14 '22 at 10:24
  • Maybe i didn't explain well, everything is working as intended, but i would want the results to show up as images corresponding to the result, let's say the result after the user interacts with the slider - will show 2, 5, 6, 10 - instead of it showing a number, it should then show images for those numbers, like: image2, image5, image6. so on.. if that is possible? otherwise lets drop this and i'll move on thank you. –  Feb 14 '22 at 10:54
  • 1
    `$('form').submit('click', function() {` this is just wrong. Your fiddle has it correctly though. Nonetheless, use always the `.on()` Method like: `$("form").on("submit", cb);` – Roko C. Buljan Feb 14 '22 at 12:30

1 Answers1

1

I'm not sure what you mean by 'image' here, but maybe you want to display the slider within div#result?

Your code has some issues. To educate and entertain I've created a minimal reproducable example, presuming that by 'image' you mean the actual sliders. It

document.addEventListener(`change`, handle);
updateTotal();

function handle(evt) {
  if (evt.target.dataset.inputstate) {
    return displayResult(evt.target);
  }
}

function displayResult(origin) {
  proRangeSlider(origin, ...origin.dataset.inputstate.split(`,`));
  let totalValues = [];
  document.querySelectorAll(`[data-inputstate]`).forEach(range => {
    const rangeClone = createClone(range);
    totalValues.push(`<li><div>${rangeClone}</div><div>${
        range.dataset.name}: ${range.value}</div></li>`);
  });
  totalValues.push(`<li><div><b>Total: ${
    document.querySelector(`#n_total`).textContent}</b></div></li>`);
  document.querySelector(`#result`).innerHTML = `<ul>${totalValues.join(``)}</ul>`;
}

function createClone(fromRange) {
  const clone = fromRange.cloneNode();
  clone.setAttribute(`value`, fromRange.value);
  clone.id = ``;
  clone.removeAttribute(`data-inputstate`);
  return clone.outerHTML;
}

function proRangeSlider(origin, outputId, colorclass) {
  origin.closest(`div`).querySelector(`#${outputId}`).textContent = origin.value;
  origin.setAttribute('class', colorclass);
  updateTotal();
}

function updateTotal() {
  let total = 0;
  [...document.querySelectorAll(`[data-inputstate]`)]
    .forEach(elem => total += +elem.value);
  document.getElementById("n_total").textContent = total;
}
body,
html {
  margin: 10px;
}

#proRangeSlider {
  border: 1px solid #CCC;
  padding: 0;
}

div {
  background: #f1f1f1;
  border-bottom: 1px dotted #666;
  padding: 2px 0px;
}

div:last-child {
  border: none;
}

input {
  -webkit-appearance: none;
  width: 160px;
  height: 15px;
  background: linear-gradient(to right, #16a085 0%, #16a085 100%);
  background-size: 150px 10px;
  background-position: center;
  background-repeat: no-repeat;
  overflow: hidden;
  outline: none;
  vertical-align: middle;
}

input::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  background: #27ae60;
  position: relative;
  z-index: 3;
}

#total {
  padding-left: 7px;
}

.blue::-webkit-slider-thumb {
  background: #2980b9;
}

.orange::-webkit-slider-thumb {
  background: #d35400;
}

#result {
  margin-bottom: 0;
  border: none;
  padding: 5px;
  background-color: transparent;
}

#result ul {
  margin-left: -1.5rem;
}

#result ul li div {
  display: inline-block;
  vertical-align: middle;
  background-color: transparent;
  border: none;
  padding: 0 3px;
}

#result ul li div input[type=range] {
  height: auto;
  margin-left: -0.4rem;
}

#result ul li {
  text-align: left;
}
<div id="proRangeSlider">
  <div id="total">TOTAL: <span id="n_total"></span></div>
  <div>
    <input type="range" data-name="Cost per day" class="range orange" value="20" data-inputstate="output1,orange">
    <output id="output1">20</output>
  </div>

  <div>
    <input type="range" data-name="Number of days" value="50" class="blue range" data-inputstate="output2,blue">
    <output id="output2">50</output>
  </div>

</div>
<div id="result"></div>

But ... you meant to create an image from some number, ok. This snippet may help. It uses an image sprite for the numbers.

const createNumber = nr => {
  const numbers = `zero,one,two,three,four,five,six,seven,eight,nine`
    .split(`,`);
  return [...`${nr}`]
    .map(n => `<div class="number ${numbers[n]}"></div>`)
    .join(``);
}

const example = nr => document.body.insertAdjacentHTML(
  `beforeend`,
  `<div class="example">${nr} => ${createNumber(nr)}</p>`);

example(1234567890);
example(233);
example(732);
example(1854);
example(42);
.example {
  height: 32px;
}

.example .number {
  vertical-align: middle;
}

.number {
  background-image: url('//sdn.nicon.nl/tests/numbers.png');
  background-repeat: no-repeat;
  width: 14px;
  height: 16px;
  display: inline-block;
  border: 1px solid #aaa;
  padding: 1px;
  margin: 0 1px
}

.number.zero {
  background-position: 3px 1px;
}

.number.one {
  background-position: -25px 1px;
}

.number.two {
  background-position: -51px 1px
}

.number.three {
  background-position: -77px 1px
}

.number.four {
  background-position: -103px 1px
}

.number.five {
  background-position: -129px 1px
}

.number.six {
  background-position: -155px 1px
}

.number.seven {
  background-position: -183px 1px
}

.number.eight {
  background-position: -209px 1px
}

.number.nine {
  background-position: -235px 1px
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • If I might suggest this simpler solution to the one above: https://jsfiddle.net/3zL45omq/ – Roko C. Buljan Feb 14 '22 at 12:54
  • Ofcourse you may, but it seems a bit less precise. The snippet is just an example, there are more ways to do this. – KooiInc Feb 14 '22 at 13:54
  • I agree with you. Your example is less precise and bug prone. All it takes is to miss a hardcoded value. Not to say that if the image changes (since the one provided is also misaligned) - good luck recalculating all the values. Another suggestion would be to use SVG . And yes, there's many ways to do *something*. – Roko C. Buljan Feb 14 '22 at 14:11
  • Thanks everyone, i was able to add an image, not from the help here but by own myself, i didn't get any straight answers except for advises without showing me a basic example, anyways no heart feelings. Again thanks to all here! –  Feb 15 '22 at 01:43
  • @RokoC.Buljan Here is an [svg variant](https://stackblitz.com/edit/web-platform-plvfcr?file=script.js) – KooiInc Feb 15 '22 at 13:45
  • @ArchieValderrosa You're confusing me. What straighter, simpler example you expected to see? This answer and some comments are straight to the point of your **question title**. Your code (provided in your Q) does nothing about what you asked. Anyways - glad you made it on your own. Would be nice you shared with the community from which you asked for help - your *better* solution; instead of just saying: *"I did it without your help, guys"*. – Roko C. Buljan Feb 15 '22 at 15:47
  • @ArchieValderrosa can you shear or update your question with a solution? – Tlotli Otlotleng Feb 16 '22 at 11:58