different random number in each div - php

This is probably simple but I can't get it to work.
I have working code that inputs random number inside div but it inputs same random number in all divs on the page.
How can I input different random number in each div?
Here is my code:
<script>
var randomNumber = Math.random();
var num = Math.floor((randomNumber * 75) + 15);
jQuery('#sale').each(function() {
jQuery(this).find('.savings').append(num);
});
</script>
Yes I'm looping on # since class is inside, should I loop on class itself?
Here is the html:
<div class="col-md-6 itemcol">
<div class="">
<div id="sale" class="sale" style=""><span class="savings"></span>% OFF<br></div>
SOLVED. Here is the final code if someone else finds it useful, changed $ to jQuery and adjusted numbers to go between 15-75.
<script>
jQuery(document).ready(function() {
jQuery("#sale .savings").each(function(){
jQuery(this).text(createRandom());
});
function createRandom() {
var Num = Math.floor((Math.random() * (75 - 15) + 1) + 15 );
return Num;
}
});
</script>

from you code, i assume, you want to loop on all the div's having saving class and append different random number with each of them.Try the below code.
jQuery('.savings').each(function() {
var randomNumber = Math.random();
var num = Math.floor((randomNumber * 75) + 15);
$(this).append(num);
});
</script>

Its because you are storing a value in a variable, and print out the variable all the time without updating it in the loop.
<script>
var randomNumber = Math.random();
jQuery('#sale').each(function() {
var num = Math.floor((randomNumber * 75) + 15);
if(jQuery(this).hasClass('.savings')){
jQuery(this).append(num);
}
});
</script>
You could also do something like the following:
<script>
var randomNumber = Math.random();
jQuery('.savings').each(function() {
var num = Math.floor((randomNumber * 75) + 15);
jQuery(this).text(num);
});
</script>

Try this :
$(document).ready(function() {
$("#sale .savings").each(function(){
$(this).text(createRandom());
})
function createRandom() {
var Num = Math.floor((Math.random() * (75 - 15) + 1) + 15 );
return Num;
}
})
Final code :
$(document).ready(function() {
$("#sale .savings").each(function(){
$(this).text(createRandom());
})
function createRandom() {
var Num = Math.floor((Math.random() * (75 - 15) + 1) + 15 );
return Num;
}
})
.savings {
border: 2px solid red;
width: 200px;
height: 30px;
margin-bottom: 1px;
}
<div id="sale">
<div class="savings"></div>
<div class="savings"></div>
<div class="savings"></div>
<div class="savings"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Related

Unity simulator disable form inputs - Laravel

I'm making some modifications on my web, in the page were I'm doing the modifications has a Unity render where you can interact with. For some unknown reason the JS files needed for the render to work are like "disabling" the iputs of the form.
But if you inspect the element you can see that there is no attribute in either css or HTML to disable it.
I'm quite lost in this problem.
In the UnityProgress.js:
function UnityProgress(gameInstance, progress) {
if (!gameInstance.Module)
return;
if (!gameInstance.logo) {
gameInstance.logo = document.createElement("div");
gameInstance.logo.className = "logo " + gameInstance.Module.splashScreenStyle;
gameInstance.container.appendChild(gameInstance.logo);
}
if (!gameInstance.progress) {
gameInstance.progress = document.createElement("div");
gameInstance.progress.className = "progress " + gameInstance.Module.splashScreenStyle;
gameInstance.progress.empty = document.createElement("div");
gameInstance.progress.empty.className = "empty";
gameInstance.progress.appendChild(gameInstance.progress.empty);
gameInstance.progress.full = document.createElement("div");
gameInstance.progress.full.className = "full";
gameInstance.progress.appendChild(gameInstance.progress.full);
gameInstance.container.appendChild(gameInstance.progress);
}
gameInstance.progress.full.style.width = (100 * progress) + "%";
gameInstance.progress.empty.style.width = (100 * (1 - progress)) + "%";
if (progress == 1)
gameInstance.logo.style.display = gameInstance.progress.style.display = "none";
setTimeout(function() {
$('.simulator-loading').fadeOut();
}, 5000);
}
function scrollDown() {
window.scrollBy({
top: 200, // could be negative value
left: 0,
behavior: 'smooth'
});
}
function scrollUp() {
window.scrollBy({
top: -200, // could be negative value
left: 0,
behavior: 'smooth'
});
}
Blade (the section where it is used):
#include('includes.questions-form', ['familia'=> $familia]) //this is afected form
#include('includes.ayuda')
</article>
#endsection
#section('pagescript')
<script src="{{ mix('/js/solution-detail.js') }}"></script>
<script src="{{ asset('unity/XXX/TemplateData/UnityProgress.js')}}"></script>
<script src="{{ asset('unity/XXX/Build/UnityLoader.js')}}"></script>
<script>
var gameInstance = UnityLoader.instantiate("simulator", "{{ asset('unity/Marine/Build/GHWebGL.json')}}", { onProgress: UnityProgress});
</script>
#endsection
Thanks for your help

