Accessing multiple css property - javascript

Is this method appropriate for accessing multiple css method?
<script>
$("div").click(function () {
var html = ["The clicked div has the following styles:"];
var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
This is what jquery API is doing.Is above method for accessing multiple property appropriate?Or is that the way?
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
$( "#result" ).html( html.join( "<br>" ) );
});

You copied the code from the docs, mentioning it could help, anyway they show you they pulled all the data with:
var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
Now they manipulate the data with:
$.each( styleProps, function( prop, value ) {
html.push( prop + ": " + value );
});
Finally they output the result with a <br> between each name-value pair:
$( "#result" ).html( html.join( "<br>" ) );

Related

How do I add a second variable value to the jQuery widget 'Autocomplete'?

I have been using the jQuery ‘Autocomplete Widget’ for a number of years now. This has always been done but passing a value with ‘term’ to the PHP SQL code like this;
$( "#cs1" ).autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
select: function( event, ui ) {
// This if undes the readonly on the Fname input field below
if ( ui.item.label == 'NONHAM' ) {$('#Fname').prop('readonly', false);}
$( "#cs1" ).val( ui.item.label );
$( "#hints" ).val( ui.item.value );
$( "#Fname" ).val( ui.item.desc );
var nc = $( "#thenetcallsign" ).html();
//return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + " ---> " + item.desc + "</a>" )
.appendTo( ul );
};
});
But now I have to add another condition to the SQL code to return a more detailed value. The value for this additional condition is;
var nc = $( "#thenetcallsign" ).html();
The problem is I don’t know how to add this to ‘term’ or a separate variable and pass it to gethint.php using the ‘Autocomplete’ widget.
Once I get the extra value to the PHP program I know what to do.
Would somebody please explain or show me how to do this?
You might have to stringify it but pass the extraParams
extraParams: { type: "CoolCode" },
var nc = $("#thenetcallsign").html();
$("#cs1").autocomplete({
autoFocus: true,
minLength: 3,
source: "gethint.php",
extraParams: {
nc: nc
},
select: function(event, ui) {
// This if undes the readonly on the Fname input field below
if (ui.item.label == 'NONHAM') {
$('#Fname').prop('readonly', false);
}
$("#cs1").val(ui.item.label);
$("#hints").val(ui.item.value);
$("#Fname").val(ui.item.desc);
var nc = $("#thenetcallsign").html();
//return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + " ---> " + item.desc + "</a>")
.appendTo(ul);
};
});
source could be a function in order to get more flexibility
$( "#cs1" ).autocomplete({
/* ... */
source: function(request, response) {
$.getJSON( "gethint.php", {
term: request.term ,
nc: $( "#thenetcallsign" ).html()
}, response );
},
/* ... */
});

Send JSON Array to MySql database

