Unusual Behavior of JavaScript When Interacting with Bootstrap Sliders

I sought guidance from a web guru to enhance my code for creating a bootstrap slider per list item within a JavaScript for loop. However, the behavior of the slider has become inconsistent.

At times it functions perfectly, while on other occasions it generates new items that are not sliders (just text input fields), and sometimes it only produces one item per list.

https://i.sstatic.net/6BSdP.png

Can any brilliant minds spot where I may have made a mistake?

var proArray = [];
function addPro() {
    var val = document.getElementById("proInput").value.trim();
    document.getElementById("proForm").reset();
    if (val.length == 0) {
        return;
    }
    if (document.getElementById('proInput' + val) == null) {
        proArray.push({id: val, slider: null});
    } else {
        return;
    }
    for (var i = 0; i < proArray.length; i++) {
        var ele = document.getElementById('proInput' + proArray[i].id);
        if (ele == null) {
            var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput'" +
                    proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
                    + "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
            document.getElementById("proList").innerHTML += newItem;
            proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
                formatter: function(value) {
                    return 'Current value: ' + value;
                }
            });
        } else {
            (function(i) {
                setTimeout(function() {
                    var val = proArray[i].slider.getValue();
                    proArray[i].slider.destroy();
                    document.getElementById('SIDproInput' + proArray[i].id).remove();
                    proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
                        formatter: function (value) {
                            return 'Current value: ' + value;
                        }
                    });
                    proArray[i].slider.setValue(val);
                }, 100);
            })(i);
        }
    }
}

var conArray = [];
function addCon() {
    var valCon = document.getElementById("conInput").value.trim();
    document.getElementById("conForm").reset();
    if (valCon.length == 0) {
        return;
    }
    if (document.getElementById('conInput' + valCon) == null) {
        conArray.push({id: valCon, slider: null});
    } else {
        return;
    }
    for (var i = 0; i < conArray.length; i++) {
        var ele = document.getElementById('conInput' + conArray[i].id);
        if (ele == null) {
            var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
                    conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
                    + "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
            document.getElementById("conList").innerHTML += newItem;
            conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
                formatter: function(value) {
                    return 'Current value: ' + value;
                }
            });
        } else {
            (function(i) {
                setTimeout(function() {
                    var valCon = conArray[i].slider.getValue();
                    conArray[i].slider.destroy();
                    document.getElementById('SIDconInput' + conArray[i].id).remove();
                    conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
                        formatter: function (value) {
                            return 'Current value: ' + value;
                        }
                    });
                    conArray[i].slider.setValue(valCon);
                }, 100);
            })(i);
        }
    }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>

<div class="col-sm-6">
    <h2>Pros</h2>
    <p>The Good Stuff</p>
    <form id="proForm" onkeypress="return event.keyCode != 13;">
    <input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
    <div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
    </div> <!-- pros -->

    <div class="col-sm-6">
    <h2>Cons</h2>
    <p>The Bad Stuff</p>
    <form id="conForm" onkeypress="return event.keyCode != 13;">
    <input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
    <div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
    </div> <!-- cons -->

Answer №1

With the presence of two lists, you have the option to utilize two arrays:

  • var proArray = [];
  • var conArray = [];

To make things more efficient, consider adjusting the inline functions to accept the list prefix as a parameter:

  • newAdd('pro')
  • newAdd('con')

This adjustment allows for customization in the addPro function.

In reference to a comment made:

If "@" or "?" are used as items in the code snippet above, an error may occur. Have you experienced this?

To address this issue, it is recommended to escape these characters when setting up the slider:

arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
         arr[i].id.replace(/@/g, '\\@').replace(/\?/g, '\\?').....

The provided snippet showcases the functionality:

var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
    var val = document.getElementById(listIdPrefix + "Input").value.trim();
    document.getElementById(listIdPrefix + "Form").reset();
    if (val.length == 0) {
        return;
    }
    var arr;
    if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
        if (listIdPrefix == 'pro') {
            proArray.push({id: val, slider: null});
            arr = proArray;
        } else {
            conArray.push({id: val, slider: null});
            arr = conArray;
        }
    } else {
        return;
    }
    for (var i = 0; i < arr.length; i++) {
        var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
        if (ele == null) {
            var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
                    arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
                    + "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
            document.getElementById(listIdPrefix + "List").innerHTML += newItem;
            arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/@/g, '\\@').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
                formatter: function (value) {
                    return 'Current value: ' + value;
                }
            });
        } else {
            (function (i, arr) {
                setTimeout(function () {
                    var val = arr[i].slider.getValue();
                    arr[i].slider.destroy();
                    document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
                    arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/@/g, '\\@').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
                        formatter: function (value) {
                            return 'Current value: ' + value;
                        }
                    });
                    arr[i].slider.setValue(val);
                }, 100);
            })(i, arr);
        }
    }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>


