Create an infinite loop on field value - javascript

So im creating a shop on bigcartel and i want to add a free delivery option. but they currently dont allow you to add it to spercific countries. I am currently adding coding to show a div or alert the user when their total is over £85 and they select UK as their desitination.
ATM i think my code wont loop.. well it dont seem to :/
I need it to loop so that it checks the value of the total price when customers add or subtract items .. whicvh would + or - the total amount.
i HAVE
var amount = {{ cart.total }} ;
var country = {{ store.country | country_select }};
t=setTimeout("checkprice()",10);
function checkprice()
{
if(amount >= 85 || country = 45 )
{
alert('OVER 85!') ;
}
else
{
alert('monkeys')
}
}
EDIT! 08/Feb/12
as suggested by #kolink: i have come up with this,,,
//----get variables--
var amount = {{ cart.total }};
var moose = document.getElementById("country");
function freedel()
{
if (moose = 42 || amount >= 85 )
{
document.getElementById("moose").style.visibility='visible';
}
else
{
alert('WRONG!')
}
}
the HTML being:
<div id="moose" style="visibility:hidden;"> dfgsdgfdsg</div>
and
<h3 id="cart_price" onChange="freedel()">{{ cart.total | money_with_sign }}</h3>

You tell it to check the price 10 milliseconds after the page loads, then you never tell it to run again.
And if your code worked, it would show the alert, then another 10 milliseconds later (which is nowhere near enough time to fix the issue).
What you should do is add checkprice(); to your code wherever you update cart.total or store.country. Maybe an onChange event can help you there.
As a side note, never ever use a string in setTimeout. Pass the function itself (ie. setTimeout(checkprice,10);) or an anonymous function (is. setTimeout(function() {checkprice();},10); instead.

Related

jQuery: How do I check a number from string?

there is a class named:
<div class="level_11 price_level" style="display: block;">
I have a script that runs a browser function.
But I want to run this only when my number in the script is lower than the number from the "level_" div.
I have no idea how to do this.
Well, there are everytime another number. Sometimes level_4, sometimes level_18, etc.
I need to check the number and say if my number is lower then the number from the level_, then run the script.
let setLevel = 3; // Change this to set the building level. Example: let Level = 20 //
let Level = setLevel -1; // Don't touch this //
let logLevel = Level +1; // Don't touch this //
console.log(`Success ✓ - ${IBuilding.length} buildings left`);
$.each(IBuilding, function(Index, Entity) {
let BuildingMissing = IBuilding.length - (Index + 1);
window.setTimeout(function() {
$.get(`/buildings/${Entity.id}/expand_do/credits?level=${Level}`)
console.log(`${BuildingMissing > 0 ? BuildingMissing : 'Success ✓ - last building successfully expanded to level: ' + logLevel }`);
}, Index * 250);
});
});
Basically the script request all sites, and every site have another "level_".
On the sites where the "level_" number is higher than the number in my variable, then dont run the script at the site. but run the script at the sites where my number is higher then the "level_"
Can anyone help me out? :/
You can get the level number like this:
let classname = $("div[class^='level']").attr("class").split(" ").filter(getClass);
function getClass(value) {
return value.startsWith("level_");
}
let level = classname.toString().substr(6);
console.log(level);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="level_11 price_level" style="display: block;">
I found this on link /buildings/ID/:
current level of building
Maybe I can check the Level from there?
The HTML section for that is:
<dd>
13
Ausbauen
</dd>

show hide on logic js

I have some logic
$("#finish-button").click(function () {
$(".hidebuttonvresults").hide();
$(".showbuttonvresults").show();
});
This works for most of my pages, however one page does not have #finish-button. The only unique is id is #question-number but I only want this action to happen when the ID prints Question 15 of 15.
Any idea how to alter my logic to include this extra factor? I was trying
var str = $('#question-number').html();
if (str.indexOf("Question 40 of 46") !== -1) {
$(".hidebuttonvresults").hide();
$(".showbuttonvresults").show();
}
but it does not work

