jquery 0 - 10 slider for form question
trying to create a simple slider for an input.
Using a survey gem that adds extra fields. I added a class called "jSlider" to the question and does display the slider, but does not update the input.
html form generated:
<fieldset class="q_default jSlider" id="q_353" name="17) On a scale of 0 to 10, ...">
<legend><span>17) On a scale of 0 to 10, ...</span></legend>
<ol><span class='help'></span>
<input id="r_18_question_id" name="r[18][question_id]" type="hidden" value="353" />
<input class="" id="r_18_answer_id" name="r[18][answer_id]" type="hidden" value="3840" />
<li class="string optional" id="r_18_string_value_input"><input id="r_18_string_value" maxlength="255" name="r[18][string_value]" type="text" /></li>
</ol>
</fieldset>
My js is:
$(".jSlider").each(function(){
var newSlider = '<div style="margin-top:20px;margin-bottom:20px;" id="slider">0</div><br />';
$(this).append(newSlider);
$("#slider", this).slider({
value:0,
min: 0,
max: 10,
step: 1,
slide: function( event, ui ) {
alert(ui.value);
// when append, it adds to the fieldset
// first parent is the fieldset, next should be the ol, then the li
// finally arriving at the inpu开发者_如何学编程t field
$(this).parent().next("ol").next("li").next("input:text").val(ui.value);
}
});
});
EDIT
Proposed edit to fix duplicate id breaks again.
$(".jSlider").each(function(){
var id = $(this).attr("id");
var sliderID = id + "_slider";
alert(sliderID);
var newSlider = '<div id="' + sliderID + '"></div><br />';
$(this).append(newSlider);
// or even
// $(sliderID).slider({
$(sliderID, this).slider({
value:0,
min: 0,
max: 10,
step: 1,
change: function( event, ui ) {
// alert(ui.value);
// when append, it adds to the fieldset
// first parent is the fieldset, next should be the ol, then the li
// finally arriving at the input field
$(this).closest('fieldset').find('input:text').val(ui.value);
}
});
});
You could do (you should use the stop event or the change event):
stop: function( event, ui ) {
alert(ui.value);
// when append, it adds to the fieldset
// first parent is the fieldset, next should be the ol, then the li
// finally arriving at the input field
$(this).closest('fieldset').find('input:text').val(ui.value);
}
To update a field:
$('input#myfield').val($('#slider').slider("option", "value"));
The script generates duplicate IDs (new ID #slider in every loop). Using $(this) will prevent from misbehaving scripts:
$('.jSlider').each(function(){
$(this).slider({..});
};
EDIT 28.7.: using var $newSlider which extends var newSlider so function $.slider() may be used:
$(".jSlider").each(function(){
var $newSlider = $('<div id="' + $(this).attr("id") + '">');
$(this).append($newSlider);
$newSlider.slider(options);});
$.append() accepts a definition for an HTML element, no closing tags are required.
精彩评论