Can't make the function true when the argument is passed JQuery - javascript

Problem is simple. When the scoring variable is higher than 10, I can't make the sprawdzRyzyko() function return boolean true.
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
$('#country, #country-bd, #country-wd').change(function(){
caunt = $(this).val();
var arr = $.inArray(caunt, high_ryzyko_kraj);
var drr = $.inArray(caunt, less_ryzyko_kraj);
if (arr>-1){
scoring += 4 ;
sprawdzRyzyko();
}else if(drr>-1){
scoring += 2 ;
sprawdzRyzyko();
}
});
console.log(scoring);
var sprawdzRyzyko = function () {
if (scoring > 10){
return true;
}
}
// For Testing
var a = sprawdzRyzyko();
if (a){
console.log("Hey it works!");
}
Fiddle
You can set the scoring variable above 10 by sting the selects to 3 countries in high_ryzyko_kraj array.

Here is a solution. Answer Fiddle
function sprawdzRyzyko() {
if (scoring > 10) {
return true;
}
};

Try this: http://jsfiddle.net/uJA39/15/
var high_ryzyko_kraj = ['Polska', 'Afganistan', 'Ukraina'];
var less_ryzyko_kraj = ['Serbia', 'Egipt'];
var scoring = 0;
var sprawdzRyzyko = false;
$('#country, #country-bd, #country-wd').change(function(){
if ($.inArray($(this).val(), high_ryzyko_kraj)>-1)
scoring += 4;
else if($.inArray($(this).val(), less_ryzyko_kraj)>-1)
scoring += 2;
if (scoring > 10){
alert("Hey it works!");
sprawdzRyzyko=true;
}
});
I don't know your dynamics but are you sure that scoring shouldn't be set to 0 (zero) every time DDL changes (so inside change event handler)?
Hope this helps,
Have a nice day,
Alberto

Related

How to make the click of 1 button change the .innerhtml of multiple things?