JavaScript if statement: apply when a certain value changes to another certain value

How do I write an if statement so that it applies only when Value A changes to Value B in a select box? https://jsfiddle.net/mademoiselletse/gv0ohdzv/1/
I have the following select box for "miles" and input box for "residual":
<div class="item_div"><label>Miles:</label>
<select id="miles">
<option value="10000">10,000</option>
<option value="12000" selected>12,000</option>
<option value="15000">15,000</option>
</select>
</div>
<div class="item_div">
<label>Residual: </label>
<input type="number" id="resP" class="rmVal" value="52"> %
</div>
<div>
<label>Result (10000*Residual)</label>
<input id = "result"></input>
</div>
I would like to add 1 to the miles <input> value if the user changes from 12000 to 10000. If the user changes from 10000 to 15000, I would like to subtract 3. If the user then changes from 15000 to 120000, I would like to +1 and so on.
The residual values for corresponding miles are:
10000 miles: 53%
12000 miles: 52%
15000 miles: 50%
The reason I wanted to make the residual change based on the miles change is that later on, I want the user to be able to manually change the residual value and adjust the residual value based on the miles.
I tried to following code to +1 when the $("#miles") changes from 12000 to 10000 and -2 if it changes from 12000 to 15000 (line 13-26):
if (miles.val() == "12000") {
miles.change(function() {
if (miles.val() == "10000") {
resN = resN +.01;
resP.val(parseFloat(resP.val())+1);
calculate();
}
else if (miles.val() == "15000") {
resN = resN -.02;
resP.val(parseFloat(resP.val())-2);
calculate();
}
})
};
I repeated the if statement for the other miles changes (line 27-55). However, the code only works correctly for the 1st and 2nd miles change. The 3rd time on is messed up. I was wondering how I may correct my code and whether there is an easier way to accomplish this. Thank you very much! I much appreciate it!
Store the previous value in a variable.
var cur_miles; // set default value of drop down
function milesChange (){
switch(cur_miles){
case "10000":
switch(miles.val()){
case "20000":
// Do 10000 was changed to 20000 code
break;
case "30000":
// Do 10000 was changed to 30000 code
break;
}
break;
case "20000":
//...changed from 20000
break;
default:
//...first time changed
break;
}
// set cur_miles to current value
cur_miles = miles.val();
}
You can't register events based on the current value of the control. What you really need is a single change function that can track both the previous value and the value it has changed to. Using an example from here:
Getting value of select (dropdown) before change
You could accomplish it with something like this:
//set the pre data, usually needed after you initialize the select element
$('#miles').data('pre', $('#miles').val());
$('#miles').change(function(e) {
var oldMiles = $(this).data('pre'); //get the pre data
var newMiles = $(this).val();
//Do your work here
switch(oldMiles) {
case "12000":
if newMiles == "15000" {
...
}
$(this).data('pre', newMiles); //update the pre data
})
First you need to keep previous value in one js variable.
If you can use jQuery, following code will do what you want:
var prev_value = false;
$('#miles').on('change', function(){
var new_value = $(this).val();
if (prev_value ==== false) {
prev_value = new_value;
return; // Because this is just first time loading
}
if((prev_value =='10000') && (new_value =='12000')) {
// do something
} else if (...) {
...
}
});

How to create a persistent random countdown?

Basically, I need a counter that will go backwards from 100-1 slowly as users enter our website. We are only giving out "100" free coupon but want to give the appearance that users are quickly grabbing them in order to create urgency and have the prospect give us their email. I am using Unbounce to host our mobile landing page.
I came across a similar post to mine but the code generated numbers randomly in the millions. Here is the link for further help: https://stackoverflow.com/a/17964971
Quick example:
Be the first to know when we launch! We are only giving out 100 coupons and there are only (x) amount left.
Click here to get yours!
Count down at a random rate between 5 seconds and 1 second, save the current to the browser so if the user revisits the page the number doesn't reset
(Demo)
var i = 100;
var counter = document.getElementById('counter');
if(localStorage.counter) {
i = localStorage.counter;
}
function countDown() {
if(i > 0) {
i--;
console.log(i);
counter.innerText = i;
localStorage.counter = i;
var timeout = Math.floor(Math.random() * (5000 - 1000)) + 1000;
setTimeout(function(){
countDown();
}, timeout);
} else {
document.getElementById('counter-wrp').innerText = 'Oh no, you missed out! All of the coupons are gone.'
}
}
countDown();
<span id="counter-wrp">Be the first to know when we launch! We are only giving
out 100 coupons and there are only <span id="counter" style="color: red;"></span> left</span>
I create this jsFiddle for you using your example
My method utilizes localStorage, which is perfect for this type of function. You can read more about local storage here w3schools. You need to this save the count.
You will notice that to initialize the counter you need additional options
var counter = new Counter({
start: 123456789,
up: '#btnUp',
down: '#btnDn',
storageKey: 'count'
});
up: and down: are just jQuery selectors for the buttons I added with id's btnUp and btnDn. storagekey: can be whatever string you'd like to set to retrieve our count out of localstorage.
here are my buttons
<div class="buttons">
<button id="btnUp" type="button">+</button>
<button id="btnDn" type="button">-</button>
</div>
I hope this helps

Help me improve this Javascript codes limitations?

This Javascript which uses functions from jQuery is quite handy but getting feedback on it there is some limitations which I was hoping you guys could help me overcome.
The function basically creates a textbox with a formatted time (HH:MM:SS) so that it is easy for users to enter in times rather than have to use a date time picker which involves lots of clicks.
Code:
//global variable for keeping count on how many times the function is called
var i = 0;
//for adding formatted time fields
function timemaker()
{
//creates an input field of text type formatted with a value of "00:00:00"
var input = $("<input>",
{
name: 'time'+i, // e.g. time0, time1, time2, time3
value: '00:00:00',
maxlength: '8',
size: '6'
});
//this function which uses jquery plugin causes the cursor in the field to goto position zero
//when selected making it easier for the user to enter times and not need to select the correct position
input.click(function()
{
$(this).prop({
selectionStart: 0,
selectionEnd: 0
});
//this child function moves the cursor along the text field
//when it reaches the first ":" it jumps to the next "00"
}).keydown(function() {
if (event.keyCode == 9)
{
return;
}
else
{
var sel = $(this).prop('selectionStart'),
val = $(this).val(),
newsel = sel === 2 ? 3: sel;
newsel = sel === 5 ? 6: newsel;
$(this).val(val.substring(0, newsel) + val.substring(newsel + 1))
.prop({
selectionStart: newsel,
selectionEnd: newsel
});
}
});
//this appends the text field to a divved area of the page
input.appendTo("#events");
i++;
return;
}
00:00:00
Limitations I need help with
Say for example you wanted to enter a time of 12:45:00 , you
obviously don't need to enter the seconds part (last "00") as they
are already there. So you then decide to tab out of that text field
but the javascript interprets your "Tab" keypress as an entry and
deletes a zero from the field causing the value to be like 12:45:0
Does not validate inputs for 24 hour format- do you think it will be
possible to do that? e.g. first number you enter is "2" therefore the
only options you have are "0,1,2,3"
If you make a mistake in the 4th digit and reselect the text field
you have to enter everything again.
I think the main thing you're missing that would allow you to implement all those requirements is the argument that jQuery passes to you in your keydown event handler. So, change that line to this:
.keydown(function(event){
if (event.keyCode == 9) { return; }
... the rest of your code ...
and then you can use event.keyCode to identify what was pressed and take actions accordingly. So for example, if event.keyCode == 9 then the user pressed TAB.
This is a slightly out-of-the-box solution, but you might consider it if things don't work out with your filtered textbox:
http://jsfiddle.net/YLcYS/4/

Categories

Resources