I am trying to get the slider values to stay where they were moved to when the SEARCH button is pressed. They default back to the starting values whenever the search is pressed. I have tried all sorts of things and nothing appears to work. Any help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/jquery-ui.css">
</head>
<body>
<form method="post" id="formMain">
<label>Price Range</label>
<div>
<div id="slider-range" ></div>
<input type="hidden" name="price_l" id="price_l" value="<?php echo
(isset($_REQUEST["price_l"])?$_REQUEST["price_l"]:"50000")?>"/>
<input type="hidden" name="price_h" id="price_h" value="<?php echo
(isset($_REQUEST["price_h"])?$_REQUEST["price_h"]:"400000")?>"/>
<input type="text" name="text" id="amount" disabled="" />
</div>
<div>
<input type="submit" value="Search">
</div>
</form>
<script src="js/jquery-3.5.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
var siteSliderRange = function() {
$( "#slider-range" ).slider({
range: true,
min: 5000,
max: 450000,
step: 5000,
values: [ 50000, 400000 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
// when the slider values change, update the hidden fields
$("#price_l").val(ui.values[ 0 ]);
$("#price_h").val(ui.values[ 1 ]);
}
});
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" - $" + $( "#slider-range" ).slider( "values", 1 ) );
};
siteSliderRange();
</script>
</body>
</html>
Consider the following example that uses localStorage to store the slider values in the browser.
https://jsfiddle.net/Twisty/e28pqhy9/11/
HTML
<fieldset class="ui-widget">
<legend>Price Range</legend>
<div class="content">
<div id="slider-range"></div>
<div id="amount"></div>
<button>Search</button>
</div>
</fieldset>
JavaScript
$(function() {
function getValues(k) {
if (k == undefined) {
return false;
}
var v = localStorage.getItem(k);
if (v != null) {
return JSON.parse(v);
} else {
return -1;
}
}
function setValues(k, v) {
if (k == undefined || v == undefined) {
return false;
}
localStorage.setItem(k, JSON.stringify(v));
}
function showRange(tObj, v) {
tObj.html("$" + v[0] + " - $" + v[1]);
}
function searchRange(q) {
$.post("searchRange.php", {
price_l: q[0],
price_h: q[1]
}, function(response) {
// Do the needful
})
}
function siteSliderRange(tObj) {
tObj.slider({
range: true,
min: 5000,
max: 450000,
step: 5000,
values: [50000, 400000],
slide: function(event, ui) {
showRange($(this).next(), ui.values);
},
stop: function(e, ui) {
setValues($(this).attr("id"), ui.values);
}
});
}
function init() {
var cVal = getValues("slider-range");
if (cVal != -1) {
showRange($("#amount"), cVal);
siteSliderRange($("#slider-range"));
$("#slider-range").slider("values", cVal);
} else {
showRange($("#amount"), [50000, 400000]);
siteSliderRange($("#slider-range"));
setValues("slider-range", [50000, 400000]);
}
$(".content button").click(function() {
searchRange($("#slider-range").slider("values"));
});
}
init();
});
This will check the localStorage upon initialization to see if any values have been stored. If not, 50000 and 400000 are set as defaults. If there is a value, it will be loaded to both the Slider and the display area. Moving away from the Form model will give you added security. Less chance of someone entering their own values by manually enabling the Text field.
When the User moves the Slider, the display is updated. When they stop it then updates the localStorage. This ensure if they refresh the page or navigate back later, the Slider will recall their selection.
When the Search button is clicked, an AJAX Post is performed, this sends the data to PHP and expects some results to be passed back. I assume those results would be appended to the page.
Update
New Example for PHP: https://jsfiddle.net/Twisty/e28pqhy9/20/
If you want to echo the PHP Values, you can do this, you just need to adjust your JS to look for these values.
HTML
<form>
<fieldset class="ui-widget">
<legend>Price Range</legend>
<div class="content">
<div id="slider-range"></div>
<div class="amount-display"></div>
<input type="hidden" id="amount" value="<?php echo $price_l . ',' . $price_h ?>" />
<button type="submit">Search</button>
</div>
</fieldset>
</form>
JavaScript
$(function() {
function getValues() {
return $("#amount").val().split(",");
}
function setValues(v) {
$("#amount").val(v.join(","));
}
function showRange(tObj, v) {
tObj.html("$" + v[0] + " - $" + v[1]);
}
function siteSliderRange(tObj) {
tObj.slider({
range: true,
min: 5000,
max: 450000,
step: 5000,
values: getValues(),
slide: function(event, ui) {
showRange($(this).next(), ui.values);
},
stop: function(e, ui) {
setValues($(this).attr("id"), ui.values);
}
});
}
function init() {
var cVal = getValues();
showRange($(".amount-display"), cVal);
siteSliderRange($("#slider-range"));
}
init();
});
When the form is submitted, the $_POST['amount'] will be a string and you can use this to convert it back:
PHP
$amounts = explode(",", $_POST['amount']);
$price_l = (int)$amounts[0];
$price_h = (int)$amounts[1];
Related
i try to make a multiple dialog form from some data in the database but when i clicked the button, the dialog form not showed
i use PHP increment numeric to differentiate the attribute id
then i use for to sync the id on my php code with the id on jquery code
when i try on jsfiddle, it says "Functions declared between loop referencing an outer scoped variable may lead to confusing semantics"
this is my php code:
<button class="btn btn-danger" id="create-user<?php echo $no2++; ?>">Buka Blokir</button>
<div id="dialog-form<?php echo $no++; ?>" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="reason">Reason</label>
<input type="text" name="reason" id="reason" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
and thisis my jquery code:
$( function() {
var dialog, form,
reason = $( "#reason" ),
allFields = $( [] ).add( reason ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function unBlock() {
var valid = true;
allFields.removeClass( "ui-state-error" );
valid = valid && checkLength( reason, "reason", 6, 80 );
if ( valid ) {
$( "#users tbody" ).append( "<tr>" +
"<td>" + dasar.val() + "</td>" +
"</tr>" );
dialog.dialog( "close" );
}
return valid;
}
for (var i = 1; i < 50; i++) {
dialog = $( "#dialog-form"+i ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Unblock": unBlock,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
}
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});
for (var b = 1; b < 50; b++) {
$( "#create-user"+b ).button().on( "click", function() {
dialog.dialog( "open" );
});
}
} );
I think you're making it overly complicated. Consider the following code.
$(function() {
var reasons = $("[id^='reason']"),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function() {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
$("[id^='dialog-form']").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Unblock": function() {
var valid = true;
reasons.removeClass("ui-state-error");;
var reason = $(this).find("[id^='reason']");
valid = valid && checkLength(reason, "reason", 6, 80);
if (valid) {
/*
$("#users tbody").append("<tr>" +
"<td>" + dasar.val() + "</td>" +
"</tr>");
*/
$("[id^='dialog-form']").dialog("close");
}
return valid;
},
Cancel: function() {
$(this).dialog("close");
}
},
close: function() {
$(this).find("form")[0].reset();
reasons.removeClass("ui-state-error");
}
});
$("div[id^='dialog-form'] form").on("submit", function(e) {
e.preventDefault();
/*
addUser();
*/
});
$("button[id^='create-user']").on("click", function(e) {
var selfId = $(this).attr("id");
var d = selfId.match(/\d+/g).map(Number);
var dlg = $("#dialog-form-" + d);
dlg.dialog("open");
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<button class="btn btn-danger" id="create-user-1">Buka Blokir</button>
<div id="dialog-form-1" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="reason-1">Reason</label>
<input type="text" name="reason" id="reason-1" value="Jane Smith" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<button class="btn btn-danger" id="create-user-20">Buka Blokir</button>
<div id="dialog-form-20" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="reason-20">Reason</label>
<input type="text" name="reason" id="reason-2" value="John Smith" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
With a selector that encompasses more than one element, you can still assign UI Widgets to it. You just have to understand how to use this and $(this) to your advantage.
I have a g:field that when pressing enter or deselect it the page needs to refresh it self because i have a value that is calculated by value in the g:field
<g:field type="text" name="amount" pattern="[1-9]*" maxlength="2" value="${Buyer?.amount}"/>
I tired with, but it does not work for some reason
$("#amount").change(function() {
$("#" + divId).load("/ordering" + "?amount=" + document.getElementById('amount').value)
}
$("#amount").keydown(function (event) {
if (event.keyCode === 13) {
$("#" + divId).load("/ordering" + "?amount=" + document.getElementById('amount').value)
}
}
I simplified your code a little to provide a complete working example, the following works for me with little changes to your original post.
/views/test/index.gsp
<!doctype html>
<html>
<head>
<meta name="layout" content="main"/>
<script>
$(document).ready(function(){
var amt = $( '#amount' );
$( amt ).keydown(function (event) {
if (event.keyCode === 13) {
$( "#myDiv" ).load("/ordering" + "?amount=" + amt.val() )
}
});
$( amt ).change(function() {
$("#myDiv").load("/ordering" + "?amount=" + amt.val() )
});
});
</script>
</head>
<body>
<g:field type="text" name="amount" pattern="[1-9]*" maxlength="2" value="${params.amount}"/>
<div id="myDiv"></div>
</body>
</html>
TestController
def ordering() {
render( "Amount is ${params.amount}" )
}
I am playing around with the jQuery UI slider and found two examples that look very similar to me.
However, the first slider allows for a handle to be dragged to the other side other handle, whereas the in the second slider, the handles seem to be blocking each other (i.e. you cannot drag the left handle to the right side of the right handle and vice versa).
Can somebody explain to me, why this is happening ?
Here is the fiddle: http://jsfiddle.net/w4gy8p1v/1/
Code for slider:
$(document).ready(function() {
$("#slider").slider({
min: 0,
max: 100,
step: 1,
values: [10, 90],
slide: function(event, ui) {
for (var i = 0; i < ui.values.length; ++i) {
$("input.sliderValue[data-index=" + i + "]").val(ui.values[i]);
}
}
});
$("input.sliderValue").change(function() {
var $this = $(this);
$("#slider").slider("values", $this.data("index"), $this.val());
});
});
<form>
<div>
<input type="text" class="sliderValue" data-index="0" value="10" />
<input type="text" class="sliderValue" data-index="1" value="90" />
</div>
<br />
<div id="slider"></div>
</form>
Code for second slider:
$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: 500,
values: [ 75, 300 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
}
});
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" - $" + $( "#slider-range" ).slider( "values", 1 ) );
});
<p>
<label for="amount">Price range:</label>
<input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-range"></div>
The difference comes from the range option (range: true).
When the range option is true, the slider handles can't cross.
I'm using datepicker inside my input , my last field is the datepicker input , after validating it i want to set focus on another input inside my form , but the problem is the datepicker is not closed even taht it does not have the focus..
how can I close the datepicker when i set the focus on another input field?
(I tried .datepicker("hide"); but it did not worked for me).
UPDATE:
this is my code:
$(function()
{ $( "#test_date" ).datepicker({
dateFormat: "dd/mm/yy"
});
});
//when i call my function:
$( "#test_date" ).datepicker("hide"); //---> this does not work!
Thank's In Advance.
Question Edited to work with the latest version of jqueryUI
JqueryUi auto-closes the datepicker when an element loses focus by user interaction, but not when changing focus with JS.
Where you are calling your function which removes focus from the input assigned a datepicker you also need to call:
$("#test_date ~ .ui-datepicker").hide();
This code is hiding the datepicker which is a sibling (~) of #test_date.
To be dynamic, and using the class assigned by jQueryui you can do:
$(".hasDatepicker").on("blur", function(e) { $(this).off("focus").datepicker("hide"); });
;(function() {
function eventOnFocusDP(e, par) {
if (par.ver == $.fn.jquery) {
if (this.tmr) clearTimeout(this.tmr);
par.lbl1.text(par.msgs[1]);
this.tmr = setTimeout(function() { par.inpNP.focus(); }, par.secs*1e3);
}
}
function eventOnFocusNP(e, par) {
if (par.ver == $.fn.jquery) {
par.lbl1.text(par.msgs[0]);
par.lbl2.text(par.msgs[2]);
}
}
function eventOnBlurNP(e, par) {
if (par.ver == $.fn.jquery) par.lbl2.text("");
}
function eventOnBlurHDP(e, par) {
if (par.ver == $.fn.jquery) {
$(this).off("focus").datepicker("hide");
}
}
function test(secs) {
this.ver = $.fn.jquery;
this.secs = (typeof secs)=='number'?secs:2;
this.msgs = [
'This will lose focus to box below '+this.secs+' seconds after it gains focus.',
'Losing focus in '+this.secs+' seconds!',
'Focus now on bottom box.'
];
this.inpDP = $('[name=datePicker]');
this.inpNP = $('[name=nextPicker]');
this.lbl1 = $('#dPMsg').text(this.msgs[0]);
this.lbl2 = $('#dPMsg2');
var par = this;
this.inpDP.datepicker({ dateFormat: "dd/mm/yy" })
.on('focus', function(e) { eventOnFocusDP.apply(this, [e, par]) });
this.inpNP.on('focus', function(e) { eventOnFocusNP.apply(this, [e, par]) });
this.inpNP.on('blur', function(e) { eventOnBlurNP.apply(this, [e, par]) });
$(document).on('blur', '.hasDatepicker', function(e) { eventOnBlurHDP.apply(this, [e, par]) });
return this;
}
function init() {
window.Test = test;
setTimeout(function() {
$(document).on('change', '.switcher, .switcher-ui', function(e) { if (window.Test) new Test(); });
$(jQueryUISwitcher).trigger('change');
}, 1e3);
}
if (document.readyState == "complete") init();
else jQuery(window).on('load', init);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/cfc32292cbbfa548fb9584db05b2b2fc/raw/4f16f7ee441dfb98aa166a2e84193b14574a46d1/jquery.switcher.js"></script>
<form action="javascript: void 0">
<input type="text" name="datePicker" id="dP" placeholder="mm/dd/yyyy" />
<label for="dP" id="dPMsg"></label>
<hr />
<input type="text" name="nextPicker" placeholder="tab to here" />
<label for="dP" id="dPMsg2"></label>
</form>
<hr />
<hr />
<hr />
Here's a modified solution that worked for me:
$(".hasDatepicker").each(function (index, element) {
var context = $(this);
context.on("blur", function (e) {
// The setTimeout is the key here.
setTimeout(function () {
if (!context.is(':focus')) {
$(context).datepicker("hide");
}
}, 250);
});
});
My version of js:
<script type="text/javascript"> $(function () {
$("#dtp1").on("dp.change", function (e) {
$('#dtp1').data("DateTimePicker").hide();
});
});
I hope it's help you
This worked for me:
$("#datepickerTo").datepicker({
onSelect: function () {
$(this).off( "focus" );
}
});
I have written code (below) to be able to drag an input field onto another, but it seems that draggable swallows input[text].onfocus.
This results in the problem, that all draggable input fields act as disabled (firefox) and clicking the mouse does not focus them. I can edit the input field if I focus on them using the TAB key, but I have to traverse all the necessary tab-indexes.
So it seems draggable swallows the input[text].onfocus mouse event.
Is there a way to workaround this during bind-time?
<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready( function()
{
$("#drag-table tr td input").draggable({helper: 'clone', revert: 'invalid', cancel: null, cursor: 'move', addClasses: false, containment: $("#drag-table"), handle: 'h2', opacity: 0.8, scroll: true });
$("#drag-table tr td input").droppable({
addClasses: false,
drop: function(ev, ui) {
alert('value='+ ui.draggable.val() + ", text=" + ui.draggable.text() + " and deeper=" + ui.draggable[0].value);
$(this).insertAtCaret(ui.draggable.val());
ui.draggable.val(null);
$(this).trigger('change');
}
});
});
$.fn.insertAtCaret = function (myValue) {
return this.each(function(){
//IE support
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
//MOZILLA / NETSCAPE support
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
};
</script>
</head>
<body>
<table border="1" cellspacing="10" cellpadding="10" id="drag-table">
<tr>
<td><input type="text" name="1x1y" id="id1x1y" value="text" onfocus="alert('onfocus swallowed?');"/></td>
<td><input type="text" name="2x1y" id="id2x1y" onchange="alert('hello');"/></td>
</tr>
<tr>
<td><input type="text" name="1x2y" id="id1x2y" value="next"/></td>
<td><input type="text" name="2x2y" id="id2x2y"/></td>
</tr>
</table>
</body>
Wrap the element in either a div or span (depending on which would be valid) and apply the draggable event on that instead.