Hide <tr> containing specific ID's - javascript

I have multiple tables on one page and an array of numbers from array_keys.
I have given each <tr> an incremental ID, starting at 0. If my array returns 0,1,3,5 I would want the <tr> with an ID of 2 and 4 to hide. Usually I would use CSS and apply a style: display=none.
I presume I need to use jQuery .find() within a array loop such as this:
$arr = array_keys($floor_item, $po); //floor_item is my array & po is the value I'm searching
foreach($arr as $key => $item){
print "<tr id='" . $item . "'><td>" . $item . "</td></tr>"; //this will show me the id's I want
//just guessing here
$( "tr" ).find( "$item" ).hide();
}

If you need to use client side code to hide the elements, try something like this:
var jsArray = [<?php echo(implode(",", $ids_you_want_to_show_array); ?>];
$("#your_table_id tr").hide();
$.each(jsArray, function(key, value) {
$("#tr_" + value).show();
});
Assuming your td's ids are "tr_0", "tr_1", and so on.
By the way, don't use numbers as ID.

Try this:
$arr = array_keys(1,2,3,4,5,6,7,8,9,10);
$i == 0;
foreach ($arr as $item) {
if ($i%2 != 0 || $i == 0) {
//this will show me the id's I want
print "<tr id='pref_" . $item . "'><td>" . $item . "</td></tr>";
}
$i++;
}
Anyway, you need to learn php from basics before you start to use that.
In arrays, if you want key/value pairs you can define it like:
$array = array(
'key1' => 'value',
7 => 'other value',
...
);
or
$array['key1'] = 'value';
$array[7] = 'other value';
And as i mentioned, you can not use jQuery/javascript code in your php code.

Related

PHP modify fetched variable and return to frontend for JS

Im fetching Product Attributes from Woocommerce, and echo them out in a script tag as variable to use with javascript in frontend.
This might be a bad practice, feel free to enlighten me.
Example:
Product Attributes:
Total height: 43m
Total length: 55m
PHP queries "Total-height" as Attribute Name and "43m" as Attribute Value.
PHP replaces empty space with "-".
I can't define a javascript var with "-" in var name.
Example: var Total-height = "43m";
How could I fix this issue?
Here is my code.
Thanks in advance.
function product_attribute_dimensions(){
global $product;
foreach ($product->get_attributes() as $taxonomy => $attribute_obj ) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$value = $product->get_attribute($taxonomy);
if ($value) {
$label = get_taxonomy($taxonomy)->labels->singular_name;
$profile_one = $value;
echo '<script>' . $attribute_label_name . ' = "' . $value . '";
</script>';
}
}
try using window["variable_name"]
do this:
echo '<script>window["' . $attrname . '"]=' . $attrval
then in your js:
let this_var = window[attrname]
It seems like the clearest shortest way to do this.
As I understand the generated string in the variable "$attribute_label_name" is the problem? Take a look at https://www.php.net/manual/de/function.str-replace.php
With this native PHP function you can search for a character (eg."-") and replace with something else (eg. "_")
echo '<script>' . str_replace("-", "_", $attribute_label_name) . ' = "' . $value . '";
But as you said, this might not be the best approach. I personally would add this kind of information into a "data-X" HTML attribute in some HTML element and would extract this in my JS. Similar to this:
<div id="some_element" class="could be hidden" data-total-height="<?= $value ?>"></div>
You could Query something like this with jQuery $("#some_element").attr("data-total-height")
function product_attribute_dimensions() {
global $product;
$product_atrributes = array();
foreach ($product->get_attributes() as $taxonomy => $attribute_obj) {
// Get the attribute label
$attribute_label_name = wc_attribute_label($taxonomy);
$attribute_label_name = str_replace(' ', '_', $attribute_label_name);
$value = $product->get_attribute($taxonomy);
if ($value) {
$product_atrributes[$attribute_label_name] = $value;
}
}
echo '<script type="text/javascript">var product_atrributes = ' . json_encode($product_atrributes) . ';</script>';
}
Now you can use in JS like product_atrributes.Total_height.value
This way the redundant script tag also can be avoided.

How to dynamically pass an array of values to a <select> field in Contact Form 7?

According to the official Contact Form 7 docs, it is possible to pass a a default value to CF7 from the shortcode, in this way:
// field in CF7 in Wordpress admin area
[email* destination-email default:shortcode_attr]
// shortcode in a Wordpress php template
[contact-form-7 id="123" title="Contact Form" destination-email="xxxxxx#example.com"]
// function in functions.php
add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );
function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
$my_attr = 'destination-email';
if ( isset( $atts[$my_attr] ) ) {
$out[$my_attr] = $atts[$my_attr];
}
return $out;
}
This works for a simple text field, but I need to pass an array of values to a <select> field and use them as <option>s inside it; I've tried to modify a bit this code, but apparently it isn't working, or at least I've not been able to.
Is it possible to use the shortcode to send dynamic data to CF7 even if not a single plain text like this?
If not, I'm open to every other kind of solution, even if it involves another method, or some additional plugin; is there some other way to dynamically send an array of values to <select> fields in Contact Form 7?
These values are data queried from the database (such as post names, custom fields, and so on), so they need to come from php first even if there is a solution that involves javascript.
Here's an example of a form tag I've used for getting US States. This is a <select> generated from an array. This is probably more along the lines of what you want to do.
You can see that I also use the usermeta billing_state to pre-select the choice.
With that said, you should also be able to use this same method to create a select tag that performs any WP_Query and puts the results into an option tag.
<?php
add_action('wpcf7_init', function (){
wpcf7_add_form_tag( array('dd_states', 'dd_states*'), 'cf7_state_dropdown' , true );
});
function cf7_state_dropdown($tag) {
$tag = new WPCF7_FormTag( $tag );
$atts = array();
$validation_error = wpcf7_get_validation_error( $tag->type );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts['class'] = $tag->get_class_option( $class );
$atts['aria-required'] = 'true';
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$atts = wpcf7_format_atts( $atts );
// Get User ID and Billing State from DB
$userid = get_current_user_id();
$user_state = get_user_meta($userid, 'billing_state', true);
$states = array ( 'FL'=>'Florida','AL'=>'Alabama','AK'=>'Alaska','AZ'=>'Arizona','AR'=>'Arkansas','CA'=>'California','CO'=>'Colorado','CT'=>'Connecticut','DE'=>'Delaware','DC'=>'District of Columbia','GA'=>'Georgia','HI'=>'Hawaii','ID'=>'Idaho','IL'=>'Illinois','IN'=>'Indiana','IA'=>'Iowa','KS'=>'Kansas','KY'=>'Kentucky','LA'=>'Louisiana','ME'=>'Maine','MD'=>'Maryland','MA'=>'Massachusetts','MI'=>'Michigan','MN'=>'Minnesota','MS'=>'Mississippi','MO'=>'Missouri','MT'=>'Montana','NE'=>'Nebraska','NV'=>'Nevada','NH'=>'New Hampshire','NJ'=>'New Jersey','NM'=>'New Mexico','NY'=>'New York','NC'=>'North Carolina','ND'=>'North Dakota','OH'=>'Ohio','OK'=>'Oklahoma','OR'=>'Oregon','PA'=>'Pennsylvania','RI'=>'Rhode Island','SC'=>'South Carolina','SD'=>'South Dakota','TN'=>'Tennessee','TX'=>'Texas','UT'=>'Utah','VT'=>'Vermont','VA'=>'Virginia','WA'=>'Washington','WV'=>'West Virginia','WI'=>'Wisconsin','WY'=>'Wyoming');
$output = '<span class="wpcf7-form-control-wrap '.sanitize_html_class( $tag->name ).'"><select name="state" id="state" '.$atts.'>';
$output .= "<option value=\"\"> - - Choose State - - </option>";
foreach ($states as $abbrev=>$state){
$selected = ($user_state == $abbrev) ? ' selected="selected"' : '';
$output .= '<option value="'.$abbrev.'"'. $selected .'>'.$state.'</option>';
}
$output .= "</select></span>";
$output .= $validation_error;
return $output;
}

