Want to be able to dynamically add new snap to increment slider when I click a button?

366 Views Asked by At

At the moment I am trying to create a form where you can add new fields/sliders based on what you need. The person is able to add their skill name to a textbox and then select on the slider which level they are at with that skill and they can then choose to add another skill if they like.

Then when the user hits the submit button I want to post this data to a php file where I'll be able to handle the rest and insert these details to the database tables which they correspond to.

I have the following code which displays one text box but I'm really in no mans land with jQuery:

<script>

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

$(document).on('click', '.addNew', function() {
$('#container').append(addSlide);
});  

</script>

<div id="container">  

<button class="addNew">Add</button>  

<form><br><input type="text" name="skill" placeholder="What's your skill?">

<p>
  <label for="amount">Skill Level: 1</label>
  <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>

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

</form> 

</div> 

Thanks in advance, hope you can help!!

2

There are 2 best solutions below

0
On

I think what you really want is a method at which you can click and add new sliders into the DOM. You will need to re-bind the slide event each time you create an object. Here's a quick writeup:

$.fn.addSlide = function () {
    return this.each(function () {
        var $this = $(this),
            $num = $('.slide').length++,
            $slide = $('<div class="slide" id="slider-' + $num + '"></div>'),
            $amt = $('<input id="amount-' + $num + '" readonly/>');
        $this.append($slide).append($amt);
        $slide.slider({
            value: 1,
            min: 0,
            max: 5,
            step: 1,
            slide: function (event, ui) {
                $amt.val(": " + ui.value);
            }
        });
    });
}

You simply call it on a container, such as:

$(document).on('click', '.addNew', function() {
    $('#container').addSlide();
}); 

Also, please replace document with a closer static parent selector, even body.

As usual, here's a working jsFiddle

0
On

This is how you would add a new input box to a form.

$(".addNew").click(function(){
   $("form").append("<input type='text'/>");
 });

You will have to give them different names, and also have another input attached to each, that will carry label to it. You don't need to add a new slider everytime just move current one to the end.

DEMO JSFIDDLE