Im making a sweetshop project for my apprenticeship and ive done some test runs and have got all my code working but then i get my brief and the prices are changed depending on the weight and have got decimal prices instead of whole E.G £0.0.1 i thought this wouldnt make a difference but im not sure whats stopping the plus and minus button from changing the decimal price.
<?php
foreach ($result as $key => $value) { ?>
<div class="col-md-4 inner-container">
<div class="card border">
<div class="column-image" style=" background-image: url(<?php echo ($value['image']); ?>" >
</div>
<h2><?= $value['sweet_name'] ;?></h2><br/>
<p>Price: £<?= $value['price'] ; ?></p>
<p>Weight: <?= $value['weight'] ; ?>g</p>
£<span id="prices"><?php echo ( $value['price'] ); ?></span><br/>
<span id="weight"><?php echo ( $value['weight'] ); ?></span> g<br/>
<button onclick="minus()"> - </button><span id="quantity"> 1 </span><button onclick="plus()"> + </button><br/>
<!-- runs the function addcookie in javascript and passes paramater id -->
<button class="column-button" onclick="addcookie(<?php echo $value['id']; ?>)">Add to basket</button>
</div>
<?php } ?>
<script>
// these varibles are to not get [object HTMLSpanElement]
var weight = <?php echo ( $value['weight'] ); ?>;
var price = <?php echo $value['price']; ?>;
function addcookie(id){
// element can be anything in HTML
// innerHTML gets anything inside the html tags E.G quantity = 1
var quantity = document.getElementById('quantity').innerHTML;
var id = <?php echo $value['id']; ?>;
// creates the cookie with a key and a value and also creates a path to be stored
// this means i can access it on any page E.G basket.php
document.cookie = "zzz_"+id+"_id="+id+"; ;path=/";
document.cookie = "zzz_"+id+"_quantity="+quantity+"; ;path=/";
document.cookie = "zzz_"+id+"_weight="+weight+"; ;path=/";
}
function plus(){
// parseint changes strings into intergers
document.getElementById('quantity').innerHTML = parseInt( document.getElementById('quantity').innerHTML) +1;
document.getElementById('prices').innerHTML = parseInt( document.getElementById('prices').innerHTML) +price;
document.getElementById('weight').innerHTML = parseInt( document.getElementById('weight').innerHTML) +weight;
}
function minus(){
if (document.getElementById('quantity').innerHTML > 1){
document.getElementById('quantity').innerHTML = parseInt( document.getElementById('quantity').innerHTML) -1;
document.getElementById('prices').innerHTML = parseInt( document.getElementById('prices').innerHTML) -price;
document.getElementById('weight').innerHTML = parseInt( document.getElementById('weight').innerHTML) -weight;
}
}
</script>
i'm just wondering what i'm doing wrong? i've tried changing my parseInt to a ParseDouble but there was no change at all.
You're nearly there. parseFloat is what you need. There's no such function as ParseDouble or parseDouble, so that was probably producing errors in your browser's Console (you didn't say whether you'd checked for those or not).
I've also added some calls to .toFixed so you don't end up with large trailing decimal places, but you can adjust that according to the level of accuracy / rounding you need.
Live demo:
var weight = 5.2;
var price = 3.5;
function addcookie(id)
{
// element can be anything in HTML
// innerHTML gets anything inside the html tags E.G quantity = 1
var quantity = document.getElementById('quantity').innerHTML;
var id = 22;
// creates the cookie with a key and a value and also creates a path to be stored
// this means i can access it on any page E.G basket.php
//document.cookie = "zzz_" + id + "_id=" + id + "; ;path=/";
//document.cookie = "zzz_" + id + "_quantity=" + quantity + "; ;path=/";
//document.cookie = "zzz_" + id + "_weight=" + weight + "; ;path=/";
}
function plus()
{
document.getElementById('quantity').innerHTML = parseInt(document.getElementById('quantity').innerHTML) + 1;
document.getElementById('prices').innerHTML = (parseFloat(document.getElementById('prices').innerHTML) + price).toFixed(2);
document.getElementById('weight').innerHTML = (parseFloat(document.getElementById('weight').innerHTML) + weight).toFixed(2);
}
function minus()
{
if (parseInt(document.getElementById('quantity').innerHTML) > 1) {
document.getElementById('quantity').innerHTML = parseInt(document.getElementById('quantity').innerHTML) - 1;
document.getElementById('prices').innerHTML = ( parseFloat(document.getElementById('prices').innerHTML) - price).toFixed(2);
document.getElementById('weight').innerHTML = ( parseFloat(document.getElementById('weight').innerHTML) - weight).toFixed(2);
}
}
<div class="col-md-4 inner-container">
<div class="card border">
<div class="column-image" style=" background-image: url(<?php echo ($value['image']); ?>">
</div>
<h2>
Something
</h2><br/>
<p>Price: £ 3.5
</p>
<p>Weight: 5.2g
</p>
£<span id="prices">3.5</span><br/>
<span id="weight">5.2</span> g<br/>
<button onclick="minus()"> - </button><span id="quantity"> 1 </span><button onclick="plus()"> + </button><br/>
<!-- runs the function addcookie in javascript and passes paramater id -->
<button class="column-button" onclick="addcookie(<?php echo $value['id']; ?>)">Add to basket</button>
</div>
Related
I have a little problem. I have a simple select field and get options from the database when the user clicks on any option I get an input box with the name of the last inserted record from the database, and I need to display the input box with the name of what the user selected not the last record. Code is bellow:
<div class="col-md-6 mb-3">
<label>Odaberite dimenziju produkta</label>
<select class="select2" name="size_id[]" multiple="multiple" id="selectBox" onchange="changeFunc();">
<?php
$get_sizes = "select * from sizes";
$sizes = mysqli_query($con,$get_sizes);
while($row_size = mysqli_fetch_array($sizes)){
$size_id = $row_size['id_size'];
$size_name = $row_size['productSize'];
$i++;
echo "<option value=".$size_name.">".$size_name."</option>";
} ?>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12 mb-3">
<div id="textboxcont" style="display: inline-flex; width: 100%;"></div>
<script type="text/javascript">
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues)
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}
</script>
</div>
I need when the user clicks on one of four available selected options to display selected inputs with different names. Now when users select any 1 or 2 or 3 available options they display only the last records from the database. Any help why?
You are having problem here..
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", "<?php echo $size_name; ?>");
i1.setAttribute("id", "<?php echo $size_name; ?>");
i1.setAttribute("placeholder", "Enter price for <?php echo $size_name; ?>");
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
Your $size_name var contains last value of the query data array that you looped already while adding options to the select.
You should not use that to set attribute while creating input.
You should use the values that you have collected in selectedValues.
You can either itarate through it or use array index like selectedValues[ i ] to set input attribute like below.
function changeFunc() {
document.getElementById('textboxcont').innerHTML = '';
var selectBox = document.getElementById("selectBox");
var selectedValues = Array.from(document.getElementById('selectBox').selectedOptions).map(el=>el.value);
//alert(selectedValues[0]);
for( var i = 0; selectedValues.length > i; ++i ) {
var i1 = document.createElement("input");
i1.setAttribute("type", "text");
i1.setAttribute("name", selectedValues[i]);
i1.setAttribute("id", selectedValues[i]);
i1.setAttribute("placeholder", "Enter price for " + selectedValues[i] );
i1.setAttribute("class", "form-control txtt");
// you may want to change this
// add the file and text to the div
document.getElementById('textboxcont').appendChild(i1);
}
}
The below script is for displaying countdown timing
Used code is here with a combination of php,javascript
Tried many ways but no use
<script>
function countdown(endT,callback,val) {
var val,days,hours,minutes,sec,timer;
end = new Date(endT);
end = end.getTime(); //Get initial Date in Milliseconds,
if (isNaN(end)) {
alert('# countdown.js # "Invalid Date", valid format- mm/dd/yyyy hh:mm:ss TT ');
return;
}
timer = setInterval(calculate,1000);//Timer to calculate remaining time
function calculate(){
var current = new Date();
var remaining = parseInt((end - current.getTime())/1000);//remaining seconds,
if (remaining <= 0){
clearInterval(timer);
days=0;
hours=0;
minutes=0;
sec=0;
display(days,hours,minutes,sec);
if (typeof callback === 'function' ) {
callback();
}
}else{
days = parseInt(remaining/86400);
remaining = (remaining%86400);
hours = parseInt(remaining/3600);
remaining = (remaining%3600);
minutes = parseInt(remaining/60);
remaining = (remaining%60);
sec = parseInt(remaining);
display(days,hours,minutes,sec);
}
}
//Function For displaying Results in HTML page with specific ID's
function display(days,hours,minutes,sec) {
var dl = days.toString().length;
if (dl == "1") {
sl = 2;
}else{
if (isNaN(dl)) {
sl = 3;
}
sl = dl;
}
d1="days";
d2=val;
d=d1.concat(d2);
h1="hours";
h2=val;
h=h1.concat(h2);
m1="minutes";
m2=val;
m=m1.concat(m2);
s1="seconds";
s2=val;
s=s1.concat(s2);
document.getElementById(d).innerHTML = ("00"+days).slice(-sl);
document.getElementById(h).innerHTML = ("0"+hours).slice(-2);
document.getElementById(m).innerHTML = ("0"+minutes).slice(-2);
document.getElementById(s).innerHTML = ("0"+sec).slice(-2);
}
}
</script>
<?php
for ($i = 6; $i <9; $i++)
{
$dates="2019-03-0$i 12:45:01";
?>
<script>
countdown('<?php echo $dates;?>',callback,'<?php echo $i;?>');
function callback(){
//alert('Your Id is Expired');
};
</script>
<div class="countDown" align="center">
<span id="days<?php echo $i; ?>">00</span> <!-- Remaining Days,id="days"-->
<span id="hours<?php echo $i; ?>">00</span> <!-- Remaining hours ,id="hours"-->
<span id="minutes<?php echo $i; ?>">00</span> <!-- Remaining minutes,id="minutes"-->
<span id="seconds<?php echo $i; ?>">00</span> <!-- Remaining secounds,id="secounds"-->
</div>
<?php
}
?>
First iterated value only assigned to all other loop ids...Instead of unique values
Loop have 3 iterations
First iteration value assigned first id
The first iteration value assigned to next two iterations..
Kindly help me to fix the issue..
Combination of php and javascript always confusing. It can be used in combination when creating dynamic elements on page load but not after page load.So you have to code in javascript for countdown. If there is need to access server variable (i.e php variable ) then you need Ajax request to access this variable.
So, I'm trying to create a filter for this list of stores, so only the ones with content that is equal to the value of the input box will display. Unfortunately, my filter does not work correctly. For one, whatever I type in the input box causes all of my store elements to add the 'display' class, which causes my items to receive the style 'display: none;'. Secondly, it's not updating every time a key is pressed.
HTML:
<li class="p-3 clearfix store display">
<div class='float-left w-50'>
<div class='mb-1'><strong>Store Number:</strong><span class="store-info">
<?php
if (strlen($row['store_num']) < 4) {
if (strlen($row['store_num']) == 3) {
echo '0' . $row['store_num'];
} else if (strlen($row['store_num']) == 2) {
echo '00' . $row['store_num'];
}
} else {
echo $row['store_num'];
}
?>
</span></div>
<div class='mb-1'><strong>Store Name: </strong><span class='store-info'><?php echo $row['store_name']; ?></span></div>
<div class='clearfix mb-1'>
<p class='float-left'><strong>Address: </strong></p>
<span class='d-block store-info float-left'><?php echo $row['store_street']; ?></span>
<br>
<span class='d-block store-info float-left'><?php echo $row['store_city']; ?>, <?php echo strtoupper($row['store_state']); ?> <?php echo $row['store_zip']; ?></span>
</div> <!-- mb-1 -->
</div> <!-- float-left -->
<div class="float-left w-50 clearfix">
<div class="d-inline float-right">
<div class='mb-1'>
<strong>Time Zone: </strong><span class='time-zone store-info'><?php echo strtoupper($row['time_zone']); ?></span>
</div>
<div class='mb-1'>
<strong>Current Time: </strong><time>3:45pm</time>
</div>
<div class='mb-1'>
<strong>Phone Number:</strong><span class='store-info'>
<?php
$phone = $row['store_phone'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
<div class='mb-1'>
<strong>Fax Number:</strong><span class='store-info'>
<?php
$phone = $row['store_fax'];
$area = substr($phone, 0, 3);
$prefix = substr($phone, 4, 3);
$line = substr($phone, 6, 4);
echo '(' . $area . ') ' . $prefix . '-' . $line;
?>
</span>
</div>
</div> <!-- d-inline -->
</div> <!-- float-right -->
</li> <!-- clearfix -->
JavaScript:
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
for(var i = 0; i < spans.length; i++) {
if (spans[i].innerText.toLowerCase() != data) {
store.classList.remove('display');
} else {
store.classList.add('display');
}
}
});
});
If I understand your question correctly, you could make the following changes to your javascript to resolve the issues you're facing. Please see comments in code for explaination of what's going on:
search.addEventListener('keyup', function (e) {
var query = e.target.value.toLowerCase();
if (search.value.length >= 0) {
search.classList.add('focused');
label.classList.add('focused');
} else {
search.classList.remove('focused');
label.classList.remove('focused');
}
// recommend performing this query in the keyup event to ensure
// that you're working with the most up to date state of the DOM
var stores = document.querySelectorAll(".store");
stores.forEach(function(store) {
// query .store-info from current store
var spans = store.querySelectorAll(".store-info");
// hide the store by default
store.style.display = 'none';
for (var i = 0; i < spans.length; i++) {
var storeInfoText = spans[i].innerText.toLowerCase();
// consider revising search logic like so
if (storeInfoText.indexOf(query) !== -1 || !query) {
// display the store if some match was found
store.style.display = 'block';
}
}
});
});
Link to working jsFiddle here
I think your issue with it showing everything is because of the add remove... if a store already has display it will re add it and then only remove it once where as if it doesn’t you will get an error so try toggle
var search = document.getElementById('search');
var stores = document.querySelectorAll('.store');
search.addEventListener('keyup', function (e) {
var data = e.target.value.toLowerCase();
stores.forEach(function(store) {
var spans = document.querySelectorAll('.store-info');
spans.filter(span=>{
if(span.innerText.toLowerCase().includes(data)){
store.classList.toggle('display');
}else{store.classList.toggle('display')
})
});
I am using js and php to build an app. I've used a foreach loop in php to create buttons for each row fetched from mysql table. Each button has a unique value (row id).
If someone clicks on of the buttons (each with unique id), there will be a total likes count that holds how many times a button is clicked.
If we have three buttons, and button 1 is clicked, then total likes will be increase by 1. if the same button is clicked again, then the value would decrease by 1.
However, if two buttons of different values are clicked, the total likes add.
When using js, I cant get each button id to pass to the js function loaded from the foreach loop. only the last button value loads to the js function.
Here is what i've tried. the js works but it doesnt apply to each button of the foreach loop.
My Code
<?php foreach($values as $value){
$value['button_id'];
<!-- button --->
<button id="button"
class="button-<?= $value['button_id']; ?>"
value="<?= $value['button_id']; ?>"
onclick="showUser(this.value)" >LIKE
</button>
<!-- button --->
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
Here is an illustration explaining what I mean
Thanks in advance
<script>
var likes = new Array();
function calc(value) {
if(likes[value] == 0 || !likes[value]) {
likes[value]=1;
} else {
likes[value]=0;
}
var sum=0;
for(i=0; i<likes.length; i++) {
if(likes[i]==1){ sum ++ }
}
document.getElementById("total").innerHTML = sum;
}
</script>
<div id=total>0 </div>
<?php
$values = [1,2,3]; //here you can generate values
foreach($values as $value){
?>
<button id="button"
class="button-<?php echo $value; ?>"
value="<?php echo $value; ?>"
onclick="calc(<?php echo $value; ?>)" >LIKE
</button>
<?php
} ?>
<script>
var i = parseInt(document.getElementById('button').value, 10);
var x = i;
function showUser(this.value) {
/// changing value //
if (x == i){
i++;
document.getElementById('button').value = i;
}
else {
i = x;
document.getElementById('button').value = i;
}
}
</script>
How to calculate using jquery or Javascript in Codeigniter as below requirement
I have 3 input element to calculate after user complete they form element :
1, Quantity
2, Unitprice
3, Total.
By Total = quantity * unitprice.
<td><?php echo form_input('quantity','',' class="form-control"')?></td>
<td><?php echo form_input('unitprice','',' class="unit form-control" placeholder="unit pricee"')?></td>
<td><?php echo form_label('','total','class="form_control"')?></td>
I try to write javascript like this
<script type="text/javascript">
$(document).ready(function () {
$('.unitprice').keyup(function () {
Calculate();
});
});
function Calculate() {
var quantity = document.getElementsByClassName("quantity").val();
var unitprice = document.getElementsByClassName("unitprice").val();
var total = quantity * unitprice;
$('.total').val(total);
}
</script>
But it is not work
Thanks advance!!!!
Try like this:
$(function(){
$('.qty, .unit').on('blur', function(e){
var qty = parseFloat( $('.qty').val() ),
unit = parseFloat( $('.unit').val() );
if( isNaN(qty) || isNaN(unit) ) {
$('.result').text('');
return false;
}
var total = qty * unit;
$('.result').text( total );
});
});
DEMO
Here's a basic example, since I was bored. Fiddle - http://jsfiddle.net/sgnl/44ts8ucf/1/
html
<input type="text" id="quantity" class="calc_element"> Quantity
<input type="text" id="unit_price" class="calc_element"> Unit Price
<div id="total"></div>
javascript
// get some IDs or classes on your elements to target them easily
var total = $('#total');
// bind an event that triggers on KEYUP
$('.calc_element').on('keyup', function(){
// when triggered get the values from the input elements
// via jQuery's '.val()' method
var quantity = $('#quantity').val() || 1;
var unit_price = $('#unit_price').val();
var result = (quantity * unit_price) + " total";
// set the innerHTML of the div to your calculated total
total.html(result);
});
YMMV, thats the jist of it, some tweaking will need to be down for your code.