I'm creating simple quiz plugin, but now I'm in dilemma, because don't have an idea how to make options to auto-scroll to the top of the Explanation Box after visitor choose an answer (right or wrong, explanation box is same with same content. Note - explainer box is hidden until visitor clicks with mouse on checkbox of any offered answer.
Below is JavaScript code I have so far:
var wpvqgr = wpvqgr || {};
(function($)
{
$(document).ready(function()
{
wpvqgr.selectAnswer = function($question, question_id, $answer, answer_id)
{
// Don't let the user play twice the same question!
if ($answer.hasClass('wpvqgr-disabled-answer') && !wpvqgr.vars.quiz.settings.trivia_hiderightwrong) {
return;
}
// Right or wrong?
var rightAnswers = wpvqgr.getRightAnswers(question_id);
var isRight = (rightAnswers.indexOf(answer_id) > -1);
// Store data
var _answers = wpvqgr.getStore('answers') || { 'questions' : [] };
_answers.questions[question_id] = {
'answer_id' : answer_id,
'isRight' : isRight,
'rightAnswers' : rightAnswers,
};
wpvqgr.setStore('answers', _answers);
// Display Right or Wrong answers
if (wpvqgr.vars.quiz.settings.trivia_hiderightwrong != 'yes')
{
// First, disable every answers
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer').addClass('wpvqgr-disabled-answer');
// Add explanation
var $explanation = $question.find('div.wpvqgr-explanation');
$explanation.find('div.wpvqgr-explanation-content').html(wpvqgr.vars.quiz.questions[question_id].wpvqgr_quiz_questions_explanation);
if (isRight)
{
$explanation.find('h3.wpvqgr-thats-right').show();
$answer.addClass('wpvqgr-right-answer');
}
else
{
$explanation.find('h3.wpvqgr-thats-wrong').show();
$answer.addClass('wpvqgr-wrong-answer');
$.each(rightAnswers, function(index, answer_id){
$question.find('.wpvqgr-answer[data-id=' + answer_id + ']').addClass('wpvqgr-right-answer');
});
}
$explanation.show();
}
else
{
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer');
$answer.addClass('wpvqgr-selected-answer');
}
// Update visual checkbox
$question.find('div.wpvqgr-checkbox-picture').removeClass('wpvqgr-checkbox-checked-picture');
$answer.find('div.wpvqgr-checkbox-picture').addClass('wpvqgr-checkbox-checked-picture');
// Not a visual class, just marked as
$answer.addClass('wpvqgr-is-selected-answer');
};
wpvqgr.computeResults = function()
{
var answers = wpvqgr.getStore('answers') || { 'questions' : [] };
var finalScore = 0;
// Score
$.each(answers.questions, function (q_id, answer_data) {
if (answer_data.isRight) {
finalScore++;
}
});
// Appreciation
var appreciation = wpvqgr.getAppreciation(finalScore);
// Store global data for Facebook, page refresh and other stuff
wpvqgr.setStore('finalScore', finalScore);
wpvqgr.setStore('appreciation', appreciation);
};
//Autoscroll
/**
* Integrate results in view
* #return {[type]} [description]
*/
wpvqgr.integrateResults = function ()
{
wpvqgr.parseResults('quizname', wpvqgr.vars.quiz.general.name);
wpvqgr.parseResults('score', wpvqgr.getStore('finalScore'));
wpvqgr.parseResults('total', wpvqgr.getStore('answers').questions.length);
wpvqgr.parseResults('description', wpvqgr.getStore('appreciation').content);
}
wpvqgr.getAppreciation = function(score)
{
var finalAppreciationId = -1;
var finalAppreciationScoreStep = 9999;
$.each(wpvqgr.vars.quiz.appreciations, function (ap_id, data)
{
var app_score = parseInt(data.score);
if (score <= app_score && finalAppreciationScoreStep > app_score)
{
finalAppreciationScoreStep = app_score;
finalAppreciationId = ap_id;
}
});
// No appreciation found!
if (finalAppreciationId == -1) {
return { 'content':'', 'redirect':'', 'picture':'', 'score':-1 }
} else {
return wpvqgr.vars.quiz.appreciations[finalAppreciationId];
}
};
wpvqgr.getRightAnswers = function(question_id)
{
var rightAnswers = [];
var answers = wpvqgr.vars.quiz.questions[question_id]['wpvqgr_quiz_questions_answers'];
$.each(answers, function(id, data) {
if (data['wpvqgr_quiz_questions_answers_right']) {
rightAnswers.push(id);
}
});
return rightAnswers;
};
wpvqgr.getFinalScore = function()
{
return wpvqgr.getStore('finalScore');
};
});
})(jQuery);
/**
* Store
*
* questions[$id] = $answer_id
*
*
*
*/
<?php global $wpvqgr_quiz, $wpvqgr_quiz_columns, $wpvqgr_resources_dir_url, $wpvqgr_skin_dir_url; ?>
<!-- Load CSS Skin Theme -->
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'css/bootstrap-wrapper.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'icons/fa/css/font-awesome.min.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_resources_dir_url . 'css/fo-style.css'; ?>'); </style>
<style> #import url('<?php echo $wpvqgr_skin_dir_url . 'style.css'; ?>'); </style>
<!-- Custom style -->
<style>
<?php if ($wpvqgr_quiz->getSetting('progessbarcolor') != ''): ?>
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-playagain,
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-start-button,
.wpvqgr-wrapper div.wpvqgr-continue button.wpvqgr-button,
.wpvqgr-wrapper button.wpvqgr-button.wpvqgr-askinfo-submit,
.wpvqgr-progress .progress-bar {
background-color:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;
}
<?php endif; ?>
<?php echo $wpvqgr_quiz->getSetting('global_custom_css'); ?>
</style>
<!-- Facebook SDK -->
<script type="text/javascript">
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<!-- / Prepare sharing options -->
<?php echo apply_filters('wpvqgr_public_version', "<!-- Quiz Created with WP Viral Quiz (v".WPVQGR_VERSION.") - https://www.ohmyquiz.io/discover -->"); ?>
<a name="wpvqgr"></a>
<div class="wpvqgr-wrapper">
<div class="container-fluid">
<?php if ($wpvqgr_quiz->getSetting('startbutton') && !$wpvqgr_resultsOnly): ?>
<div class="wpvqgr-intro">
<?php if ($wpvqgr_quiz->getSetting('startbuttonintro')): ?>
<p><?php echo $wpvqgr_quiz->getSetting('startbuttonintro'); ?></p>
<?php endif ?>
<button class="wpvqgr-start-button wpvqgr-button"><?php echo $wpvqgr_quiz->getSetting('customlabel_startbutton'); ?></button>
</div>
<?php endif ?>
<div id="wpvqgr-<?php echo $wpvqgr_quiz->getId(); ?>" class="wpvqgr <?php echo $wpvqgr_quiz->getType(); ?>">
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_before')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_before')); ?>
</div>
<?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('top', $wpvqgr_quiz->getSetting('progessbar'))): ?>
<!-- Progress bar -->
<div class="wpvqgr-progress wpvqgr-progress-top progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<?php endif ?>
<?php if (!$wpvqgr_resultsOnly): ?>
<div class="wpvqgr-page-0 wpvqgr-page" data-id="0">
<?php
$wpvqgr_questions = $wpvqgr_quiz->getQuestionsAndBlocks();
$q_real_id = -1;
foreach($wpvqgr_questions as $q_id => $question):
// Type and content
$q_type = $question['_type'];
$q_content = ($q_type == 'wpvqgr_quiz_htmlblocks') ? $question['wpvqgr_quiz_htmlblocks_content'] : $question['wpvqgr_quiz_questions_content'];
// Real ID (ignore HTML blocks)
if ($q_type == 'wpvqgr_quiz_questions') {
$q_real_id++;
}
// Pagination
$q_isTherePage = ($question['wpvqgr_quiz_questions_addpage'] && isset($wpvqgr_questions[$q_id+1]));
$currentPage_id = (!isset($currentPage_id)) ? 0 : $currentPage_id;
// Picture
if ($q_type == 'wpvqgr_quiz_questions') {
$q_picture_id = $question['wpvqgr_quiz_questions_picture'];
$q_picture_info = WPVQGR_Snippets::wpGetAttachment($q_picture_id);
$q_picture_url = wp_get_attachment_url($q_picture_id);
}
?>
<div class="row">
<div class="col-sm-12">
<!-- Global ads between questions -->
<?php if ( $q_real_id > 0 && $wpvqgr_quiz->getSetting('global_ads_between_count') > 0 && ($q_real_id % $wpvqgr_quiz->getSetting('global_ads_between_count') == 0) ): ?>
<?php echo $wpvqgr_quiz->getSetting('global_ads_between_content'); ?>
<?php endif; ?>
<!-- HTML Blocks -->
<?php if ($q_type == 'wpvqgr_quiz_htmlblocks'): ?>
<div class="wpvqgr-htmlblock">
<?php echo do_shortcode($q_content); ?>
</div>
<?php else: ?>
<!-- Regular question -->
<div class="wpvqgr-question" data-id="<?php echo $q_real_id; ?>">
<div class="wpvqgr-question-label"><?php echo do_shortcode(nl2br($q_content)); ?></div>
<?php if (is_numeric($q_picture_id)): ?>
<div class="wpvqgr-question-picture">
<figure class="figure">
<img src="<?php echo $q_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($q_picture_info['alt']); ?>" />
<?php if ($q_picture_info['caption'] != ''): ?>
<figcaption class="figure-caption"><?php echo $q_picture_info['caption']; ?></figcaption>
<?php endif; ?>
</figure>
<?php if (function_exists ('adinserter')) echo adinserter (1); ?> <!-- / First Add Code -->
</div>
<?php endif ?>
<div class="row">
<?php
$smartColumns = WPVQGR_Snippets::getSmartColumnsSize($question, $wpvqgr_quiz_columns);
foreach ($question['wpvqgr_quiz_questions_answers'] as $a_id => $answer):
// Answer
$a_label = $answer['wpvqgr_quiz_questions_answers_answer'];
// Picture
if ($smartColumns['displayPicture'])
{
$a_picture_id = $answer['wpvqgr_quiz_questions_answers_picture'];
if ($a_picture_id == 0) {
$a_picture_info = array('alt' => '', 'caption' => '');
$a_picture_url = WPVQGR_PLUGIN_URL . '/resources/images/picture-placeholder.jpg';
} else {
$a_picture_info = WPVQGR_Snippets::wpGetAttachment($a_picture_id);
$a_picture_url = wp_get_attachment_image_src($a_picture_id, 'wpvqgr-square-answer');
$a_picture_url = $a_picture_url[0];
}
}
?>
<div class="wpvqgr-answer-col col-xs-<?php echo $smartColumns['xs-size']; ?> col-md-<?php echo $smartColumns['md-size']; ?>">
<div class="wpvqgr-answer" data-id="<?php echo $a_id; ?>">
<?php if ($wpvqgr_quiz->getType() == 'wpvqgr_quiz_perso'): ?>
<!-- Multipliers -->
<?php foreach ($answer['wpvqgr_quiz_questions_answers_multipliers'] as $p_id => $value): ?>
<input type="hidden" name="wpvqgr_answer_multipliers[]" data-pid="<?php echo (int)$p_id; ?>" value="<?php echo (int)$value; ?>" />
<?php endforeach ?>
<?php endif; ?>
<?php if ($smartColumns['displayPicture']): ?>
<div class="wpvqgr-answer-picture">
<figure class="figure">
<img src="<?php echo $a_picture_url; ?>" class="figure-img img-fluid" alt="<?php echo htmlentities($a_picture_info['alt']); ?>" />
<?php if ($a_picture_info['caption'] != ''): ?>
<figcaption class="figure-caption"><?php echo $a_picture_info['caption']; ?></figcaption>
<?php endif; ?>
</figure>
</div>
<?php endif ?>
<?php if ($a_label != ''): ?>
<div class="wpvqgr-checkbox">
<div class="wpvqgr-checkbox-picture wpvqgr-checkbox-unchecked-picture"></div>
<span class="wpvqgr-answer-label"><?php echo do_shortcode(stripslashes($a_label)); ?></span>
<hr class="wpvqgr-clear" />
</div>
<?php endif ?>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="row"><div class="col-sm-12">
<div class="wpvqgr-explanation">
<center><h6>⇩ SCROLL DOWN TO CONTINUE ⇩</h6></center>
<h3 class="wpvqgr-thats-right"><?php echo $wpvqgr_quiz->getSetting('customlabel_right'); ?></h3>
<h3 class="wpvqgr-thats-wrong"><?php echo $wpvqgr_quiz->getSetting('customlabel_wrong'); ?></h3>
<div class="wpvqgr-explanation-content"></div>
</div>
</div>
</div>
</div> <!-- .question -->
<?php endif; ?>
</div> <!-- / col -->
</div> <!-- / row -->
<div class="autoscroll>">
</div>
<div class="wpvqgr-continue">
<?php if (function_exists ('adinserter')) echo adinserter (2); ?> <!-- / Second Add Code -->
<button class="wpvqgr-button" style="background:<?php echo $wpvqgr_quiz->getSetting('progessbarcolor'); ?>;">
<?php echo $wpvqgr_quiz->getSetting('customlabel_continuebutton'); ?>
</button>
</div>
<?php
if ($q_isTherePage): $currentPage_id++;
?>
</div> <!-- close previous page -->
<div class="wpvqgr-page-<?php echo $currentPage_id; ?> wpvqgr-page" data-id="<?php echo $currentPage_id; ?>">
<?php endif ?>
<?php endforeach; ?>
</div> <!-- Final page close -->
<?php endif; ?>
<a id="wpvqgr-resultarea"></a>
<!-- Force to share -->
<div class="row">
<div class="col-xs-12 col-md-10 offset-md-1">
<div class="wpvqgr-forcetoshare">
<h3><?php echo __("Share the quiz to show your results !", 'wpvq'); ?></h3>
<button class="wpvqgr-button wpvqgr-social-facebook wpvqgr-force-share" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i> <?php echo __('Share on Facebook', 'wpvq'); ?></button>
</div>
</div>
</div>
<!-- Force to give some informations -->
<div class="row">
<div class="col-xs-12 col-md-10 offset-md-1">
<div class="wpvqgr-askinfo">
<h3><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfotitle'); ?></h3>
<form action="" method="GET">
<?php foreach($wpvqgr_quiz->getSetting('askinfo_fields') as $field): ?>
<?php
$field_slug = WPVQGR_Snippets::slugify($field['wpvqgr_settings_askinfo_fields_field_label']);
$is_required_field = ($field['wpvqgr_settings_askinfo_fields_field_optional'] != 'yes');
?>
<div class="form-group">
<label for="wpvqgr-<?php echo $field_slug; ?>"><?php echo $field['wpvqgr_settings_askinfo_fields_field_label']; ?></label>
<input type="<?php echo $field['wpvqgr_settings_askinfo_fields_field_type']; ?>" class="form-control" name="<?php echo $field_slug; ?>" id="wpvqgr-<?php echo $field_slug; ?>" <?php if($is_required_field): ?>required="true"<?php endif; ?>/>
</div>
<?php endforeach; ?>
<?php if ($wpvqgr_quiz->getSetting('global_gdpr_enabled') == 1): ?>
<div class="form-check gdpr-area">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="wpvq_gpdr" id="wpvq_gpdr_checkbox" required="true" />
<?php echo $wpvqgr_quiz->getSetting('global_gdpr_message'); ?>
</label>
</div>
<?php endif ?>
<div class="form-group" style="text-align:center;">
<button type="submit" class="wpvqgr-button wpvqgr-askinfo-submit"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfobutton'); ?></button>
</div>
</form>
<?php if ($wpvqgr_quiz->getSetting('askinfo_ignore')): ?>
<p class="wpvqgr-askinfo-ignore"><?php echo $wpvqgr_quiz->getSetting('customlabel_askinfoignore'); ?></p>
<?php endif ?>
</div>
</div>
</div>
<!-- Show results -->
<div class="row">
<div class="col-sm-12">
<div class="wpvqgr-results">
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_aboveresults')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_aboveresults')); ?>
</div>
<div class="wpvqgr-results-box <?php echo $wpvqgr_quiz->getType(); ?>">
<div class="wpvqgr-top-result">
<div class="wpvqgr-quiz-name"><?php echo stripslashes($wpvqgr_quiz->getName()); ?></div>
<h3><?php echo $wpvqgr_quiz->getSetting('global_template_result'); ?></h3>
<div class="wpvqgr-result-description">%%description%%</div>
</div>
<div class="wpvqgr-additional-results">
<div class="wpvqgr-additional-results-template">
<h3><?php echo $wpvqgr_quiz->getSetting('global_template_additional_results'); ?></h3>
<div class="wpvqgr-result-description">%%description%%</div>
</div>
</div>
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_afterresults')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_afterresults')); ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('displaysharing')): ?>
<div class="wpvqgr-sharing">
<?php if (!in_array('facebook', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-facebook" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_facebook_description'); ?>"><i class="fa fa-facebook-square" aria-hidden="true"></i> <?php echo __('Share on Facebook', 'wpvq'); ?></button>
<?php endif; ?>
<!-- Twitter -->
<?php if (!in_array('twitter', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-twitter" data-tweet="<?php echo $wpvqgr_quiz->getSetting('global_template_twitter'); ?>" data-mention="<?php echo $wpvqgr_quiz->getSetting('twittermention'); ?>" data-hashtag="<?php echo $wpvqgr_quiz->getSetting('twitterhashtag'); ?>"><i class="fa fa-twitter-square" aria-hidden="true"></i> <?php echo __('Share on Twitter', 'wpvq'); ?></button>
<?php endif ?>
<!-- VK -->
<?php if (!in_array('vk', $wpvqgr_quiz->getSetting('global_socialmedia_hide'))): ?>
<button class="wpvqgr-button wpvqgr-social-vk" data-title="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_title'); ?>" data-description="<?php echo $wpvqgr_quiz->getSetting('global_template_vk_description'); ?>"><i class="fa fa-vk" aria-hidden="true"></i> <?php echo __('Share on VK', 'wpvq'); ?></button>
<?php endif ?>
</div>
<?php endif; ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('playagain')): ?>
<button class="wpvqgr-button wpvqgr-playagain"><?php echo $wpvqgr_quiz->getSetting('customlabel_playagainbutton'); ?></button>
<?php endif; ?>
</div>
</div>
</div>
<?php if ($wpvqgr_quiz->getPageCounter() > 1 && in_array('bottom', $wpvqgr_quiz->getSetting('progessbar'))): ?>
<!-- Progress bar -->
<div class="wpvqgr-progress wpvqgr-progress-bottom progress">
<div class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<?php endif ?>
<div class="wpvqgr-a-d-s">
<?php echo do_shortcode($wpvqgr_quiz->getSetting('global_ads_after')); ?>
<?php echo do_shortcode($wpvqgr_quiz->getSetting('ads_after')); ?>
</div>
<?php if ($wpvqgr_quiz->getSetting('promote')): ?>
<div class="wpvqgr-promote">
<p>
<?php _e("This quiz has been created with", 'wpvq'); ?> WordPress Viral Quiz
</p>
</div>
<?php endif; ?>
</div> <!-- / #wpvqgr -->
</div> <!-- / container -->
<!-- Loading -->
<div class="row">
<div class="wpvqgr-loader">
<p>
<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i>
<span class="sr-only"><?php _e("Loading...", 'wpvq'); ?></span>
</p>
</div>
</div>
</div> <!-- / Bootstrap wrapper -->
I tried with dummy DIV element, but without success (to have it as an anchor, because explainer element is invisible).
Code samples I tried so far are:
$('wpvqgr-answer').click(function() {
$('html,body').animate({scrollTop: ('#autoscroll').offset().top - staticHeaderHeight}, 'slow');
return true;
});
And:
$('.wpvqgr-answer').click(function () {
$("html, body").animate({ scrollTop: $(el).closest(':visible').offset().top}, 400);
return true;
});
And, this was desperate act of self destruction:
$('.wpvqgr-answer').click(() => {
$('.wpvqgr-explanation').toggle('smooth', () => {
$('.wpvqgr-explanation').get(0).scrollIntoView();
});
});
I hope you have some kind of overview now, even in basic sense. Any guidance appreciated. Thank you
EDIT: Box creation conditions are within JS and parsed to HTML code, example below:
// Add explanation
var $explanation = $question.find('div.wpvqgr-explanation');
$explanation.find('div.wpvqgr-explanation-content').html(wpvqgr.vars.quiz.questions[question_id].wpvqgr_quiz_questions_explanation);
if (isRight)
{
$explanation.find('h3.wpvqgr-thats-right').show();
$answer.addClass('wpvqgr-right-answer');
}
else
{
$explanation.find('h3.wpvqgr-thats-wrong').show();
$answer.addClass('wpvqgr-wrong-answer');
$.each(rightAnswers, function(index, answer_id){
$question.find('.wpvqgr-answer[data-id=' + answer_id + ']').addClass('wpvqgr-right-answer');
});
}
$explanation.show();
}
else
{
$question.find('.wpvqgr-answer').removeClass('wpvqgr-selected-answer');
$answer.addClass('wpvqgr-selected-answer');
}
<div class="row"><div class="col-sm-12">
<div class="wpvqgr-explanation">
<center><h6>⇩ SCROLL DOWN TO CONTINUE ⇩</h6></center>
<h3 class="wpvqgr-thats-right"><?php echo $wpvqgr_quiz->getSetting('customlabel_right'); ?></h3>
<h3 class="wpvqgr-thats-wrong"><?php echo $wpvqgr_quiz->getSetting('customlabel_wrong'); ?></h3>
<div class="wpvqgr-explanation-content"></div>
</div>
</div>
</div>
Simple piece of code worked as charm for me, just enough to achieve functionality and in the same time not to complicate too much:
const goToTop = () => window.scrollTo(0, 950);
goToTop();
This is very quick and "clean" solution for one who does not need complicated function.
JQuery connected, AJAX probably works correctly, because when I change select in the console the values are correct. But the query to the database doesn't change. Checking var_dump($_POST['filter']) shows that there value from previous request.
If I wrap select in a form and send it via POST using submit button, the requests are sent.
Where can there be an error here?
And how to add a condition, so that when selecting "All" the query will just be to all items "SELECT * FROM orders, without the condition "WHERE?
<script>
$('#filter').change(function() {
$.ajax({
method: "POST",
url: "thispage.php",
data: {
filter: $("#filter").val()
},
success: function(response) {
console.log($("#filter").val())
}
});
});
</script>
<?php
require_once __DIR__ . "/database/database.php";
$item1 = $_POST['item1'];
$worker_name = $_POST['worker_name'];
$worker_company = $_POST['worker_company'];
$errors = [];
if (empty($item1)) {
$errors['item1'] = true;
}
if (empty($errors)) {
$sql = "INSERT INTO `orders`(`order_dish1`, `order_name_worker`, `order_company`) VALUES (:order1, :order_name_worker, :worker_company)";
$params = [
"order1" => $item1,
"order_name_worker" => $worker_name,
"worker_company" => $worker_company
];
$dbh->prepare($sql)->execute($params);
}
$order_dishes1 = [];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
// In this form it works
<form action="thispage.php" method="POST">
<select type="text" name="filter" id="filter">
<option value="*">All</option>
<?php
$sql = "SELECT * FROM `companies`";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<option value="<?php echo $row['name'] ?>">
<?php echo $row['name'] ?>
</option>
<?php } ?>
</select>
<button type="submit">submit</button>
</form>
<div class="orders__wrapper" id="result">
<?php
$company = $_POST['filter'];
var_dump($_POST['filter']);
$sql = "SELECT * FROM `orders` WHERE `order_company` = '$company'";
$rows = $dbh->query($sql);
foreach ($rows as $row) {
?>
<div class="order-items">
<div class="order-items__header">
<div class="order-items__wrapper">
<div class="order-items__number">
Order №: <?php echo $row['order_id'] ?> </div>
</div>
<div class="order-items__wrapper">
<div class="order-items__name">
<?php echo $row['order_name_worker'] ?> </div>
<div class="order-items__company">
Company:
<span>
<?php echo $row['order_company'] ?>
</span>
</div>
</div>
</div>
<div class="order-items__orders">
<div class="orders-item orders-item-1">
Order №1:
<span class="order1">
<?php echo $row['order_dish1'] ?>
</span>
</div>
</div>
</div>
<?php
$order_dishes1[] = $row['order_dish1'];
}
$content = ob_get_contents();
ob_end_clean();
?>
<div class="result__all" id="result__all">
<div class="result__all-company">
<?php echo $row['order_company'] ?>
</div><br>
<div class="result__all__wrapper">
<div class="result__all-view">
<div class="result__all-title">
Soups:
</div>
<?php
$count_dishes1 = array_count_values($order_dishes1);
foreach ($count_dishes1 as $key => $val) echo '<div class="result__all-item">' . $key . ' - ' . $val . ' шт.,</div>';
?>
</div><br>
</div>
</div>
<?= $content ?>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
I am attempting to 'check' the the 'AC:Front' box from a button click on the below website. I tried changing the checkbox to 'checked' and I also tried changing the encompassing to class="checked".
The goal is to eventually collect the inputted VIN, run it through a decoder and use the data to fill the page.
Here is the website
HTML
<div class="stm-single-feature">
<div class="heading-font">Comfort</div>
<div class="feature-single">
<label>
<input type="checkbox" value="A/C: Front" name="stm_car_features_labels[]"/>
<span>A/C: Front</span>
</label>
</div>
CSS
div.checker span.checked {
background-position: -16px 0; }
PHP
<?php
if ($items) {
if (!empty($id)) {
$features_car = get_post_meta($id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($items as $item) { ?>
<?php if(isset($item['tab_title_single'])): ?>
<div class="stm-single-feature">
<div class="heading-font"><?php echo $item['tab_title_single']; ?></div>
<?php $features = explode(',', $item['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
if (in_array($feature, $features_car)) {
$checked = 'checked';
};
?>
<div class="feature-single">
<label>
<input type="checkbox" value="<?php echo esc_attr($feature); ?>"
name="stm_car_features_labels[]" <?php echo $checked; ?>/>
<span><?php echo esc_attr($feature); ?></span>
</label>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php }
}?>
JavaScript
<script type="text/javascript">
jQuery(function($) {
$("#generateVin").on("click", function() {
var $checkbox = $("input[type=checkbox]").eq(1);
$checkbox.prop("checked", true);
$checkbox.parent().addClass("checked");
});
});
</script>
i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???
I would like to display multiple slideshow on one page from my website.
I'm using a repeater ACF to enter my images.
I'm not able to know in advance how many slideshows are going to be displayed
when one slideshow is displayed, everything works perfectly, but when 2 are displayed, It doesn't work anymore.
does anyone knows how I can fix it ?
here is a basic code without the repeater and with 2 slideshows :
http://jsfiddle.net/XRpeA/13/
<div id="slideframe">
<img class="image_news" src="http://s1.lemde.fr/image/2007/07/09/534x0/933544_5_aa6d_polynesie-bora-bora_0608bcead896ce3f59fc0e2fb3cc7435.jpg" />
<img class="image_news" src="http://production.slashmedias.com/main_images/images/000/005/357/IMAGE-PENSEE-HD-1_original_original_large.jpg?1372235419" />
<img class="image_news" src="http://images.telerama.fr/medias/2013/03/media_94814/une-image-un-film-l-auberge-de-dracula-1931,M106823.jpg" />
</div>
<br>
<div id="counter">image <span id="current">1</span> / <span id="total"></span></div>
<br><br>
<div id="slideframe">
<img class="image_news" src="http://s1.lemde.fr/image/2007/07/09/534x0/933544_5_aa6d_polynesie-bora-bora_0608bcead896ce3f59fc0e2fb3cc7435.jpg" />
<img class="image_news" src="http://production.slashmedias.com/main_images/images/000/005/357/IMAGE-PENSEE-HD-1_original_original_large.jpg?1372235419" />
<img class="image_news" src="http://images.telerama.fr/medias/2013/03/media_94814/une-image-un-film-l-auberge-de-dracula-1931,M106823.jpg" />
</div>
<br>
<div id="counter">image <span id="current">1</span> / <span id="total"></span></div>
and here is my code with the repeater :
http://jsfiddle.net/XRpeA/14/
<?php if(get_field('images')): ?>
<div id="counter_2"><span id="current">1</span> / <span id="total"></span></div>
<div id="slideframe">
<?php while(has_sub_field('images')): ?>
<?php if(get_sub_field('image') != ''){ ?>
<img class="image_news" src="<?php the_sub_field('image'); ?>"/>
<?php } ?>
<?php endwhile; ?>
</div>
<?php endif; ?>
thanks a lot
Ok, so I did it just for you as I promiced, thought I thought it will be faster :)
Result
http://skyloveagency.com/new/
(will remove tomorrow)
Fields:
photo_repeater - repeater
---photo_slider - repeater
------photo_block - image with URL output
Full script, not optimized but works perfectly
<?php
/**
* Template Name: Profiles2
*/
get_header(); ?>
<?php
// query
$args = array(
'post_type' => 'profiles',
'show' => 1
);
$wp_query = new WP_Query($args);
?>
<?php $random = 0;
if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<?php if(get_field('photo_repeater')): ?>
<?php while(has_sub_field('photo_repeater')): ?>
<?php $random++; ?>
<div id="slideframe<?php echo $random; ?>">
<?php if(get_sub_field('photo_slider')): ?>
<?php while( has_sub_field('photo_slider') ): ?>
<?php
$img_url = get_sub_field('photo_block');
$image = aq_resize( $img_url, 200, 200, true );
?>
<img class="image_news" src="<?php echo $image; ?>" alt="111" />
<?php endwhile; ?>
<?php endif; ?>
</div>
<br>
<div id="counter<?php echo $random; ?>">image <span id="current<?php echo $random; ?>">1</span> / <span id="total<?php echo $random; ?>"></span></div>
<script>
var count<?php echo $random; ?> = $('#slideframe<?php echo $random; ?> .image_news').length;
$("#total<?php echo $random; ?>").text(count<?php echo $random; ?>);
// set display:none for all members of ".pic" class except the first
$('#slideframe<?php echo $random; ?> .image_news:gt(0)').hide();
// stores all matches for class="pic"
var $slides<?php echo $random; ?> = $('#slideframe<?php echo $random; ?> .image_news');
$slides<?php echo $random; ?>.click(function () {
// stores the currently-visible slide
var $current<?php echo $random; ?> = $(this);
if ($current<?php echo $random; ?>.is($slides<?php echo $random; ?>.last())) {
$("#current<?php echo $random; ?>").text("1");
$current<?php echo $random; ?>.hide();
$slides<?php echo $random; ?>.first().show();
}
// else, hide current slide and show the next one
else {
$("#current<?php echo $random; ?>").text($current<?php echo $random; ?>.next().index()+1);
$current<?php echo $random; ?>.hide().next().show();
}
});
</script>
<br><br>
<?php endwhile; ?>
<?php endif; ?>
<?php endwhile; ?>
<?php get_footer(); ?>