Calculate sum of dynamically adding input fields with jquery

I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();
This code is calculating sum of rendered rows not the new created rows
$(document).ready(function(){
$('.datepicker').datepicker();
var $inst = $('.inst_amount');
$inst_form = $('.inst_form');
$total_amount = $('#total_amount');
$total_price = $('#total_price');
total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
$(document).on('blur','.inst_amount', function(){
var total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
console.log(total);
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
});
});
move var $inst = $('.inst_amount'); to where you use it:
var total = 0,$inst = $('.inst_amount'); - actually don't even. See my code
Use commas to separate vars
DRY - Don't Repeat Yourself
give the class correctly and add the field to a container.
function sumIt() {
var total = 0, val;
$('.inst_amount').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('#total_price').html(Math.round(total));
$('#total_amount').val(Math.round(total));
}
$(function() {
// $('.datepicker').datepicker(); // not needed for this test
$("#add").on("click", function() {
$("#container input").last()
.before($("<input />").prop("class","inst_amount").val(0))
.before("<br/>");
sumIt();
});
$(document).on('input', '.inst_amount', sumIt);
sumIt() // run when loading
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="add" value="add" /><br/>
<form id="inst_form">
<div id="container">
<input type="text" class="inst_amount" value="4" /><br/>
<input type="text" class="inst_amount" value="" /><br/>
<input type="text" id="total_amount" value="0" />
</form>
</div>
<span id="total_price"></span>
This code will only calculate total of all the rows which were available when page was loaded. You need to call the same code to make the total again when you are adding a new row. Basically on click of add row you need to re-calculate.
Put these code outside the $(document).ready
$(document).on('blur','.inst_amount', function(){
var total = 0;
$.each($inst, function(index, val) {
var val = ($(this).val() == "") ? 0 : $(this).val();
total = total + parseFloat(val);
});
console.log(total);
$total_price.html(Math.round(total));
$total_amount.val(Math.round(total));
});
because at a time of $(document).ready , new row is not added

Rich snippets: ratings called by javascript do not appear in Google

I implemented a stars rating system on my one page html site. The system uses jQuery, AJAX and PHP. I found the code here and it works well regarding the storage of the ratings and the updating of the votes.
This is the Javascript code:
// STARS
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
// can't use 'this' because it wont contain the updated data
set_votes($(this).parent());
}
);
// This actually records the vote
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text(votes);
$(widget).find('.avg_votes').text(exact);
}
// END STARS
There is a PHP script for storing and update the ratings:
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = './ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
# Get the value of the vote
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
# Update the record if it exists
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
# Create a new one if it doesn't
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
# ---
# end class
}
And the ratings are obtained through this code inside my html page:
<div class='movie_choice'>
<div id="r1" class="rate_widget">
<div class="star_1 ratings_stars"></div>
<div class="star_2 ratings_stars"></div>
<div class="star_3 ratings_stars"></div>
<div class="star_4 ratings_stars"></div>
<div class="star_5 ratings_stars"></div>
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
<div class="avg_votes" style="display: table-cell; float: left;" itemprop="ratingValue"></div><div style="float:left;">/</div><div itemprop="bestRating" style="float:left;">5</div><div style="float: left;">, </div><div class="total_votes" style="display: table-cell; float:left;" itemprop="ratingCount"></div><div style="width: 200px;"> voti</div>
</div>
</div>
</div>
The method works and show the correct average ratings and the total number of votes. The problem is that Google does not recognize the ratingValue. In the testing tool for structured data, Google says me that "ratingValue field can't be empty". In other words, for Google the line of code <div class="avg_votes" style="display: table-cell; float: left;" itemprop="ratingValue"></div> means that ratingValue is empty, although the rating is correctly showed in the page.
I suppose the problem is that this method is based on jQuery and my page is in html, but I can't find the solution for this issue.
Do you know the source of the problem, please?
Google doesn't run javascript when indexing your webpage, so all it will see is the empty html elements on the page and not the rating (since the rating is generated by javascript). If you want google to see the rating, you will need to generate the correct html on the server when you serve the page. This way, google will see the html with the ratings.

