"Refreshing the page will still show the jQuery slider's current input value even after

I've come across a unique slider that combines 4 sliders, each sharing 100% value. The issue is that it doesn't take the input values into account and resets to 25% for each slider whenever the page is refreshed. Can someone assist in making the slider consider the input values before determining the position of the slider knob?

HTML

<div align="center" class="title">Statistiche:</div>
<div id="outer_container">
<div id="container">
<span class='multislider'>Hokuto ShinKen (<input type='text' required name='question_3' class='amount' value='5' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Nanto (<input type='text' required name='question_3' class='amount' value='15' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Gento (<input type='text' required name='question_3' class='amount' value='50' data-min='0' data-max='100'/>)
<div class='slider tied'>
</div>
Artiglio del Monte Taishan (<input type='text' required name='question_3' class='amount' value='30' data-min='0' data-max='100'/>)
<div class='slider tied'></div>
</span>
</div>
</div>

jQuery

    var init = true;
    var elements = $(".multislider").children(".slider.tied").length;
    var MAX = 100;
  var inpVal = $('.txt_name').val();
  var initValue = (inpVal) >> 0;
    //var initValue = (MAX / elements) >> 0;
    var InitMod = MAX % elements;

    $(".slider.tied").each(function() {
        var slidersTied = $(".slider.tied");
        var context = $(this);

        var input = context.prev(".amount");
        var val = input.data('answer');
        var min = input.data('min');
        var max = input.data('max');
        var range = 1;
        var proceed = false;

        $(this).empty().slider({
            value: val,
            min: min,
            max: max,
            range: range,
            animate: "slow",
            create: function(event, ui){

                if (InitMod > 0) {
                    $(this).slider('value', initValue + 1);
                    $(this).prev('.amount').val(initValue + 1);
                    InitMod = InitMod - 1;
                }
                else
                {
                    $(this).slider('value', initValue);
                    $(this).prev('.amount').val(initValue);
                }

            },
            slide: function(e, ui) {

                // Update display to current value
                $(this).prev('.amount').val(ui.value);

                var current = ($(this).index() / 2) >> 0;
                var total = 0;
                var counter = 0

                slidersTied.not(this).each(function() {

                    total += $(this).slider("option", "value");                
                    counter += 1;
                });

                total += ui.value;

                if (total != MAX){
                    proceed = true;
                }

                var missing = MAX - total;
                console.log("missing: " + missing);

                counter = 0;

                if(proceed) {

                    //carico vettore elementi
                    var elements = [];

                    slidersTied.each(function() {
                        elements[counter] = $(this);
                        counter += 1;
                    });

                    var endIndex = counter - 1;
                    counter = endIndex + 1;

                    while (missing != 0) {

                        console.log("current counter: " + counter);
                        do {
                            if (counter == 0) 
                            {
                                counter = endIndex;
                            }
                            else
                            {
                                counter = counter - 1;
                            }
                        } while(counter == current)

                        console.log("elemento attuale: " + counter);

                        var value = elements[counter].slider("option", "value");
                        var result = value + missing;

                        if (result >= 0) 
                        {
                            elements[counter].slider('value', result);
                            elements[counter].prev('.amount').val(result);

                            missing = 0;    
                        }
                        else
                        {
                            missing = result;
                            elements[counter].slider('value', 0);
                            elements[counter].prev('.amount').val(0);
                        }

                    }

                }

            }
        });
    });

Example http://jsfiddle.net/vuQz5/116/

Thanks

Answer №1

Two important issues to address here. Firstly, the code snippet var val = input.data('answer'); is incorrect as there isn't a data value called 'answer'. Instead, you should retrieve the input value like this:


var val = input.val();
val = (val) ? val : 0;

Secondly, make sure to utilize this value in the create method rather than using initValue. The conditional check with the if statement is unnecessary - only implement what's in the else block:


$(this).slider('value', val);
$(this).prev('.amount').val(val);

For a demonstration, refer to this example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Left-align the text above the div (in relation to it)

My current issue involves aligning h2 text to the left relative to a centered div in the mobile view. How can I achieve this alignment with a media query in the provided CSS? https://i.sstatic.net/sIJb4.jpg CodePen Here is the relevant HTML: <sectio ...

Utilizing Phantom Js with Apache server

After creating a JavaScript app, I realized the importance of making it SEO friendly. I am curious if anyone has experience setting up a crawlable webpage on Apache using Backbone.js (potentially with assistance from PHP and .htaccess files, or with Phant ...

Trouble aligning content in CSS? Try using justify-content center for perfect centering!

I am facing an issue with centralizing the content properly. Despite using justify-content:center, the layout breaks. https://i.sstatic.net/EMiw1.png When I apply justify-content:center, the layout appears like this: https://i.sstatic.net/lTJRi.png Her ...

The dropdownlist in asp.net does not trigger the selectedindexchanged event after changing its selected value using Jquery

I am facing an issue with two dropdown lists on my website. I have implemented a jQuery code that resets the second dropdown to its default option (selected index 0) whenever the first dropdown is changed. $("select[id*='ddlWayType']").bind( ...

Make sure to exclude any line breaks when making a request to the server using Ajax Post and JQuery

Currently, I am attempting to utilize Ajax in conjunction with JQuery. My objective is to send the value from a multiline textbox to PHP using Ajax. The code snippet I am currently utilizing sends the txtAnswer value to PHP. Unfortunately, it appears that ...

Instructions on how to prompt users to register using a distinctive code

Currently in the process of constructing a website and I'm interested in setting restrictions on the number of users who can sign up for it. https://i.stack.imgur.com/JD2Ct.png In the image provided, there is a database in phpMyAdmin labeled as &apo ...

Setting header details for optimal data transfer

Currently, there is a Java code snippet that I am working on which attempts to access the header information sent by an HTML page. Unfortunately, I do not currently have the specific HTML page in question. However, I still need to be able to access and m ...

jQuery $.ajax problem encountered

When working with AngularJS, we have the ability to catch errors using the $http() service as shown below: return $http(defaultConfig).then(sendResponseData)**.catch(errorCallBack)**; On the other hand, when attempting to do something similar in jQuery: ...

Is it possible to encounter an "Invalid Promise.all usage" error when using Promise.all?

My approach involves returning promises from a promise and utilizing Promise.all in the following manner: updateVideos() .then(videos => { return videos.map(video => updateUrl({ id: video, url: "http://..." })) }) .then(Promise.all) // encounte ...

Retrieving table information using curl and regular expressions

Here is the code I have developed to extract data from a table on a specific website. However, I am looking to remove any links present in the data and also separate the title and price into an array. <?php $ch = curl_init("http://www.digionline.ir/ ...

Equalize the height of columns by making them all float at a uniform 100%

Let's discuss the challenge of having 3 floated columns. Take a look at this example: http://jsfiddle.net/A9dqD/ html, body {height: 100%;} #a { float: left; height: 100%; width: 50%; background-color: green; } #b { float: left; ...

Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API. Index.js file: const express = require('express'); const http = require('http'); const morgan = require('morgan'); const b ...

Utilizing Custom HTTP Headers in Angular 2 to Enhance Request Handling

Within my Angular 2 project, I am implementing the use of Http (@angular/http) to communicate with my API. In order for these requests to be successful, specific headers, including a JWT header, must be included in each API request. My goal is to have an ...

Leveraging the ajax framework for creating a dynamic web application using php and codeigniter framework

Beginning development of a web application using the PHP framework CodeIgniter. The application will primarily interact with the database using AJAX/jQuery. Here is my planned approach for completing a specific task: Create a view page Add event handlers ...

Assigning a class to an element that is neither selected nor focused

I am working on a hover effect for a button that should add a CSS class to a specific element. Despite having multiple elements, I only want the class added to one particular element. Here is my current code: $("ul.subnav").parent().append("<span> ...

Is Angular Routing worth using just for variable changes?

Is there a way to implement routing in an Angular application without relying on secondary controllers or templates? I am looking for a method to use routes as triggers to change variables and display different UI elements dynamically. Can anyone help wi ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

viewing a collection of tuples in an HTML document

My top_5 list consists of tuples containing the usernames and post counts of the top 5 users. This list contains 5 items, each with 2 indexes. {% for user in top_5 %} {{ user }} {% endfor %} While using this code will return the user and their post ...

Customizing Carousel Arrows in Angular with ng-bootstrap

I need help changing the position and icon of control arrows using Bootstrap. I've tried targeting "carousel-control-prev-icon" & "carousel-control-next-icon", but nothing seems to work. Any suggestions on how to properly solve this issue? Here is th ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...