I need to send array to my mysql database.
I've created a JSON array and dont know how to post it to php to transfer to db.
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
I need to post it item->item, qty->qty, price->price to the db.
I've tried :
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
Data stores whole page, but not (stringified myData). And I still cant get it at php code by $_POST and json_decode
Data stores whole page, but not stringified myData and I can't get it at php code by $_POST and json_decode
php code
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`
Try this one for js
$(function () {
$('#orderForm').on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
data_to_server = JSON.stringify(myData);
});
$.post("*your_php_file*", {
data: data_to_server;
}).done(function (data_returned) {
// any your code
});
});
And seems you have mismatch in PHP code - trying to serialize() instead of json_decode()
Remove nested click event and closure.
e.g.
$( '#orderForm' ).on( 'submit', function ( event ) {
$( '#orderForm' ).on( 'submit', function ( event ) {
} );
} );
Than try again.
And your MySQL insert statement in php
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
is not ok.
Learn more about MySQL insert statement here https://www.w3schools.com/php/php_mysql_insert.asp

How to store Javascript value in php variable shown in alert

How to pass javascript variable to php variable my code is- I want to store alert value in php variable.
<script type="text/javascript" >
$(document).ready( function() {
$( '#container' ).html( '<ul class="filetree start"><li class="wait">' + 'Generating Tree...' + '<li></ul>' );
getfilelist( $('#container') , 'Sample' );
function getfilelist( cont, root ) {
$( cont ).addClass( 'wait' );
$.post( 'Foldertree.php', { dir: root }, function( data ) {
$( cont ).find( '.start' ).html( '' );
$( cont ).removeClass( 'wait' ).append( data );
if( 'Sample' == root )
$( cont ).find('UL:hidden').show();
else
$( cont ).find('UL:hidden').slideDown({ duration: 500, easing: null });
});
}
$( '#container' ).on('click', 'LI A', function() {
var entry = $(this).parent();
if( entry.hasClass('folder') ) {
if( entry.hasClass('collapsed') ) {
entry.find('UL').remove();
getfilelist( entry, escape( $(this).attr('rel') ));
entry.removeClass('collapsed').addClass('expanded');
window.alert($(this).attr('rel'))
$( '#selected_file1' ).text( "Folder: " + $(this).attr( 'rel' ));
<?php
?>
}
else {
entry.find('UL').slideUp({ duration: 500, easing: null });
entry.removeClass('expanded').addClass('collapsed');
}
} else {
$( '#selected_file' ).text( "File: " + $(this).attr( 'rel' ));
}
return false;
});
});
</script>
There is difference between Javascript and PHP, PHP is a server-side script language while Javascript is a client-side script language. See https://www.sqa.org.uk/e-learning/ClientSide01CD/page_18.htm
Use the advantage of AJAX instead for your problem

Jquery remote completion, li's are not selectable

I'm trying to create a text input with text completion using a remote host.
I've been trying to use the example in the following URL: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
this is the javascript code from the example:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
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 ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
so first of all I changed dataType from jsonp to json which makes the ajax call
return a proper json object and the unordered list is filled properly.
the problem that I encounter is that once I see the text completion (the li elements), I can't select any of the elements.
I tried browsing this example on my Galaxy Note 2 and I encountered the same problem, the elements are not selectable.
any ideas how to resolve the issue?
thanks
update
as to #Omar comment i changed the following line:
html += "<li>" + val + "</li>";
to
html += "<li><a href='#'>" + val + "</a></li>";
now i can click on an item but it doesn't do anything. it supposed to close the list and add to the text field the selected item.
You need to delegate an event to generated list items and then update input with the value.
$("#autocomplete").on("click", "li", function () {
/* text of clicked element */
var value = $(this).text();
/* update value of input */
$("#autocomplete-input").val(value);
/* optional - remove autocomplete result(s) */
$(this).parent().empty();
});
Demo

Removing duplicates from autocomplete results Json

I have an issue where I have added two feature classes and it means that I sometimes get results which are duplicated in the autosuggest. I wondered if there is a way I can some how check for duplicates and fetch an alternative instead of showing the same result twice.
This is my code here (working): http://jsfiddle.net/spadez/nHgMX/4/
$(function() {
jQuery.ajaxSettings.traditional = true;
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: ["A","P"],
style: "full",
maxRows: 7,
name_startsWith: request.term,
country: "UK"
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
Any help or information would be much appreciated
Hard to tell exactly what you're asking. But to remove duplicates from an array of objects, you can use underscore's _.uniq()
$.map( _.uniq(data.geonames, false, function(o){return o.adminName1})
Here's a jsfiddle that doesn't show duplicates. But again, it's hard to tell what a duplicate really is from your structure, but this code should move you in the right direction
You don't have use underscore, it's really easy to implement uniq on your own, just look at azcn2503's answer
I modified the code slightly so that it does the following:
Puts all the autocomplete entries in to an object, with the autocomplete value as the key
Converts this object back in to an array and returns it
By doing this, any duplicate keys simply overwrite the previous one.
The success function now looks like this:
success: function( data ) {
var x = $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
});
// Create an object to easily filter out duplicates (key of same name will simply be reused)
var x2 = {};
for(var i in x) {
x2[x[i].value] = x[i];
}
// Create a new array that simply converts the object in to a de-duplicated array
var x3 = [];
for(var i in x2) {
x3.push(x2[i]);
}
// Return the array
response(x3);
}
I have tested it and it seems to be working, although your issue with the duplicates appearing in the first place is not something I can replicate.
Updated fiddle: http://jsfiddle.net/nHgMX/8/
If your ajax call is returning an array with the response value, you can run it through a plugin to remove duplicate entries. Here's a plugin that I found on another SO thread somewhere a while back.
function ArrayNoDupes(array) {
var temp = {};
for (var i = 0; i < array.length; i++)
temp[array[i].value] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
I may be mistaken, but you would implement it into your existing code by changing the following line:
source: function( ArrayNoDupes(request), response )
EDIT: Updated function per Juan Mendes' comment

Categories

Resources