This is my html part where I use coupon input
IF need more code I'll provide
Enter Coupon Code
<input type="text" class="form" name="couponadd" id="couponadd" placeholder="Enter Your Coupon Code" oninput="myFunction()" style="width: -moz-available;" />
Oninput I am getting the coupon code in script
<script>
function myFunction() {
var getcoupon = document.getElementById("couponadd").value;
var aftercoupn=0;
if coupon code is gold then less 15 from total
if(getcoupon == 'gold')
{
var aftercoupn = 15;
document.getElementById("aftercoupan").innerHTML = '- $' + aftercoupn;
alert('minus 15 dollers');
}
if coupon code is silver then less 10 from total
else if(getcoupon == 'silver')
{
var aftercoupn = 10;
document.getElementById("aftercoupan").innerHTML = '- $' + aftercoupn;
alert('minus 10 dollers');
}
else
{
}
}
</script>
Iam getting price from php code loop
echo "<ul id='sub'>";
if($Seats == null){
echo '<li class="BlankSeat" ></li>';
}
elseif($ticketType=='PINK' && $ticketType == $_GET['type']){
echo '<li class="pink" id="pink" data-price="100" title="Row'.$Seats.'" name="'.$RowName.'" value="'.$Seats.'"></li>';
}
else{
echo '<li class="orange" id="orange" data-price="200" title="Row'.$Seats.'" name="'.$RowName.'" value="'.$Seats.'"></li>';
}
}
echo "</ul>";
script code from get price on click of li
var total =0;
var counter = 0;
var price=0;
$('li').click(function(e) {
var price = $(this).attr('data-price');
if click something
{
counter++;
}else
{
counter --;
}
how can i use coupon code value here in total
var total = parseFloat(price * counter);
document.getElementById('demoPrice').innerHTML = '$' + total;
}
});
Update aftercoupn variable on text input, then use it on li's on click like
var total = 0;
var counter = 0;
var price = 0;
var aftercoupn = 0;
$('li').click(function(e) {
$('li').removeClass('active');
$(this).addClass('active');
var price = $(this).attr('data-price');
if (price) { // I'm not sure with the counter variable here
counter++;
} else {
counter--;
}
var total = parseFloat(price * counter);
$('#demoPrice').text('$' + (total-parseInt(aftercoupn)));
});
function myFunction() {
var getcoupon = $("#couponadd").val(),
txt='Invaild Coupon';
if (getcoupon == 'gold') {
aftercoupn = 15;
txt = '- $' + aftercoupn;
console.log('minus 15 dollers');
counter=0;
} else if (getcoupon == 'silver') {
aftercoupn = 10;
txt = '- $' + aftercoupn;
console.log('minus 10 dollers');
counter=0;
}
$('li.active').length && $('li.active').trigger('click');
$("#aftercoupan").text(txt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form" name="couponadd" id="couponadd" placeholder="Enter Your Coupon Code" oninput="myFunction()" style="width: -moz-available;" />
<div id="aftercoupan"></div>
<ul id='sub'>
<li class="BlankSeat" data-price="0">Blank</li>
<li class="pink" id="pink" data-price="100" title="Row10" name="pink" value="10">Pink</li>
<li class="orange" id="orange" data-price="200" title="Row20" name="orange" value="20">Orange</li>
</ul>
<div id="demoPrice"></div>
I assume you're using price as a global variable. Then on click of li you should be updating that variable. So, you'll be able to have the price set on li click from other places ( I think that is what you're trying to achieve).
var total = 0, price, counter = 0;
$('li').click(function(e) {
price = parseFloat($(this).attr('data-price'));
// Do your other stuffs if you want
});
Then at other places you can get this price set after li click.
total = price * counter;
document.getElementById('demoPrice').innerHTML = '$' + total;
The whole thing is written in an assumption of your need. Correct me if I've thought it wrong or misunderstood somewhere
Related
I am facing an issue where the for loop loops properly to display a table in php when Google Charts is not used and when Google Charts is implemented on the page, the table only loops twice. I know this because I've echoed the count($arr) and echo the word LOOPED. My count shows 9 but it will only loop twice.
The google chart I am using is the pie chart and when this pie chart becomes really huge, where there are many slices, this would occur. What's weird is the Google Chart isn't inside this for loop.
for ($i = 1; $i < count($arr); $i++){
print_r(count($arr));
echo "LOOPED";
$splitwords = explode("ON", ($arr[$i]));
<td>$splitwords[0]</td>
<td>$splitwords[1]</td>"; }
This is the function being called.
function retrievepieCharts(minnumber,hournumber,daynumber){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawminuteChart);
google.charts.setOnLoadCallback(drawhourChart);
google.charts.setOnLoadCallback(drawdayChart);
function drawminuteChart() {
var data = google.visualization.arrayToDataTable([
['Timing', 'Times'],
<?php
for ($i = 0; $i < count($minuteArray); $i++) {
$firstArraywithin10mins = $minuteArray[$i];
$firstDATEtoRetrieve = $firstArraywithin10mins[0];
$firstTimingtoRetrieve1 = $firstArraywithin10mins[1];
$firstTimingtoRetrieve = $firstDATEtoRetrieve . " ". $firstTimingtoRetrieve1;
$totalCountwithin10mins = count($firstArraywithin10mins)-1;
echo "['$firstTimingtoRetrieve', $totalCountwithin10mins],";
}
echo" ]);";
?>
var mintitle = "Logon Fails > 5 within " + minnumber + " minute(s)";
var hourtitle = "Logon Fails > 5 within " + hournumber + " hour(s)";
var daytitle = "Logon Fails > 5 within " + daynumber + " day(s)";
var options = {backgroundColor: 'transparent',chartArea:
{left:0,top:90,width:"90%",height:"90%"}
,height: 450
,width: 450,
title: 'Logon Fails > 5 within '+ minnumber +' minutes (Likely to be automated brute force)'
};
var minutechart = new google.visualization.PieChart(document.getElementById('piechart'));
minutechart.draw(data, options);
function selectminuteHandler() {
var selectedItem = minutechart.getSelection()[0];
if (selectedItem) {
var topping = data.getValue(selectedItem.row, 0);
var date = new Date(topping).toLocaleDateString("en-US");
var options = { hour12: false };
var time = new Date(topping).toLocaleTimeString('en-US', options);
var rows = document.querySelectorAll('#csv_table tr');
$allRows = $('#csv_table tr');
$allData = $('#csv_table td');
row1 = $allRows.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == date;
});
row2 = $allData.filter(function(){
return $.trim($(this).find('td').eq(1).text()) == time;
});
index = $allRows.index(row1);
var table = document.getElementById("csv_table");
row = table.rows[index];
for (var i = 0, row11; row11 = table.rows[i]; i++) {
for (var j = 0, col; col = row11.cells[j]; j++) {
row11.cells[j].style.backgroundColor = "";
}}
rows.forEach(row => row.classList.remove('active'))
for (var j = 0, col; col = row.cells[j]; j++) {
var timeintable = row.cells[j].innerHTML.slice(12,20);
var target = new Date("1970-01-01 " + time);
var target2 = new Date("1970-01-01 " + timeintable);
timedifferences = target - target2;
var minuteVal = timedifferences / 60000;
if (minuteVal< 0){
minuteVal = minuteVal * -1;
}
if (minuteVal < minnumber){
row.cells[j].style.backgroundColor = "yellow";
document.getElementById('msg_div').innerHTML = hourtitle;
rows[index].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
else{
row.cells[j].style.backgroundColor = "";
}
}
}
}
google.visualization.events.addListener(minutechart, 'select', selectminuteHandler);
}
This is the part where the function is being called. The $minData and $hourData is retrieved when the user clicks on the submit button through a form.
if (isset($minData) and isset($hourData)){
echo "<script type='text/javascript'>retrievepieCharts('$minData', '$hourData', '$dayData');
</script>"
;
}
This is the form which takes in the $minData and $hourData. I've tried changing the $minData and $hourData values and every time I changed it, the table loops differently. I've also tried to remove the submit button to see if that was causing the issue but the result is the same without the submit.
<form id="differencesnumber" method="POST">
<label for="mindiff">Minutes Differences</label>  
<input type="number" id="mindiff" name="mindiff" style="width:50px;" min="0"
oninput="validity.valid||(value='');"required>
<br>
<label for="hourdiff">Hours Differences</label>  
<input type="number" id="hourdiff" name="hourdiff" style="width:50px;" min="0" oninput="validity.valid||(value='');"required>
<br>
<input type="submit" value="Get PieCharts">
</form>
The codes are over 1000 lines and if anyone needs the entire code, do inform me.
Anyone knows what is the bug? I've been trying to debug this for days but to no avail.
I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>
I have the following codes that generate checkboxes from database
< table class="table">
< thead>
< /thead>
< th>
<?php
$oaNamesQuery = "SELECT DISTINCT oaName FROM oaDetails";
$oaNamesQueryExecute = mysqli_query($conn, $oaNamesQuery);
while($oaNamesQueryRow = mysqli_fetch_array($oaNamesQueryExecute)){
$oaName = $oaNamesQueryRow['oaName'];
echo '<div class = "checkbox-group" required style="float:left; margin-right: 25px;"> <input class="checkBoxes" type="checkbox" id="checkBoxArray" name="checkBoxArray[]" value="'.$oaName.'"> '.$oaName.'</div>';
}
?>
< /th>
< /table>
There is another input box as below whereby input type is number
<div class="col-sm">
<label for="numberOfShiftPerDay">Number</label>
<input type="number" class="form-control" id="numberOfShiftPerDay" name="numberOfShiftPerDay" placeholder="No: " onchange="disablingRoutine()" min="1" max="4">
</div>
Example UI as below
When I enter some number, there will be a drop down menu appear according to the number I entered. Eg: If keyed in 1, there will be one drop down list will appear as below using jQuery 'OnChange'. The UI will be as below
What I Need
I need the drop down menu options to be based on user selected checkboxes. Eg: If the user selected checkboxes X, Y and XX, then these drop down list should show X, Y and XX. Can someone help me how to do this?
Edit 1
Added Javascript function on the change routine as suggested by stackoverflow member. But now having duplicate issues. Below the code that I changed
if ($("#numberOfShiftPerDay").val() == 1) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift1').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 2) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift2').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 3) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift3').append('<option>' + cval + '</option>')
});
} else {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift4').append('<option>' + cval + '</option>')
});
}
You can get the selected checkbox values and append to your dropdown list in your onchange function.
Try this:
function disablingRoutine()
{
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
$('#dropdownID').append('<option>'+cval+'</option>')
});
}
Edit 2
function disablingRoutine()
{
cdata = '';
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
cdata += '<option>'+cval+'</option>';
});
$('#dropdownID').html(cdata)
}
I have a script that calls to a Database to get Autocomplete data.
Once the specific Autocomplete data (Item Name) has been chosen a few other fields are populated, namely: Item Code, Price & Quantity.
When the quantity is changed the Lines Total field changes to "Quantity * Price" total.
There is the option to carry on adding rows Dynamically and autocomplete each in the same fashion ... there is a Grand Total that adds each line total together.
My issues are that the grand total only changes when the Quantity is changed, it should load on the focus of Price in each line - also, removing a line does not remove that spcific Line Totals ammount from the Grand Total and if you change the very first lines quantity (only the first line is affected) it re-sets the Grand total to anything that line has now added up to ... Please can someone look at my code.
The live version is at
http://cardoso.co.za/form/
You can also get the files there too if you browse to
http://cardoso.co.za/form/form.zip
Any and all help is greatly appreciated!!!
Edit here's some code from the entire script:
var $itemsTable = $('#itemsTable');
var rowTemp = [
'<tr class="item-row">',
'<td><a id="deleteRow"><img src="images/icon-minus.png" alt="Remove Item" title="Remove Item"></a></td>',
'<td><input name="itemType" class="itemType" id="itemType" tabindex="1" style="width:350px;"/></td>',
'<td align="center"><input name="itemCode" class="itemCode" id="itemCode" readonly="readonly" style="width:60px;" tabindex="-1"/></td>',
'<td align="center"><input name="itemQty" class="itemQty" id="itemQty" tabindex="2" style="width:40px;" maxlength="4" value=""/></td>',
'<td width="14%" align="center"><input name="itemPrice" class="itemPrice" id="itemPrice" readonly tabindex="-1"/></td>',
'<td width="17%" align="right"><input name="itemTotal" class="itemTotal" id="itemTotal" readonly tabindex="-1"/></td>',
'</tr>'
].join('');
$('#addRow').bind('click',function(){
var $row = $(rowTemp);
var $itemType = $row.find('#itemType');
var $itemCode = $row.find('.itemCode');
var $itemPrice = $row.find('.itemPrice');
var $itemQty = $row.find('.itemQty');
var $itemTotal = $row.find('.itemTotal');
if ( $('#itemType:last').val() !== '' ) {
$row.find('#itemType').autocomplete({
source: 'item-data.php',
minLength: 1,
select: function(event, ui) {
$itemType.val(ui.item.itemType);
$itemCode.val(ui.item.itemCode);
$itemPrice.val(ui.item.itemPrice);
$itemTotal.focus().val(ui.item.itemPrice);
$itemQty.focus().val(1);
$itemQty.keyup(function() {
var Quantity = $itemQty.val();
var Prices = $itemPrice.val();
var ItemsTotal = Quantity * Prices;
$itemTotal.val(ItemsTotal.toFixed(2));
var Tsum = 0;
$('.itemTotal').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
Tsum += parseFloat(this.value);
$('#toTally').val(Tsum.toFixed(2))
}
});
});
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.itemType + "</a>" )
.appendTo( ul );
};
$('.item-row:last', $itemsTable).after($row);
$('#minusRow').show();
$('#resetTable').show();
$($itemType).focus();
}
return false;
});
I have implemented the Array, Will post this instead soon, once I get it to work with ID's and Classes without jamming.
I solved the issue by doing the following :
( function($) {
var pounter = 1;
$(document).ready(function(){
var qounter = 1;
var trounter = 1;
//Count each instance and add number to Name
$row.find('._ext_price_total_html').each(function() {
$(this).attr({
'name': function(_, name) {
return name + pounter },
});
pounter++;
})
$row.find('.quantitys').each(function() {
$(this).attr({
'name': function(_, name) {
return name + qounter },
});
qounter++;
})
$('#quantity', function(){
var Tsum = 0;
$('[id^="_ext_price_total_html"]').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
Tsum += parseFloat(this.value);
}
$('.toTally').val(Tsum.toFixed(2))
})
})
$('#quantity').change(function(){
var Tsum = 0;
$('[id^="_ext_price_total_html"]').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
Tsum += parseFloat(this.value);
}
$('.toTally').val(Tsum.toFixed(2))
})
})
$('#quantity').keyup(function(){
var Tsum = 0;
$('[id^="_ext_price_total_html"]').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
Tsum += parseFloat(this.value);
}
$('.toTally').val(Tsum.toFixed(2))
})
})
//adjust/subtract from total when removeing row
$('#deleteRow').live('click',function(){
var delAsk = confirm('Remove this item?');
if (delAsk)
{
$(this).parents('.jshop_prod_cart').remove();
var Tsum = 0;
$('[id^="_ext_price_total_html"]').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
Tsum += parseFloat(this.value);
}
$('.toTally').val(Tsum.toFixed(2))
})
}
else
{
('cancel');
}
});
I have got a ordered list
<li id="prev">
<a href="#fragment-1>Next</a>
</li>
I want to increment the href value to
<a href="#fragment-1">...
<a href="#fragment-2">...
<a href="#fragment-3">...
<a href="#fragment-4">...
When the next is clicked it should stop from 4 and return to 1 allso is it possible with javascript at all
Thank you
Give your link an id first to make it easier to select.
Then,
document.getElementById('the_id_here').addEventListener('click', function(e) {
var n = e.target.href.split('-')[1] * 1 + 1;
if (n > 4)
n = 1;
e.target.href = e.target.href.split('-')[0] + '-' + n;
}, false);
Example: http://jsbin.com/ajegaf/4#fragment-1
Not exactly what you want but should be close enough to aim you in the right direction, check http://jsfiddle.net/pj28v/
<ul id="list"></ul>
Next
$(function() {
var $list = $('#list'),
count = 4,
i = 0,
cur = 0;
for (; i < count; i++) {
$list.append('<li>frag' + i + '</li>');
}
$('a', $list).eq(0).css('color','red');
$('#next').click(function(ev) {
ev.preventDefault();
cur++;
if (cur >= count) cur = 0;
$('a', $list).css('color','blue').eq(cur).css('color','red');
});
});
A jQuery solution:
$(document).ready(function(){
$('#prev a').click(function(){
var href = $(this).attr('href');
var num = parseInt(href.substr(href.indexOf('-') + 1));
if(num == 4)
{
num = 1;
}
else
{
num++;
}
$(this).attr('href', '#fragment-' + num)
});
});
http://jsfiddle.net/UYDdB/
A solution similar to Delan's one but with jQuery and without the usage of a test. http://jsfiddle.net/GZ26j/
$('#next').on('click', function(e) {
e.preventDefault();
href = $(this).attr('href');
var n = href.split('-')[1] * 1 + 1;
n = n%5;
e.target.href = href.split('-')[0] + '-' + n;
});
Edit:
This solution makes the counter start at 0 and not 1
use a hidden field to hold the value, and an onclick function to increase it and submit the form. SEE: How can I increase a number by activating a button to be able to access a function each time the button is increased?
<?
if(!isset($_GET['count'])) {
$count = 0;
} else {
$count = $_GET['count'];
}
?>
<script type='text/javascript'>
function submitForm(x) {
if(x == 'prev') {
document.getElementById('count').value--;
} else {
document.getElementById('count').value++;
}
document.forms["form"].submit();
}
</script>
<form action='hidfield.php' method='get' name='form'>
<input type='hidden' name='count' id='count' value='<?php echo $count; ?>'>
</form>
<input type='submit' name='prev' value='prev' onclick="submitForm('prev')">
<input type='submit' name='next' value='next' onclick="submitForm('next')">