How can I display value of a div with a button click?

I am currently working with a wmd editor and jQuery-UI tabs. I have created an ajax/js function that will submit (when next button is clicked) the wmd-preview value and then php echo the result in tab 2. The problem is that I am not getting any results displayed. I am not looking for the textarea value but the div #wmd-preview value. How can I display the value of the div wmd-preview through my ajax/function?
JS
<script>
$(function () {
var $tabs = $('#tabs').tabs({
disabled: [0, 1],
select: function () {
$.ajax({
type: "POST",
url: "post_tabs.php",
data: {
"wmd": $("#wmd-preview").val(),
},
success: function (result) {
$("#tab-2").html(result);
}
});
}
});
$(".ui-tabs-panel").each(function (i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab').click(function () {
var currentTab = $('#tabs').tabs('option', 'selected');
if (
(
currentTab == 0 && /*(B)*/
$.trim($('#wmd-input').val()).length > 0
)
) {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
} else {
switch (currentTab) {
case 0:
alert('Please fill out all the required fields.', 'Alert Dialog');
break;
}
}
console.log("preventing default");
return false;
});
$('.prev-tab').click(function () {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex).tabs('select', tabIndex).tabs("option", "disabled", [0, 1]);
return false;
});
});
</script>
PHP
<?
if (isset($_POST['wmd'])){
$wmd = $_POST['wmd'];
echo ('<div id="text_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$wmd.'</span></div>');
}
?>
HTML
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input" name="wmd-input" cols="92" rows="15" tabindex="6"></textarea>
<div id="wmd-preview"></div>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>
PHP code should start with <?php , yours start with <? which is incorrect.
When you see PHP code presented as text - it should tell you it is not running, this is why you keep getting output like '.$wmd.''); } ?> instead of real PHP echo output.
The other comment still stands as well - you should either use $("#wmd-preview").html() or $("#wmd-input").val() but you cannot use val on divs, it does not work.
In this scenario $("#wmd-input").val() is the better choice just because this is the reason input fields exist - to get input.
Let me know if there are more questions I can help with.

Animating a div height adjustment using javascript

I'm still a newbie when it comes to javascript but I am having trouble animating a div that I want to essentially slide up over an image from the bottom when a user runs their cursor over it. I have had success using an almost identical code to fade a div in and out of view, but for some reason it does not want to work in this context.. Here is the html/php side of it:
echo '
<div class="still" style="clear:left">
<div class="thumbnail" onmouseover="show_title('.$work['position'].');" onmouseout="hide_title('.$work['position'].');">
<div class="still_title" id="still_title'.$work['position'].'">
<br>'.$work['title'].'
</div>
<img src="'.$work['thumbnail'].'" class="still_img">
</div>
<div class="description"><p>'.$work['description'].'</p>
</div>
</div>
';
And here is the javascript that I'm having an issue getting to function properly..
var i = 0;
function show_title(position) {
var titledelay = setInterval(show_title_animation(position),30);}
function show_title_animation(position) {
still_id = "still_title" + position;
title_position = document.getElementById(still_id);
while (i<100) {
i++;
title_position.style.height = i + "px";
}
if (i==100) {
alert(title_position);
clearInterval(titledelay);
}
}
Edit: It works now but it isn't resetting after it completes the loop..
var i = 0;
function show_title(position) {
var titledelay = setInterval(function(){ show_title_animation(position); }, 10);
}
function show_title_animation(position) {
still_id = "still_title" + position;
title_position = document.getElementById(still_id);
while (i<50) {
i++;
title_position.style.height = i + "px";
break;
}
if (i==50) {
clearInterval(titledelay);
i=0;
}
}
The problem is with the line
var titledelay = setInterval(show_title_animation(position),30);
Instead of passing a function with parameter, you should only pass in a function reference, like
var titledelay = setInterval(show_title_animation, 30); // This would require position declared as global variable outside the scope of the function
or
var titledelay = setInterval(function(){ show_title_animation(position) }, 30);

Categories