Use of PHP script in a jquery function

I've echoed the following php and it shows up properly in HTML so that can't be a problem:
PHP
if (mysqli_num_rows($result) > 0) {
//create the drop down menu
$list ="";
while($row = mysqli_fetch_assoc($result)) {
$list = '<div class="dropOption">'.$row["item"].'</div>';
}
This outputs three rows - apple, pear, strawberry - in the right div format.
And when I put the following php script into the jquery function below, the menu does contain the value strawberry (the last), however the first two are missing.
JavaScript
//drop down menu
$(document).ready(function(){
function createDropdown(){
var drop = $('#customDropdown');
var i;
var htmlString = '<div id="dropContainer">';
htmlString += '<?php echo $list;?>';
htmlString += '</div>';
drop.append(htmlString);
}
createDropdown();
I'm new to jquery and php so forgive me if the error is simple; however I'm pretty sure it's right, functionally speaking, because I'm getting something; so I figured the syntax must get be wrong somewhere. Can anybody help? Thanks in advance.
In your php it should be
$list .= '<div class="dropOption">'.$row["item"].'</div>';
and then output just like this <?=$list;?> in your js part
. is used to concatenate strings in php
You're only assigning the last item to the $list variable. You need to concatenate them all together.
Try:
if (mysqli_num_rows($result) > 0) {
// Create the drop down menu
$list = "";
while($row = mysqli_fetch_assoc($result)) {
$list .= '<div class="dropOption">' . $row["item"] . '</div>';
}
}
Note the $list .= instead of $list = part.

JS - constructingan array - SyntaxError: missing ] after element list

I'm trying to make autocomplete on a research of elements from my Database (wich is on SQL Server).
Here is my PHP request :
public function getNomProduitsAutocomplete() {
$q = ' SELECT NomProduit
FROM Produit
WHERE NomProduit LIKE \'a%\' OR NomProduit LIKE \'b%\'
ORDER BY NomProduit';
$qResults = $this->fetchAll($q);
$numItems = count($qResults);
$i = 0;
//var_dump($numItems);
$result = '[ ';
foreach($qResults as $res){
if(++$i === $numItems) {
$result .= '"' .$res['NomProduit'] . '"' ;
}
else {
$result .= '"' .$res['NomProduit'] . '", ';
}
}
$result .= ' ]';
return $result;
}
And the auto complete in js here :
$(function () {
<?php
$p = new Produit();
$produits = $p->getNomProduitsAutocomplete();
//var_dump($produits);
?>
var availableTags2 = <?php echo ($produits); ?>;
$( "#tags" ).autocomplete({
source: availableTags2
});
});
and finaly the input for the auto complete :
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
All of this works fine, but ONLY when I have, less than 1 000 elements in the array, it seems.
It actually works with 700 elements (" WHERE NomProduit LIKE \'a%\' OR NomProduit LIKE \'b%\' " as you see), and I would like to get ALL the elements (+/- 4 800 elements) if possible, not only 700...
If you have any ideas... :)
Thanks.
Why are you not using josn_encode function in your getNomProduitsAutocomplete function?
You are manually creating the javascript array in PHP, instead collect all your $res['NomProduit'] in an array say $js_array and then use return json_encode($js_array)

Populating a select box with JSON array results

So I'm trying to populate a select box within my html with array objects using JSON results, I've been looking at all this code so long I don't think I'm seeing the simple solution to my problem. This is my callback function where I'm populating the select box. The JSON request has went through fine but I am stuck with a blank select box everytime.
function getArtistsCallBack()
{
if (req.readyState == 4) {
if (req.status == 200) {
// TO DO: populate artistlist select box using JSON
var response = req.responseText.parseJSON();
var artistSelect = document.getElementById("artistlist");
for (i=0;i<response.artistsarray.length;i++){
var artist_id = response.artistsarray[i].artist;
var artist = response.artistsarray[i].artist;
artistSelect.options[artistSelect.options.length] = new Option(artist, artist_id, false, true);
}
}
}
}
Here is the select box within the HTML for reference just in case;
<div id="artistscontent">
<select id="artistlist"></select>
</div>
This is artists.php where a database is queried for an array of objects, the array that is used previously;
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
$artistsarray = Collection::GetArtists();
print json_encode($artistsarray);
$jsonresponse='{"artistsarray":[';
foreach($artistsarray as $artist => $row)
{
$artist_id=$artist+1;
$artist=$row['artist'];
$jsonresponse .= '"artist_id":"' . $artist_id . '"},';
$jsonresponse .= '"artist:"' . $artist . '"},';
}
$jsonresponse .= ']}';
echo $jsonresponse;
?>
Any help would be much appreciated! Thanks!
You need to use the json length for the options array and do it outside of the for loop. Then use options.add
var json = [{key:'1', value:'value1'},{key:'2', value:'value2'}]
var artistSelect = document.getElementById("artistlist");
artistSelect.options[json.length];
$.each(json, function(key, value){
console.debug(value);
artistSelect.options.add(new Option(value.key, value.value));
});
Check out this plunker:
http://plnkr.co/edit/i3A6mo672CskXvbstWsu?p=preview
The artistSelect.options is not an array, you need to use the add method:
var opt = new Option(artist, artist_id);
artistSelect.options.add(opt);

Categories