I´m having some trouble setting the initial value of my Jquery UI Slider. The main problem (I think) is that the initial value I'm setting is being generated AFTER the slider is created (the initial value is coming from a Jquery.ajax).
Here is what I have:
<script type="text/javascript">
$(window).load(function(){
function ReadVars() {
$.ajax({
//Post to fetch values from computer B
url: "somefile.php",
type: "post",
datatype: "html",
data: {
foo: "foo",
bar: "bar",
},
success: function(response){
//Computer B responds with several values separated by
// a comma e.g. "0,23,1,hello,etc"
var responseSplitted = response.split( "," );
//The second value from the response (in this case 23)
//should be the initial value of the slider
var SliderStart = responseSplitted[1];
console.log("Slider start = ", SliderStart);
},
});
}
var Init = false;
if( !Init ) {
console.log( "Init" );
Init = true;
ReadVars();
}
setInterval( ReadVars, 10000 ); //Update respond every 10 seconds
$("#slider1").slider({
value: SliderStart, //SliderStart should be 23.. but is not working
//because SliderStart does not exist at the moment this part is run
min: 0,
max: 60,
slide: function (event, ui) {
$("#slider1Value").val(ui.value + " kg");
},
stop: function(){
var value = $(this).slider( "option", "value" );
console.log( "value = ", value );
}
});
$( "#slider1Value" ).val( $( "#slider1" ).slider( "value" ));
});
</script>
<body>
<input id="slider1Value" type="text">
<div id="slider1" style="width:300px;"></div>
<input type="text" id="slider1Value" />
</body>
If I include the following two lines under the "success: function(response){}", then it works.
$( "#slider1" ).slider( "option", "value", SliderStart );
$( "#slider1Value" ).val( $( "#slider1" ).slider( "value" ) + " kg" );
However, I just want to set the initial value once and not every 10 seconds. Is there anyway of doing this?
If you move all the code that creates your slider to the success function of your Ajax call, then the slider will be created as soon as your initial value is available.
Related
For some reason my variable keeps resetting to 2 despite me wanting to increment the variable when a function is called. It's really annoying me and I've refactored the code several times to no avail! It should be simple...
Here is my code:
( function( $ ) {
$( document ).ready( function () {
var count = 2;
var total = <?php echo $loop->max_num_pages; ?>;
if ( count <= total ) {
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + count + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
}
});
count++;
}
});
} else {
return;
}
});
})( jQuery );
EDIT: Thanks for your responses so far! Updated code below:
<script type="text/javascript">
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
jQuery( window ).scroll( function() {
if ( jQuery( window ).scrollTop() == jQuery( document ).height() - jQuery( window ).height() ){
console.log( 'Old value: ' + pageCount );
if ( pageCount > total ){
return false;
} else {
loadArticle( pageCount );
}
pageCount++;
console.log( 'New value: ' + pageCount );
}
});
function loadArticle( pageNumber ) {
jQuery.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=forums',
success: function( html ){
jQuery( "#content" ).append( html );
}
});
return false;
}
</script>
New value is always 3 and old value is always 2 (output in console) so it's still being reset...
SOLVED: The html callback in the ajax method was causing the issue. Moving the increment into there worked! New code:
( function( $ ) {
pageCount = 2;
total = <?php echo $loop->max_num_pages; ?>;
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ){
if ( pageCount > total ){
return false;
} else {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + pageCount + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
pageCount++;
}
});
}
}
});
})( jQuery );
two things first:
var can be shortened as such:
var var1 = 'string',
var2 = 'int';
Don't mix php inside JS - it's messy. Create a hidden span and assign data tags to it and call like that
secondarily, that's because the value gets reset whenever you call the function. Place outside, or pass a parameter called count so you can make it more generic and use it throughout your project.
Define count variable outside the function.
e.g.
var count = 2;
( function( $ ) {
$( document ).ready( function () {
var total = <?php echo $loop->max_num_pages; ?>;
if ( count <= total ) {
$( window ).scroll( function() {
if ( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
$.ajax({
url: "<?php bloginfo( 'wpurl' ) ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no=" + count + '&loop_file=forums',
success: function( html ){
$( "#content" ).append( html );
}
});
count++;
}
});
} else {
return;
}
});
})( jQuery );
Your problem here is that the var count is local to your method. This means that it is only alive in that method call. Next time you call your function again, it will create a different count with the value 2 since that is the value you specify on your declaration. Move the variable declaration outside the method and everything should be fine.
I am trying to create an auto-complete drop-down field in a form. This works perfectly on Chrome, but when I try it in Internet Explorer it takes long to load and crashes. I tried this code with a smaller XML file and it worked. Do you have any recommendations of how to make it load easier? or have you seen this happen before with big XML files in Internet Explorer? This file has around 70,000 rows with each row 4 child rows.
$jQ(function() {
$jQ.ajax({
url: "url",
dataType: "xml",
success: function( xmlResponse ) {
var data = $jQ( "row", xmlResponse ).map(function() {
var state = $jQ( "STATE", this ).text() ? ($jQ.trim( $jQ( "STATE", this ).text() ) + " - ") : "";
var ceeb = $jQ( "ATP_CD", this ).text() ? ($jQ.trim( $jQ( "ATP_CD", this ).text() )) : "";
return {
value: $jQ( "DESCR", this ).text() + " - " + state + $jQ( "COUNTRY", this ).text(),
ceeb: ceeb
};
}).get();
$jQ( "#School_Name_Form_Lookup" ).autocomplete({
source: data,
minLength: 3,
select: function(e, ui) {
$jQ("#School_Name_Form_Lookup").attr("DESCR","").val(ui.item.value);
$jQ("#CEEB_Code_RFI__c").val(ui.item.ceeb);
}
});
}
});
});
I'm trying to build an application that takes a text from a website (for the app I'm using gutenburg.org's open ebook catalog) and displays the story in bites of 10 indexes at a time in a div to make the story easier to read for those with ADD. I have a working increment function but I'm stuck as to how to increment back to the previous chunk.
HTML:
<input type="text" id="url" style="width: 400px">
<input type="button" id="btn" value="Get JSON">
<button id="button">Next</button>
<button id="prev">Previous</button>
<div id="test"></div>
Javscript:
$(function() {
$( '#service' ).on( 'change', function(){
$( '#url' ).val( $( this ).val() );
});
//angular.module('exampleApp')
$( '#url' ).val( $( '#service' ).val() );
$( '#btn' ).click(function(){
var url = $( '#url' ).val()
$.ajax({
crossOrigin: true,
proxy: "http://localhost:8888/whorl/proxy.php",
url: url,
//dataType: "json", //no need. if you use crossOrigin, the dataType will be override with "json"
//charset: 'ISO-8859-1', //use it to define the charset of the target url
context: {},
success: function(data) {
//alert(data);
var body = data;
console.log(body.length);
//body/data is a string
var text = body.split(' ')
console.log(text.length);
var increment = function(array) {
if (array.chunk < array.length) {
var chunk = array.slice(array.chunk,Math.min(array.chunk+array.chunkSize, array.length).join(" ");
array.chunk += array.chunkSize;
$( '#test' ).html(chunk);
console.log(chunk);
}
};
$(document).ready(function(){
$("button").click(function() {
increment(text);
});
});
}
})
.done(function( data, textStatus, jqXHR ) {
//alert(data);
});
});
});
pass an attribute, value would be either INCREMENT or DECREMENT
if (value=='increment')
array.chunk += array.chunkSize;
else
array.chunk -= array.chunkSize;
I am trying to setup a jquery autocomplete input based on the user's input in a previous field.
I have a php script that returns a json variable to this jquery post function. however I can't seem to set up my array correctly after.
I have tried just setting a variable to the data and processing the array outside of the $.post function, but still no luck.
I am just unsure how and why the sub-value of my array is alerted correctly when the "parent" value as such is shown as null?
function populateMetrics(light_id){
var availableMetrics = [];
$.post(
"getLightMetrics.php",
{
light_id: light_id,
},
function(data) {
$.each(data, function(index, item){
alert(index); //correct index
availableMetrics[index] = [];
availableMetrics[index]['value'] = item.benchmark_id;
alert(availableMetrics[index]['value']); //correct value
alert(availableMetrics[index]); //null?
availableMetrics[index]['label'] = item.benchmark_variant + "-" + item.benchmark_metric;
alert(availableMetrics[index]['label']); //correct
alert(item.benchmark_id + " = " + item.benchmark_variant + "-" + item.benchmark_metric);
alert(availableMetrics[index]); //still null
});
alert(availableMetrics); //all null, but correct amount
$( "#metric" ).autocomplete({
source: availableMetrics,
focus: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#metric" ).val( ui.item.label );
$( "#metric_id" ).val( ui.item.value );
return false;
}
});
},
"json"
);
}
Multi-dimensional arrays in JavaScript can only have integer-based indexes. They don't work like Associate Arrays do in PHP.
The code you're looking for is probably
var availableMetrics = [];
$.each(data, function(index, item) {
availableMetrics[index] = {
value: item.benchmark_id,
label: item.benchmark_variant + "-" + item.benchmark_metric
};
});
This will create an array of objects that have value and label properties. You would then be able to retrieve the values from your array using either of these notations:
availableMetrics[index]['value'];
availableMetrics[index].value;
I used the example from jQuery mobile site Autocomplete source code
It's working fine, but when I tried to give alert in the script inside the listviewbeforefilter event, it's showing the alert 3 times, so when 3 characters are entered, it will prompt around 7-9 times.
Why is it showing so many alerts? I thinks it should prompt only once when the character is inserted.
Here is the code retrun in script for autocomplete:
$( document ).on( "pageinit", "#myPage", function() {
alert("abc");
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
alert("789");
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
alert("123");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
Here is the code return in the body tag:
<div data-role="content">
<h3>Cities worldwide</h3>
<p>After you enter <strong>at least three characters</strong> the autocomplete `function will show all possible matches.</p>
<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" `data-filter-placeholder="Find a city..." data-filter-theme="a">
</ul>
</div>