Value number no appear inside js - javascript

I don't understand why the id: ' . $QspecificationName->valueInt('specification_id') . ', does'nt want to take the value of $QspecificationName->valueInt('specification_id');
$QspecificationName->valueInt('specification_id') has value like 2 and 3 but it write always 0.
Any idea ?
Tk
while ($Qspecification->fetch()) {
$specification_name = $this->productsSpecificationAdmin->getSpecificationName($Qspecification->valueInt('specification_id'), $this->lang->getId());
$customers_group_id = $Qspecification->valueInt('customers_group_id');
$QspecificationName = $this->app->db->prepare('select distinct s.specification_id as id,
sd.name as name,
sgd.name as groupName
from :table_specification s
left join :table_specification_group sg ON (s.specification_group_id = sg.specification_group_id )
left join :table_specification_group_description sgd on (sg.specification_group_id = sgd.specification_group_id),
:table_specification_description sd
where s.specification_id = sd.specification_id
and s.specification_id = :specification_id
and sg.specification_group_id = sgd.specification_group_id
and sd.language_id = :language_id
and sgd.language_id = :language_id
');
$QspecificationName->bindInt('specification_id', $Qspecification->valueInt('specification_id'));
$QspecificationName->bindInt(':language_id', $this->lang->getId());
$QspecificationName->execute();
$content .= '<tr id="specification-row' . $t . '">';
$content .= HTML::hiddenField('id', $Qspecification->valueInt('id'));
$content .= ' <td>
<script type="text/javascript">
$(document).ready(function() {
$("#specificationName' . $t . '").tokenInput("' . $products_specification_ajax . '" ,
{
tokenLimit: 1,
resultsLimit: 5,
onResult: function (results) {
$.each(results, function (index, value) {
value.name = value.id + " " + value.groupName + "/" + value.name;
});
return results;
}
});
});
$(document).ready(function() {
$("#specificationName' . $t . '").tokenInput("' . $products_specification_ajax . '", {
prePopulate: [
{
id: ' . $QspecificationName->valueInt('specification_id') . ',
name: "' . $QspecificationName->valueInt('specification_id') . ' ' . $QspecificationName->value('groupName') . '/' . $QspecificationName->value('name') . '"
}
],
tokenLimit: 1
});
});
</script>
}

Related

Woocommerce Variations Radio buttons

I had the hooks below that's working perfectly to change the Products variations select to radio buttons while creating variations using custom attributes.
I added new products variations using the Global Attributes but it seems that the hook is not compatible with it.
am looking for a way to make it compatible with both since I already have 200 products using the custom attributes and want to start using global attributes for the new products.
function variation_radio_buttons($html, $args)
{
$args = wp_parse_args(apply_filters('woocommerce_dropdown_variation_attribute_options_args', $args) , array(
'options' => false,
'attribute' => false,
'product' => false,
'selected' => false,
'name' => '',
'id' => '',
'class' => '',
'show_option_none' => __('Choose an option', 'woocommerce') ,
));
if (false === $args['selected'] && $args['attribute'] && $args['product'] instanceof WC_Product)
{
$selected_key = 'attribute_' . sanitize_title($args['attribute']);
$args['selected'] = isset($_REQUEST[$selected_key]) ? wc_clean(wp_unslash($_REQUEST[$selected_key])) : $args['product']->get_variation_default_attribute($args['attribute']);
}
$options = $args['options'];
$product = $args['product'];
$attribute = $args['attribute'];
$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title($attribute);
$id = $args['id'] ? $args['id'] : sanitize_title($attribute);
$class = $args['class'];
$show_option_none = (bool)$args['show_option_none'];
$show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __('Choose an option', 'woocommerce');
$label = wc_attribute_label($args['attribute'], $args['product']);
if (empty($options) && !empty($product) && !empty($attribute))
{
$attributes = $product->get_variation_attributes();
$options = $attributes[$attribute];
}
$html = '<select id="' . esc_attr($id) . '" class="d-none ' . esc_attr($class) . '" name="' . esc_attr($name) . '" data-attribute_name="attribute_' . esc_attr(sanitize_title($attribute)) . '" data-show_option_none="' . ($show_option_none ? 'yes' : 'no') . '">';
$html .= '<option value="">' . esc_html($show_option_none_text) . '</option>';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
// Get terms if this is a taxonomy - ordered. We need the names too.
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all'
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options))
{
$html .= '<option value="' . esc_attr($term->slug) . '" ' . selected(sanitize_title($args['selected']) , $term->slug, false) . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</option>';
}
}
}
else
{
foreach ($options as $option)
{
// This handles < 2.4.0 bw compatibility where text attributes were not sanitized.
//$selected = sanitize_title( $args['selected'] ) === $args['selected'] ? selected( $args['selected'], sanitize_title( $option ), false ) : selected( $args['selected'], $option, false );
//if (sanitize_title($option) == $current){
//$selected = 'selected';
//}
$selected = '';
$html .= '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</option>';
}
}
}
$html .= '</select>';
$radios = '<div class="radio-group">';
if (!empty($options))
{
if ($product && taxonomy_exists($attribute))
{
$terms = wc_get_product_terms($product->get_id() , $attribute, array(
'fields' => 'all',
));
foreach ($terms as $term)
{
if (in_array($term->slug, $options, true))
{
$radios .= '<input id="' . strtolower($option) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($term->slug) . '" onClick="jQuery("#' . esc_attr($name) . '").val(' . esc_attr($term->slug) . ').trigger("change");" ' . checked(sanitize_title($args['selected']) , $term->slug, false) . '><label for="' . esc_attr($term->slug) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $term->name)) . '</label>';
}
}
}
else
{
foreach ($options as $option)
{
// $checked = sanitize_title($args['selected']) === $args['selected'] ? checked($args['selected'], sanitize_title($option), false) : checked($args['selected'], $option, false);
//if (sanitize_title($option) == $current){
//$checked = 'checked="checked"';
//}
$checked = '';
$radios .= '<input id="' . strtolower(sanitize_title($option)) . '" type="radio" name="' . esc_attr($name) . '" value="' . esc_attr($option) . '" id="' . sanitize_title($option) . '" onClick="changeTrigger(\'#' . strtolower($attribute) . '\',\'' . esc_attr($option) . '\',\'' . esc_attr($label) . '\');" ' . $checked . '><label for="' . sanitize_title($option) . '">' . esc_html(apply_filters('woocommerce_variation_option_name', $option)) . '</label>';
$allAttribute[] = strtolower($attribute);
}
}
}
$radios .= '</div>';
return $html . $radios;
}
add_filter('woocommerce_dropdown_variation_attribute_options_html', 'variation_radio_buttons', 20, 2);
function variation_check($active, $variation)
{
if (!$variation->is_in_stock() && !$variation->backorders_allowed())
{
return false;
}
return $active;
}
add_filter('woocommerce_variation_is_active', 'variation_check', 10, 2);
if (!function_exists('shop_attributes_in_loop'))
{
function shop_attributes_in_loop()
{
global $product;
//Getting product attributes
$product_attributes = $product->get_attributes();
if (!empty($product_attributes))
{
//Getting product attributes slugs
$product_attribute_slugs = array_keys($product_attributes);
?>
<script>
function resetAttr(c,d){
var attr = c;
jQuery('input[name=attribute_'+c+']').attr('disabled',false);
jQuery('input[name=attribute_'+c+']').attr('checked',false);
jQuery('#' + c + '-selected').html('');
jQuery('#' + c + '-section').removeClass('d-none');
jQuery('#' + c + ' option[value=""]').prop('selected', true);
if(d){
jQuery('#' + c).trigger('change');
}
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
jQuery(this).attr('disabled', false);
}
});
<?php
}
?>
}
function changeTrigger(a,b,c){
a = a.replace(/\s+/g, "-");
jQuery(a + ' option[value="' + b + '"]').prop('selected', true);
jQuery(a + '-selected').html('<div class="selected-variable"><span>'+c.replace(/#/, "").toUpperCase()+': '+b+' </span><a class="var-del" onClick="resetAttr(\''+a.replace(/#/, "")+'\',true)"><div class="close-x"></div></a></div>');
jQuery(a + '-section').addClass('d-none');
jQuery('input[name=attribute_'+a.replace(/#/, "")+']').attr('disabled',true);
jQuery(a).trigger('change');
<?php
foreach ($product_attribute_slugs as $product_attribute_slug)
{
$attribute_name = str_replace('pa_', '', $product_attribute_slug); // Removing "pa_" from attribute slug
//echo 'jQuery(\'#'.$attribute_name.'\').trigger(\'change\');';
?>
var allvalues = [];
jQuery('select#<?php echo $attribute_name; ?>').find('option').each(function() {
if(jQuery('select#<?php echo $attribute_name; ?>').val() == ""){
resetAttr('<?php echo $attribute_name; ?>',false);
/*jQuery('input[name=attribute_<?php echo $attribute_name; ?>]').attr('checked',false);*/
if(jQuery(this).attr('disabled', false)){
var theValue = jQuery(this).val();
allvalues.push(theValue);
}
}
});
jQuery('input[name="attribute_<?php echo $attribute_name; ?>"]').each(function () {
var theRadio = jQuery(this).val();
var check = allvalues.includes(theRadio);
if(check == false){
jQuery(this).attr('disabled', true);
}else{
//jQuery(this).attr('disabled', false);
}
});
<?php
}
echo "}</script>";
}
}
}
add_action('woocommerce_before_add_to_cart_button', 'shop_attributes_in_loop');

Star rating system created through loop

enter image description hereI have a table that displays a list of recipes from a database. Each recipe stores a rating out of 5. If no ratings has been submitted 'Not yet rated' will display. If a recipe has a rating, for example, 3, I would like 3 stars to appear. I have wrote jquery to try to achieve this but it works for the first recipe and not for the rest. For each recipe, more stars are printed. Any ideas where I'm going wrong?
if ($avg !=0)
{
define('RATE_RECIPE_MAX_STAR_RATING', 5);
$contentitems1 = "<form><div class='stars'>";
for ($i = 1; $i <= RATE_RECIPE_MAX_STAR_RATING; $i++)
{
//$contentitems1 .= '<input type="radio" style= "display:none;"
//$contentitems1 .= '<img class="rate_recipe_star" name="star_' . $i . '" id="star_' . $i . '" src="fadedstar.png" width="25" />';
$contentitems1 .= '<span class="fa fa-star-o star" name="star_' . $i . '" id="star_' . $i . '"></span>';
}
"</div></form>";
echo $contentitems1 .="<script type='text/javascript'> paint_the_stars($avg)
</script>";}
echo '<div class="star_' . $avg . '"></div>'?>
function paint_the_stars(howmany) {
var items = new Array();
$(".star").each(function() {
//var star = jQuery(this)
var star = $(this);
console.log(star);
var starno = $(star).attr('id').substring(5);
console.log(starno);
//console.log("Star:"+star);
if (starno <= howmany) {
//console.log("TRUE PRINT A STAR"+starno);
//$(this).attr('src', 'yellowstar.png');
var item = $(this).removeClass("fa-star-o").addClass("fa-star");
items.push(item);
} else {
//return true;
var item = $(this).removeClass("fa-star").addClass("fa-star-o");
items.push(item);
}
if (starno == 5) {
$.each(items, function(){
console.log(this);
$('.star_'+howmany).append(this);
});
return false;
}
})
}

localstorage data not persisting between pages

I am attempting to build a website to assist with recording times of events during ems calls. I have replicated our protocols and am using localstorage to record when and what event happens. When the incident is over, all the events that have been clicked are displayed on a report page where the information can be sent via email.
Everything seems to work, however, if another page is opened, the localstorage seem to clear and only the buttons clicked on the most recent page appear. I need every button clicked recorded for the report.
This is my JS:
//GO BACK BUTTON
function goBack() {
window.history.back();
}
// DATE FORMATER
function convertDate() {
var d = new Date();
var a = [(d.getMonth() + 1),
(d.getDate()),
(d.getFullYear()),
].join('-');
var b = [(d.getHours()),
(d.getMinutes()),
(d.getSeconds()),
].join(':');
return (b + ' ' + a);
}
///////////////////button////////////////////////
$(document).ready(function () {
var report = {};
var myItem = [];
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.report = JSON.stringify(myItem);
});
});
And this is part of the report page:
<script>
window.onload = function () {
var areport = JSON.stringify(localStorage.report);
console.log(areport);
areport = areport.replace(/\\"/g, "");
areport = areport.replace(/{/g, "");
areport = areport.replace(/}/g, "");
areport = areport.replace(/[\[\]']+/g, "");
areport = areport.replace(/,/g, "");
areport = areport.replace(/"/g, "");
console.log(areport);
document.getElementById('result').innerHTML = areport;
};
</script>
<body>
<div class="container-fluid">
<h1>Report</h1>
<?php
if (isset($_POST["send"])) {
$incident = $_POST['incident'];
$name = $_POST['name'];
$address = $_POST['address'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$reportData = $_POST['reportData'];
if ($incident == '') {
echo $incident = 'No incident number entered.';
echo '<br>';
} else {
echo $incident . '<br>';
}
if ($name == '') {
echo $name = 'No name entered.';
echo '<br>';
} else {
echo $name . '<br>';
}
if ($address == '') {
echo $address = 'No address entered.';
echo '<br>';
} else {
echo $address . '<br>';
}
if ($dob == '') {
echo $dob = 'No birthdate entered.';
echo '<br>';
} else {
echo $dob . '<br>';
}
if ($gender == '') {
echo $gender = 'No gender entered.';
echo '<br>';
} else {
echo $gender . '<br>';
}
if ($reportData == null) {
echo $reportData = 'No report entered.';
echo '<br>';
} else {
echo $reportData . '<br>';
}
//mail
$headers = "From: CCEMP.info <ccemlbaw#server237.web-hosting.com> \r\n";
$reEmail = $_POST['reEmail'];
$reEmail1 = $_POST['reEmail1'];
//$areport = json_decode($_POST['localStorage.report']);
$msg = "Incident: " . $incident . "\n" . "Name: " . $name . "\n" . "Address:
". $address . "\n" . "DOB: " . $dob . "\n" . "Gender: " . $gender . "\n" .
$reportData;
mail($reEmail, 'Incident:' . $incident, $msg, $headers);
mail($reEmail1, 'Incident:' . $incident, $msg, $headers);
}//end of submit
?>
Here is a sample button:
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">General Truama</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" >Continue Assessment</a>
<a class="dropdown-item" href="GATA.php">Go to Truama</a>
</div>
</div>
Thanks.
You are not using localStorage, just setting .report on global localStorage variable. You would see this issue if you used strict mode ("use strict"; at top of the js file).
instead use:
localStorage.setItem("report", JSON.stringify(myItem));
and to get the item
localStorage.getItem("report");
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This does not set the item to localStorage. In fact, localStorage.report is undefined.
localStorage.report = JSON.stringify(myItem);
This does.
localStorage.setItem('report', JSON.stringify(myItem));
I wasn't adding the localStorage from the previous page to the new one.
var myItem = [];
$(document).ready(function () {
$('button').click(function () {
var itemTime = convertDate() + " ___ " ;
var clickedBtnID = $(this).text() + " # " ;
var item = {
ITEM: clickedBtnID,
TIME: itemTime ,
};
myItem.push(item);
localStorage.setItem('report', JSON.stringify(myItem));
console.log(myItem);
});
var areport = localStorage.getItem("report");
myItem.push(areport);
});

get current value input field quantity Woocommerce

there is any way in php to get the current value of quantity input of Woocommerce ?
I mean this field :
I need to get in this case 10 and output it.
How can I do that please?
Thanks
I resolve install this plugin : https://it.wordpress.org/plugins/woo-min-max-quantity-limit/
with this I can get the min and max value for each product.
I use the code inside :
$max = get_post_meta($product->id, '_wc_mmax_max', true);
$min = get_post_meta($product->id, '_wc_mmax_min', true);
the full code is :
// we are going to hook this on priority 31, so that it would display below add to cart button.
add_action('woocommerce_single_product_summary', 'woocommerce_total_product_price', 31);
function woocommerce_total_product_price() {
global $woocommerce, $product;
$max = get_post_meta($product->id, '_wc_mmax_max', true);
$min = get_post_meta($product->id, '_wc_mmax_min', true);
echo sprintf('<div id="product_total_price" style="margin-bottom:20px;display:none">%s %s</div>', __('Prezzo Prodotto :', 'woocommerce'), '<span class="price">' . $product->get_price() . '</span>');
echo sprintf('<div id="cart_total_price" style="margin-bottom:20px;display:none">%s %s</div>', __('Totale Carrello :', 'woocommerce'), '<span class="price">' . $product->get_price() . '</span>');
$moltiplicazione_prodotto = $product->get_price() * $max;
$moltiplicazione_prodotto = number_format($moltiplicazione_prodotto, 2, '.', '');
echo sprintf('<div id="prodotti_quantity" style="margin-bottom:20px;">%s %s</div>', __('Prezzo Prodotto :', 'woocommerce'), '<span class="price">' . get_woocommerce_currency_symbol() . $moltiplicazione_prodotto . '</span>');
?>
<script>
jQuery(function ($) {
var price = <?php echo $product->get_price(); ?>,
current_cart_total = <?php echo $woocommerce->cart->cart_contents_total; ?>,
currency = '<?php echo get_woocommerce_currency_symbol(); ?>';
var quantita_iniziale = $('[name=quantity]').val();
$('#prodotti_quantity').html(this.value);
console.log("quantita iniziale", this.value);
$('[name=quantity]').change(function () {
if (!(this.value < 1)) {
var product_total = parseFloat(price * this.value),
cart_total = parseFloat(product_total + current_cart_total);
$('#product_total_price .price').html(currency + product_total.toFixed(2));
$('#cart_total_price .price').html(currency + cart_total.toFixed(2));
if(this.value){
$('#prodotti_quantity').html(this.value).hide();
}
}
$('#product_total_price,#cart_total_price').toggle(!(this.value <= 1));
});
});
</script>
<?php
}

firefox issue with js slider

I have this slider and it works fine in IE and chrome but has a problem in firefox, it loads all the picture one time but it does not go back again and load them, in the console i get this error
"SyntaxError: missing ] after element lis" in the line of setTimeout(func,900)
this is the code
function pic_loader() {
//alert('s');
var func = new function () {}
$folder = $('#foldername').attr('value');
$files = document.getElementById('filename').value;
$num = document.getElementById('num').value;
$filenames = $files.split("##");
var $img = [];
var $link = [];
if ($num > 1) {
for ($i = 1; $i <= $num; $i++) {
$img[$i] = $folder + "/" + $filenames[$i];
if ($i == 1) {
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + ">";
$("#load_here").append($link[$i]);
$first = document.getElementById('slide[1]');
$first.style.display = "none";
$($first).fadeIn(800);
} else {
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + " style='display:none'>";
$("#load_here").append($link[$i]);
}
}
$i = 1;
var $loop = setInterval(function () {
//alert('x');
$j = $i + 1;
$current = document.getElementById('slide[' + ($i++) + ']');
$next = document.getElementById('slide[' + ($j) + ']');
$($current).fadeOut(800, function () {
$($next).fadeIn(800);
});
if ($j > $num) {
$($next).fadeOut(800);
setTimeout(func, 900);
function func() {
clearInterval($loop);
$("#load_here").html("");
pic_loader();
}
}
}, 4500);
} else {
$i = 1;
$img[$i] = $folder + "/" + $filenames[$i];
$link[$i] = "<img id='slide[" + $i + "]' width=380 src=" + $img[$i] + ">";
$("#load_here").append($link[$i]);
}
}
There is no syntax error in the code you pasted. It must be elsewhere. Paste it into jsfiddle, it does not throw a syntax error.
First of all, id attribute cannot contains [ or ] character.
You can use name atrribute in place od id or create id like slide_1,slide_2,....
Using name attribute you can use function like :
$current = document.getElementsByName('slide[' + ($i++) + ']');
This post can help you more about your problem Accessing an array of HTML input text boxes using jQuery or plain Javascript

Categories

Resources