简体   繁体   中英

Adding new slider fields on click?

I've basically grabbed most of this code from here http://jqueryui.com/slider/#steps and I'm wondering how I'll be able to add a new slider when ever I hit the "Add" button.

<script>

$(function () {
$( "#slider" ).slider({
  value:100,
  min: 0,
  max: 500,
  step: 50,
  slide: function( event, ui ) {
    $( "#amount" ).val( "$" + ui.value );
  }
});
    $( "#amount" ).val( "$" + $( "#slider" ).slider( "value" ) );
});

$(document).on('click', '.addNew', function() {
    var newSlider = $('#slider').html();
    $('#slider').append(newSlider);
});

</script>

<p>
  <button class="addNew">Add</button>   
  <label for="amount">Donation amount ($50 increments):</label>
  <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>

<div id="slider"></div>

If anyone can help then great, thanks.

It's not clear what you want to do with the new sliders, but there are a few issues with your code. First you're adding a second slider div inside the first one (rather than underneath), second you're adding it with the same id as the first slider -- you almost certainly want to have different ids. Finally you need to initialize slider on the new element.

So, something like this (replaces your $(document).on(...) { ... } ).

// Global variable to count make the ids different (could embed this on some object)
slider_count = 1; 

$(document).on('click', '.addNew', function() {
    // Work out the id for the new slider
    var new_slider_id = 'slider'+slider_count;
    // Attach it to the end of the body -- you might want a 'container' DIV here
    $('body').append("<div id='"+new_slider_id+"'></div>");
    // Initialize the new slider
    $( "#"+new_slider_id ).slider();
    // Update our unique id count
    slider_count = slider_count + 1;
});

You're also going to need to do something to handle the values -- either add them together, or have separate totals. You could either give all the slider DIVs a class then use each to go through the values. Or since you have access to the slider_count variable you can work out the number of sliders and their ids.

Hope that helps.

EDIT: Added the following based on what I think you want to do, I'll try and explain what's going on.

First, make life easy by not embedding the first slider in the HTML, just put a block there with will hold sliders later:

<p>
  <button class="addNew">Add</button>   
  <label for="amount">Donation amount ($50 increments):</label>
  <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<div id="container">

Now you need a way to create sliders, it makes sense to make this a function since it's called in response to more than one event (page load and button click).

function createSlider() {

    // Work out the id for the new slider
    var new_slider_id = 'slider'+createSlider.counter;

    // Create a slider with that id and a common slider class in the container
    $('#container').append("<div class='amount_slider' id='"+new_slider_id+"'></div>");

    // Initialize the new slider 
    $( "#"+new_slider_id ).slider({
      value:100,
      min: 0,
      max: 500,
      step: 50,
      change: function() { 
          updateAmount();
      }
    });

    // Update the amount now to take account of the new default value
    updateAmount();

    // Update our unique id count
    createSlider.counter = createSlider.counter + 1;
}

When this is called it creates a new slider in the DIV container and initializes it with the same options you used. It uses a counter to give each slider a different ID (starting from zero). The counter is stored as a variable on the function (which you can do in JavaScript) when makes it effectively static. Global variables would also work but this at least shows that the counter is only used by that function.

The function calls updateAmount() , both when the slider is changed and right after creating the slider. The second call is necessary as we start a slider on $100 so that needs added to the amount when the slider is created. The update event happens after a change , you used slide which fires on any movement and so the reflected amount was often wrong. Change will also work if something else alters the underlying value -- ie another script.

The updateAmount() function uses the fact that we gave all our sliders the same class so we can use jQuery's class matching and each function to go through them all, like this:

function updateAmount() { 
    var new_amount = 0;
    $('.amount_slider').each(function() {
        new_amount = new_amount += $(this).slider('value');
    });
    $( "#amount" ).val( "$" + new_amount );
}

As I said before, since you know the current value of counter you can also work out the list of slider ids by hand and use that.

Finally put it all together by creating the first slider on page load (remember to zero the counter, which isn't strictly necessary in JavaScript but is good practice in general) and attaching the create action to the add button:

// Create the first slider
$(document).ready(function() {
    createSlider.counter = 0;
    createSlider();
});

// Attach the createSlider() action to the 'add' button
$(document).on('click', '.addNew', function() {
    createSlider();
});

And that's it -- if that's not what you want to do hopefully you can see how the logic works and alter it to make it work as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM