Prevent checkbox from being selected in Javascript - javascript

I have a JavaScript function that checks if a checkbox is selected.
If yes, It count how many check boxes are selected and checks if the max number of selected (4) is reached.
The thing is:
How can I make that the function show an alert and disable all the unchecked check boxes when I try to check a fifth?
Even the one that was tried to be checked as the 5 one.
function ChkValidate() {
var chkDytLek = document.getElementById("ChkDytLek");
var chkDytUSD = document.getElementById("ChkDytUSD");
var chkDytEU = document.getElementById("ChkDytEU");
var chkDytCAD = document.getElementById("ChkDytCAD");
var chkDytCHF = document.getElementById("ChkDytCHF");
var chkDytAUD = document.getElementById("ChkDytAUD");
var chkDytGBP = document.getElementById("ChkDytGBP");
var MaxCount = 0
var unCheckedCount = 0
if (chkDytLek.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytUSD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytEU.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytCAD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytCHF.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytGBP.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (ChkDytAUD.checked == true) {
MaxCount = MaxCount + 1
if (MaxCount == 4) {
disableIfNotChecked();
}
} else {
unCheckedCount = unCheckedCount + 1
}
if (unCheckedCount >= 4) {
enableIfNotChecked();
}
}
The current code displays an alert and disables the checkboxes when the count is 4.
When I want this to happen at the 5 one, but if I change this:
if (MaxCount == 4) {
disableIfNotChecked();
to:
if (MaxCount == 5) {
disableIfNotChecked();
The code will disable the check boxes but will also check the one that was selected as the 5.
Any idea how can I give a solution to this situation?

I think that you need some sort of control when to try to select a checkbox.
Try this:
$('input[type="checkbox"]').on('click', function(event) {
if(maxCount == 5) {
event.preventDefault();
alert('So many checkboxes');
}
});
Here is the fiddle:
http://jsfiddle.net/DrKfE/817/

Add this to the function call inside your checkbox ChkValidate(this)
<asp:CheckBox ID="ChkDytCAD" runat="server" GroupName="Monedha" Text="CAD" CssClass="radioMarginLeft" onClick="ChkValidate(this)" ClientIDMode="Static" />
Add the parameter to the function and at the end of the function uncheck it when you have 4 boxes ticked
function ChkValidate(checkbox) {
...
if (MaxCount > 4) {
checkbox.checked = false;
}
}
this is a fiddle with an example, that does pretty much what you want, it will only let you check a maximum of 4 boxes at once https://jsfiddle.net/2p069wvb/8/

Related

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

JS Empty focused Input

If the user enters an invalid number, I want to empty the input. Negative numbers and numbers that are decimal are not allowed.
This is my Js Function:
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').html("");
}
$('#priceOutput').html(output);
}
But somehow the input is not empty if I enter a count that goes into the else section.
change the value of the input with val() instead of html():
function calcPrice() {
var count = $('#placeCount').val();
if(count%1 == 0 && count > 0) {
if(count == 0) {
var output = "";
} else if(count == 1) {
var output = "€ 2,49";
} else if(count > 1 && count != 0) {
var output = ("€ " + (2*count-0.01));
}
}
else {
$('#placeCount').val("");
}
$('#priceOutput').html(output);
}

Comparing two objects woth themselves and each other

I am a very new programmer, and im not used to things more complex than a few if else statements or some light DOM traversing.
With the help of stackoverflow I've created a test for an RPG website im building.
14 questions test the users "concerns" as a player in a dungeons and dragons like setting, and assign points to 1 of 8 personality types.
Each of the 8 types, are the properties of two objects. PrimaryResults and secondaryResults. Each of the 8 properties have the same name.
Defender (def) , Berserker(ber), Monk(mnk) etc (you'll see it in the code)
The point is to be able to get results like Def/Def or Ber/Def or Mnk/Def
there are 8x8 combinations or 64 results.
then one div with the a class of results appends the actual HTML results to the screen for the user based on the final scores of the test.
My Problem:
I need a line of Code that goes through each property of BOTH objects and finds the highest value, I'm trying to put that in an IF statement that results in appending the correct results to the user.
Updated Attempt on 6/5 ---
USing Azamantes' code suggestion, I find that I still get the results of DEF/ DEF no matter what the actual values of each variable are.
I've included a screen shot of what the console.log is telling me about the values vs what the display is bringing up.
For some reason when the code cycles over
If ph =def and sh = def its coming back as true.
In the image I circled a possible issue, I dont know im not an expert.
could it having anything to do with how it says 0 for Ber on the top and has the score for ber when clicked on ? (see picture)
or could it have anything to do with the values of the objects itself? Are the values getting lost in translation somewhere?
$(window).load(function() {
$(".intro").appendTo('#display_box');
var question = $(".question");
var questionPosition = -1;
var results =$(".results");
var secondaryResults = {
def:0,
ber:0,
mnk:0,
rng:0,
cle:0,
thf:0,
mge:0,
dru:0,
};
var primaryResults = {
def:0,
ber:0,
mnk:0,
rng:0,
cle:0,
thf:0,
mge:0,
dru:0,
};
let pH = 'def', sH = 'def';
Object.keys(primaryResults).map(key => {
if(primaryResults[key] > primaryResults[pH]) {
pH = key;
}
if(secondaryResults[key] > secondaryResults[pH]) {
sH = key;
}
});
const highestPrimary = primaryResults[pH];
const highestSecondary = secondaryResults[sH];
$("#submit").on('click', function(){
console.log(primaryResults);
console.log(secondaryResults);
if (pH == 'def' && sH == 'def') {
clearBox();
results.eq(0).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'ber') {
clearBox();
results.eq(1).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'mnk') {
clearBox();
results.eq(2).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'rng') {
clearBox();
results.eq(3).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'thf') {
clearBox();
results.eq(4).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'cle') {
clearBox();
results.eq(5).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'dru') {
clearBox();
results.eq(6).fadeIn(500).appendTo('#display_box');
};
if (pH == 'def' && sH == 'mge') {
clearBox();
results.eq(7).fadeIn(500).appendTo('#display_box');
};
})
function clearBox(){
$("#display_box").children().fadeOut(500).appendTo('#question_holding');
};
function cycle(){
question.eq(questionPosition).fadeIn(500).appendTo("#display_box");
$("#display_box").animate({scrollTop:0}, 500);
}
$('#leftarrow').on('click', function(){
questionPosition--;
if (questionPosition <= -1) {questionPosition = 13};
clearBox();
cycle();
});
$('#rightarrow').on('click', function(){
questionPosition++;
if (questionPosition > 13) { questionPosition = 0};
clearBox();
cycle();
if($('input[name^="answer"]:checked').length > 13 ) {
$("#submit").css('display', 'block');
}
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkL"){
secondaryResults.mnk += 1.02;
}
if ($(this).val() == "berserkerL"){
secondaryResults.ber += .99;
}
if ($(this).val() == "defenderL"){
secondaryResults.def += 1.01;
}
if ($(this).val() == "thiefL"){
secondaryResults.thf += 1;
}
if ($(this).val() == "mageL"){
secondaryResults.mge += .98;
}
if ($(this).val() == "clericL"){
secondaryResults.cle += 1.03;
}
if ($(this).val() == "rangeL"){
secondaryResults.rng += .97;
}
if ($(this).val() == "druidL"){
secondaryResults.dru += 1.05;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkM"){
secondaryResults.mnk += 1.31;
}
if ($(this).val() == "berserkerM"){
secondaryResults.ber += 1.29;
}
if ($(this).val() == "defenderM"){
secondaryResults.def += 1.3;
}
if ($(this).val() == "thiefM"){
secondaryResults.thf += 1.28;
}
if ($(this).val() == "mageM"){
secondaryResults.mge += 1.27;
}
if ($(this).val() == "cleric"){
secondaryResults.cle += 1.32;
}
if ($(this).val() == "rangeM"){
secondaryResults.rng += 1.33;
}
if ($(this).val() == "druidM"){
secondaryResults.dru += 1.26;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkH"){
secondaryResults.mnk += 1.5;
}
if ($(this).val() == "berserkerH"){
secondaryResults.ber += 1.51;
}
if ($(this).val() == "defenderH"){
secondaryResults.def += 1.52 ;
}
if ($(this).val() == "thiefH"){
secondaryResults.thf += 1.49;
}
if ($(this).val() == "mageH"){
secondaryResults.mge += 1.48;
}
if ($(this).val() == "clericH"){
secondaryResults.cle += 1.47;
}
if ($(this).val() == "rangeH"){
secondaryResults.rng += 1.53;
}
if ($(this).val() == "druidH"){
secondaryResults.dru += 1.51;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkPL"){
primaryResults.mnk += .96;
}
if ($(this).val() == "berserkerPL"){
primaryResults.ber += .97;
}
if ($(this).val() == "defenderPL"){
primaryResults.def += .98;
}
if ($(this).val() == "thiefPL"){
primaryResults.thf += .99;
}
if ($(this).val() == "magePL"){
primaryResults.mge += 1;
}
if ($(this).val() == "clericPL"){
primaryResults.cle += 1.01;
}
if ($(this).val() == "rangePL"){
primaryResults.rng += 1.02;
}
if ($(this).val() == "druidPL"){
primaryResults.dru += 1.03;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkP"){
primaryResults.mnk += 1.3;
}
if ($(this).val() == "berserkerPM"){
primaryResults.ber += 1.26;
}
if ($(this).val() == "defenderPM"){
primaryResults.def += 1.27;
}
if ($(this).val() == "thiefPM"){
primaryResults.thf += 1.28;
}
if ($(this).val() == "magePM"){
primaryResults.mge += 1.29;
}
if ($(this).val() == "clericPM"){
primaryResults.cle += 1.31;
}
if ($(this).val() == "rangePM"){
primaryResults.rng += 1.32;
}
if ($(this).val() == "druidPM"){
primaryResults.dru += 1.33;
}
})
});
$('#submit').on('click', function() {
$('input[name^= "answer"]:checked').each(function(){
if ($(this).val() == "monkPH"){
primaryResults.mnk += 1.46;
}
if ($(this).val() == "berserkerPH"){
primaryResults.ber += 1.47;
}
if ($(this).val() == "defenderPH"){
primaryResults.def += 1.48 ;
}
if ($(this).val() == "thiefPH"){
secondaryResults.thf += 1.49;
}
if ($(this).val() == "magePH"){
primaryResults.mge += 1.5;
}
if ($(this).val() == "clericPH"){
primaryResults.cle += 1.51;
}
if ($(this).val() == "rangePH"){
primaryResults.rng += 1.52;
}
if ($(this).val() == "druidPH"){
primaryResults.dru += 1.536172;
}
$("#submit").css('display','none');
})
});
});
Screen cap of results
If I understood you, this is what you need:
let primaryResults = {
def: 0, ber: 5, mnk: 99999,
rng: 0, cle: 1, thf: 1,
mge: 0, dru: 1,
};
let secondaryResults = {
def: 1, ber: 0, mnk: 0,
rng: 1, cle: 33333333, thf: 0,
mge: 1, dru: 0,
};
let pH = 'def', sH = 'def';
let highestPrimary, highestSecondary;
Object.keys(primaryResults).map(key => {
if(primaryResults[key] > primaryResults[pH]) {
pH = key;
}
if(secondaryResults[key] > secondaryResults[sH]) {
sH = key;
}
});
highestPrimary = primaryResults[pH];
highestSecondary = secondaryResults[sH];
pH - key in primaryResults with the highest value
sH - key in resultsResults with the highest value
highestPrimary - the highest value in primaryResults
highestSecondary - the highest value in secondaryResults