<div class="col-sm-6">
    <h2>Pros</h2>
    <p>The Good Stuff</p>
    <form id="proForm" onkeypress="return event.keyCode != 13;">
        <input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
        <div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
    </form>
    <h3 class="text-left">Benefits</h3>
    <ul class="text-left" id="proList">
    </ul>
</div> <!-- pros -->

<div class="col-sm-6">
    <h2>Cons</h2>
    <p>The Bad Stuff</p>
    <form id="conForm" onkeypress="return event.keyCode != 13;">
        <input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
        <div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
    </form>
    <h3 class="text-left">Costs</h3>
    <ul class="text-left" id="conList">
    </ul>
</div>

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

Assigning multiple properties to objects in Javascript

Can you show me a quicker way to do this? object.position.x = position.x object.position.y = position.y object.position.z = position.z object.rotation.x = rotation.x object.rotation.y = rotation.y object.rotation.z = rotation.z Your assistance is greatly ...

Populate any void area when <td> is not occupied in <tr>

I have a table with two rows and columns. If one of the columns is empty, it should move up to the upper row. For example: |td1 | td2| |td3 | | |td5 | td6| This is what I want: |td1 | td2| |td3 | td5| |td6 | | Below is the code snippet that ...

Vue CLI Plugin Electron Builder displays a completely empty screen after compiling

After building my electron app using this specific plugin, I encountered a frustrating issue where the installed package would only display a blank, white screen. Despite setting up the window to open dev tools in the built version, inspecting the page rev ...

Tips on positioning a button "above" the carousel-control-next icon

I have a carousel and I added a button to stop the spinning. However, when I try to click on the button, it seems like the "carousel-control-next" tag is being clicked instead. How can I solve this issue? ** Interestingly, when I remove the "carousel-cont ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

Rails assets folder is not directed to the specified directory in the layout file

I have a dilemma in the application layout where I'm referencing assets (js, css, and img) in the public/assets/... directory. For example: <link href='assets/images/meta_icons/apple-touch-icon-144x144.png' rel='apple-touch-icon-pre ...

Is there a way to upload several documents in just one writing?

Can anyone advise me on how to add multiple documents to my Firestore collection using just one write operation? I have over 20,000 records and I'm looking for a cost-effective solution. Is there a way to add multiple docs in a single write? Apprecia ...

Implementing percentage subtraction with jQuery: A guide

In my list of prices, I have £100 as the only item: <ol> <li><ins>£100</ins></li> </ol> var total = 0; var getPrice = parseInt($("ol li ins").data("val"), 10); var discount = -(total * getPrice/100); $('ol ...

What is the best way to save the content of an RFC822 message body as a String?

let inbox = require("inbox"); let client = inbox.createConnection(false, "imap.gmail.com", { secureConnection: true, auth:{ user: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f4e0fcf4f8f0f5d9fef4f8f0f5b7fa ...

Utilizing JavaScript/AJAX JSON encoding for arrays: Tips for effectively utilizing the received data

I am trying to retrieve all the images from a specific folder on the server using an AJAX call. files = glob('assets/img/daily/*'); // obtain all file names $imageArr; foreach ($files as $file) { $imageArr[] = $file; } $jsonObj = json_encode ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

After a PHP script is executed, a Bootstrap modal will automatically appear on the same page

Seeking assistance with integrating a bootstrap modal into a contact form submission. Despite multiple attempts, I have been unsuccessful in achieving this integration and now find myself at an impasse. My objective is simple: Upon clicking the submit bu ...

How can we redirect using an OnClick event handler in React.js?

I've been doing a lot of reading and trying to understand how to redirect using withRouter in React. However, I came across some information stating that when onClick occurs, the page should be redirected to a specific link. Additionally, I learned th ...

What could be the reason for the Unknown term error I am now encountering in Nuxt?

Today, I encountered an issue with my Nuxt project that was previously running smoothly. The problem seems to be related to Vue Flickity, which includes a CSS file from the node_modules directory. This setup has been functioning correctly until now. Upon ...

Are you looking for routes that lead to the edit page?

Is it possible to target routes that end with 'edit' using express.js? For example, I have the following normal routes: app.get('/one', controller.one); app.get('/two', controller.two); I want to know if it's possible ...

I am experiencing issues with my Vue.js application when trying to send an HTTP POST request

I am encountering an issue in my Vuejs application while trying to send an HTTP POST request to my server. The error message that keeps popping up in the console is: TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.post is not a function at Object ...

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

How to access a value from a for-loop in JavaScript beyond its scope

Hello there! Within nested json-files, I have been utilizing the following function for iteration: function organizePeopleGroups(People, container, parentObject) { _.each(People, function (item, index) { var peopleGuid =[]; for (var p ...

Adapt to screen size changes by transforming a single row into two separate rows

I am trying to create a two-column row with inputs: <div class="row first-row"> <div class="column col-6"> <div class="form-group"> <label for="usr" >Se ...