I'm new to javascript and programming and I'm attempting to make a program for my workouts. I want to be able to input the amount of sets, reps, and weight I lifted and then have the program output integers that are incrementally more challenging for my next workout. At the bottom I'm trying to get the enter button to change the .innerHTML of two different elements. Is this even possible?
`
var userMovement1 = document.getElementById("movement-1").value;
var userSet1 = document.getElementById("set-user-1").value;
var userReps1 = document.getElementById("reps-user-1").value;
var userWeight1 = document.getElementById("weight-user-1").value;
var enterButton = document.getElementById("enter-button");
//Function will calculate the reps for the next workout
function calculateFutureReps(performedReps) {
var futureReps = performedReps;
if (performedReps < 12) {
return futureReps += 2;
} else if (performedReps >= 12) {
return futureReps = 6;
}
}
//Function will calculate the weight for the next workout
function calculateFutureWeight(performedWeight) {
var futureWeight = performedWeight
if (performedWeight < 12) {
return futureWeight;
} else if (performedWeight >= 12) {
return futureWeight += 10;
}
}
//Getting the value of the functions and storing them in a variable
var newReps = calculateFutureReps(userReps1).value;
var newWeight = calculateFutureReps(userWeight1).value;
//Making that variable show up on the DOM
enterButton.onclick() = document.getElementById("reps-next-1").innerHTML = newReps;
enterButton.onclick() = document.getElementById("weight-next-1").innerHTML = newWeight;`
You can do something like this to handle the click and is a function to do whatever you want in there.
enterButton.addEventHandler('click', function() {
document.getElementById("reps-next-1").innerHTML = newReps;
document.getElementById("weight-next-1").innerHTML = newWeight;
});
`

i want to make a counter function dynamic in javascript

i have called a counter function in loop. there are 4 items per page.
i have passed $i in loop and written 4 functions
but if i changed pagination limit to 5 or 10 ,it is not a good solution
anybody can help me to solve it?
here is my div in foreach loop where l called function
<div class="tick"
data-value="'.$start.'"
data-did-init="handleTickInit'.$i.'">
<div data-layout="horizontal center"
data-repeat="true"
">
<div data-view="swap"
></div>
</div>
handleTickInit'.$i is function
function handleTickInit2(tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
please give some solution to make it dynamic
Try this
var handleTickInit = {};
var num = 5;
var handleFunc = function() {
return function (tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
}
for(var i = 0; i< num; i++){
handleTickInit[i] = handleFunc();
}
console.log(handleTickInit);
All your handle tick functions are in handleTickInit;

Getting an infinite loop and can't see why - Javascript

I'm writing a simple little Connect 4 game and I'm running into an infinite loop on one of my functions:
var reds = 0;
var greens = 0;
function checkEmpty(div) {
var empty = false;
var clicked = $(div).attr('id');
console.log(clicked);
var idnum = parseInt(clicked.substr(6));
while (idnum < 43) {
idnum = idnum + 7;
}
console.log("idnum=" + idnum);
while (empty == false) {
for (var i = idnum; i > 0; i - 7) {
idnumStr = idnum.toString();
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
}
}
return divToFill;
}
function addDisc(div) {
if (reds > greens) {
$(div).addClass('green');
greens++;
console.log("greens=" + greens);
} else {
$(div).addClass('red');
reds++;
console.log("reds=" + reds);
};
$(div).removeClass('empty');
}
$(function() {
var i = 1;
//add a numbered id to every game square
$('.game-square').each(function() {
$(this).attr('id', 'square' + i);
i++;
//add an on click event handler to every game square
//onclick functions
$(this).on('click', function() {
var divToFill = checkEmpty(this);
addDisc(divToFill);
})
})
})
Here is a link to the codepen http://codepen.io/Gobias___/pen/xOwNOd
If you click on one of the circles and watch the browser's console, you'll see that it returns true over 3000 times. I can't figure out what I've done that makes it do that. I want the code to stop as soon as it returns empty = true. empty starts out false because I only want the code to run on divs that do not already have class .green or .red.
Where am I going wrong here?
for (var i = idnum; i > 0; i - 7);
You do not change the i.
Do you want to decrement it by 7?
Change your for loop to the one shown below:
for (var i = idnum; i > 0; i -= 7) {
// ...
}
You also do not use loop variable in the loop body. Instead, you use idnum, I think this can be issue.
while (empty == false) {
for (var i = idnum; i > 0; i -= 7) {
idnumStr = i.toString(); // changed to i
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
// and don't forget to stop, when found empty
if (empty) break;
}
}
I add break if empty found, because if we go to next iteration we will override empty variable with smallest i related value.
You can also wrap empty assignment with if (!empty) {empty = ...;} to prevent this override, but I assume you can just break, because:
I want the code to stop as soon as it returns empty = true
Offtop hint:
while (idnum < 43) {
idnum = idnum + 7;
}
can be easy replaced with: idnum = 42 + (idnum%7 || 7)
Change to this:
for (var i = idnum; i > 0; i = i - 7) {
You are not decrementing the i in your for loop
Building on what the others have posted You would want to change the value of empty inside the for loop. because obviously the string still checks the last string in the loop which would always return false.
while(empty==false){
for (var i = idnum; i > 0; i -= 7) {
// your other codes
if (!empty) {
empty = str.includes('empty');
}
}

Limit length of textarea in Words using Javascript?

I have the following bind on keyup which alerts if they go over 150 characters, but you can just press okay and keep typing and then just keep pressing okay.
I want to crop them at 150 words (not characters) and if they type over it, remove the extras. But I can't seem to figure out how to do it, I can figure out characters. But not words.
jQuery('textarea').keyup(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > 150) {
jQuery(".word_count span").text("150");
return alert("You've reached the maximum allowed words.");
} else {
return jQuery(".word_count span").text(wordcount);
}
});
/**
* jQuery.textareaCounter
* Version 1.0
* Copyright (c) 2011 c.bavota - http://bavotasan.com
* Dual licensed under MIT and GPL.
* Date: 10/20/2011
**/
(function($){
$.fn.textareaCounter = function(options) {
// setting the defaults
// $("textarea").textareaCounter({ limit: 100 });
var defaults = {
limit: 100
};
var options = $.extend(defaults, options);
// and the plugin begins
return this.each(function() {
var obj, text, wordcount, limited;
obj = $(this);
obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');
obj.keyup(function() {
text = obj.val();
if(text === "") {
wordcount = 0;
} else {
wordcount = $.trim(text).split(" ").length;
}
if(wordcount > options.limit) {
$("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
limited = $.trim(text).split(" ", options.limit);
limited = limited.join(" ");
$(this).val(limited);
} else {
$("#counter-text").html((options.limit - wordcount)+' words left');
}
});
});
};
})(jQuery);
Load that up and then you can use the following to make it work:
$("textarea").textareaCounter({ limit: 100 });
http://bavotasan.com/2011/simple-textarea-word-counter-jquery-plugin/
If you want to prevent the typing itself (when count > 150) you can do as following:
Use keypress instead of keyup
Instead of return alert() first do an alert() and then return false;
You may also want to add change (or blur) event handler to handle text pasting.
var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
jQuery(".word_count span").text("" + maxWords);
alert("You've reached the maximum allowed words.");
return false;
} else {
return jQuery(".word_count span").text(wordcount);
}
});
jQuery('textarea').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
words.splice(maxWords);
$(this).val(words.join(""));
alert("You've reached the maximum allowed words. Extra words removed.");
}
});​
Fiddle here
Check jQuery: Count words in real time
and this example: http://jsfiddle.net/gilly3/YJVPZ/1/
Then, if you want to cut the extra words... you could do something like:
var maxWords = 10;
if(finalCount > maxWords){
$("#a").val(a.value.slice(0,-2)); // the -2 is to remove the extra space at the end
};
Here is a working example http://jsfiddle.net/YJVPZ/80/
Hope it helps, Good Luck!
Try this function. The value argument should be your textarea value.
jQuery('textarea').val();
function wordcount(value)
{
value = value.replace(/\s+/g," ");
var andchr = value.split(" & ").length - 1;
var char_count = value.length;
var fullStr = value + " ";
//word count for regional language
v = value.split(' ');
var word_count1 = v.length;
var cheArr = Array('#','.','"',"'",'_','-','+','=',';','&','*','\(','\)','{','}','[','}','|','\\','\,','/');
for(i=0; i<=cheArr.length; i++)
{
word_count1 = word_count1 + value.split(cheArr[i]).length - 1;
}
//word count for all languages
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = (splitString.length - 1) + andchr;
if(word_count1 > word_count)
{
word_count = word_count1;
}
if(value == '' || value == null || typeof(value) == 'undefined'){
word_count = 0;
}
alert(word_count);
}
$("textarea").keyup(function(){
var obj = $(this);
var maxLen = 150;
var val = obj.val();
var chars = val.length;
if(chars > maxLen){
obj.val(val.substring(0,maxLen));
}
});
Register to these events:
$('textarea').on('paste cut keydown', function(){...});

Multiplying Variables Not Alerting

I have a script which calls variable values from input fields and multiplies them,
At the minute my function isnt executing, Im getting no alert neither, I think this is because of my if statement, can anybody see whats going wrong?
function Calculate() {
var ContentMinutes = document.getElementById ("ContentMinutes").value;
var ContentMinutesSelect = document.getElementById('ContentMinutesDD')
.options[document.getElementById('ContentMinutesDD').selectedIndex].value
if (ContentMinutesSelect == 0.0166)
{
var RenderingHours = 10;
var VideoHours = 5;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else if (ContentMinutesSelect == 0.0003)
{
var RenderingHours = 1540;
var VideoHours = 54;
var VideoSeconds = 1;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
else
{
var RenderingHours = 6410;
var VideoHours = 345;
var VideoSeconds = 124;
document.getElementById("RenderHours").innerHTML=RenderingHours;
document.getElementById("VideoHours").innerHTML=VideoHours;
document.getElementById("VideoSeconds").innerHTML=VideoSeconds;
}
var NoOfFrames = document.getElementById ("NoOfFrames").value;
//var EstimatedCoreHours = document.getElementById ("EstimatedCoreHours").value;
var ServiceLevel = document.getElementById('SerivceLevelDD')
.options[document.getElementById('SerivceLevelDD').selectedIndex].value;
var RenderHours = 1;
var CoresInTest = document.getElementById ("CoresInTest").value;
var EstimatedCoreHours = GetNumeric(NoOfFrames)
* GetNumeric(RenderingHours)
* GetNumeric(CoresInTest);
var EstimatedTotal = GetNumeric(ServiceLevel)
* GetNumeric(EstimatedCoreHours);
alert('Estimated Cost = '
+EstimatedTotal.toFixed(2)
+ 'Estimated Core Hours = '
+EstimatedCoreHours);
document.getElementById("EstimatedCoreHours").innerHTML =
EstimatedCoreHours.toFixed(2);
document.getElementById("EstimatedTotal").innerHTML =
EstimatedTotal.toFixed(2);
document.getElementById("EstimatedCoreHours").style.backgroundColor="yellow";
document.getElementById("EstimatedTotal").style.backgroundColor="yellow";
}
function GetNumeric(val) {
if (isNaN(parseFloat(val))) {
return 0;
}
return parseFloat(val);
}
if (ContentMinutesSelect == 0.0166) i think when you do .value you will get string result.
So your comparision should be
if (ContentMinutesSelect == "0.0166")
Your code will display no alert if any line before it results in an error , like if there isn't an element with the id 'ContentMinutes' in your document . The best way to debug would be to use something like firebug , or you could always put in a bunch of alerts and figure out what goes wrong.

Categories

Resources