JavaScript - Make a variable change every second

Ok, so this is my code:
name: function(gameServer, split) {
// Validation checks
var id = parseInt(split[1]);
if (isNaN(id)) {
console.log("[Console] Please specify a valid player ID!");
return;
}
var name = split.slice(2, split.length).join(' ');
if (typeof name == 'undefined') {
console.log("[Console] Please type a valid name");
return;
}
var premium = "";
if (name.substr(0, 1) == "<") {
// Premium Skin
var n = name.indexOf(">");
if (n != -1) {
premium = '%' + name.substr(1, n - 1);
for (var i in gameServer.skinshortcut) {
if (!gameServer.skinshortcut[i] || !gameServer.skin[i]) {
continue;
}
if (name.substr(1, n - 1) == gameServer.skinshortcut[i]) {
premium = gameServer.skin[i];
break;
}
}
name = name.substr(n + 1);
}
} else if (name.substr(0, 1) == "[") {
// Premium Skin
var n = name.indexOf("]");
if (n != -1) {
premium = ':http://' + name.substr(1, n - 1);
name = name.substr(n + 1);
}
}
and i want to change premium to something like <kraken> and <spy> every second, so that then it changes gameServer.skinshortcut to %kraken and then 1 second later it changes that to %spy... and cycles, How do I do this?
Use setInterval(function, delay in ms)
Try:
Var pre_stat=0;
function tgl_pre()
if (pre_stat=0)
{
pre_stat=1;
//change variable to `kraken`;
}
else
{
pre_stat=0;
//change variable to 'spy';
}
setInterval("tgl_pre()", 1000);
end

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources