Button dissapear when value reaches 0 JAVASCRIPT - javascript

This my code:
$('.upgrade-strength').on('click', function () {
var strCount = $('#strId');
var points = $('#points');
var userId = $(this).attr('id');
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
return val*1-1;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
});
$.ajax("/upgrade-strength/"+userId,
{
});
});
<p>Available points: <strong><span id="points">{{Auth::user()->points}}</span></strong></p>
When I clicking the button the counter goes down till 0 and then button dissapears. But what happens more is, when the
points.html(function(i, val) reaches zero the button did not dissapear. You have to click one more time tu buttons dissapear. How to solve this ?

Try this it will work:
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
val = val*1-1;
if(val == 0){
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
return val;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}

When val is 1, look at your code, and see what it's doing:
if(val*1>0) - I don't know why you keep using *1 but never mind that. 1 > 0 is true, so we're in the if block.
return val*1-1; - again, what's the deal with *1? Anyway, this returns 0.
The else block is not run.
The next time you click, if(val*1>0) is false so the else gets run, hiding the buttons.
Instead you should do something like:
If the value is 1, hide the buttons
Either way, return val-1;

Related

clearing the display in a javascript calculator after pressing "="

I'm new to coding and I built a Javascript calculator, but I can't get the display to clear after Im done with one calculation. Instead, the result of the first calculation goes into the input for the second calculation. For eg if I do 3+5 it'll give me 8, but if I then press 4, the display says 84 which is why its a problem. I can clear the screen via the clear button but it gets tedious after every single calculation. Thank you.
//select all the buttons
const buttons = document.querySelectorAll('button');
//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');
//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});
//calculate function
function calculate(event) {
//current clicked buttons value
var clickedButtonValue = event.target.value;
if(clickedButtonValue === '=') {
//check if the display is not empty then only do the calculation
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
}
//if any key except "=" pressed again clear display
button.addEventListener('click',clearDisplay);
} else if (clickedButtonValue === 'C') {
//clear everything on display
display.value = "";
} else {
//otherwise concatenate it to the display
display.value += clickedButtonValue;
}
}
function clearDisplay(clickedButtonValue) {
if(clickedButtonValue !== "=") {
display.value = "";
}
}
You can have a variable that keeps track of the calculated state. If it has been calculated, clear the display and reset the state
var calculated = false;
function calculate( event ){
var clickedButtonValue = event.target.value;
if ( calculated ) {
display.value = "";
calculated = false;
}
if(clickedButtonValue === '=') {
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
calculated = true;
}
}
// the rest of your logic here
}

Kendo Validator always says multi-select is invalid

I have a multiselect that is dynamically created and appended to a template with the following bit of code:
if(fieldMap[i].required == true){
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'*</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" name="'+fieldMap[i].fieldName.toLowerCase()+'" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" required data-required-msg="Please Select Valid '+fieldMap[i].fieldLabel+'">';
} else{
extraString = '<div class="k-edit-label" style="margin-top: -6px;"><label for="'+fieldMap[i].fieldName+'Input">'+fieldMap[i].fieldLabel+'</label>'+helpText+'</div>\n<div data-container-for="'+fieldMap[i].fieldName+'Input" class="k-edit-field" id="'+fieldMap[i].fieldName+'Container">\n';
dynamicComponent = '\t<input class="multiselect-binder" id="'+fieldMap[i].fieldName+'Input" data-auto-close="false" data-role="multiselect" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'" data-source="[';
//dynamicComponent = '\t<select id="'+fieldMap[i].fieldName+'Input" data-role="dropdownlist" data-bind="value:'+fieldMap[i].fieldName.toLowerCase()+'">';
}
optString = '';
for(var k = 0; k < fieldMap[i].picklistVals.length; k++){
if(k == 0){
optString += '\''+fieldMap[i].picklistVals[k]+'\'';
}
else{
optString += ',\''+fieldMap[i].picklistVals[k]+'\'';
}
}
//Close the input component as well as the container div
dynamicComponent += optString + ']"/>\n<span class="k-invalid-msg" data-for="'+fieldMap[i].fieldName.toLowerCase()+'"></span></div>\n\n';
I run a validator.validate() on save button click to determine if information should be saved or not, which is dependent on if the multi-select input is required.
This pops up the invalid tooltip message when nothing is selected just fine. The issue is, however, that it will be marked invalid even if a selection is made. I am wondering if anyone has any solutions for how to get a validator to work correctly with the multiselect. Just hiding the pop ups is not really what I am after, as the validate() function will still fail even if the pop up is hidden, and I need the validate() function to pass.
Maybe not the best, but here is what I got.
function Save(){
$("#divTenureContainer .k-invalid").removeClass("k-invalid");
var tenureChecked = $("#chkTenure").prop('checked');
var tenureValid = Configuration_Tenure_Validator.validate();
}
Configuration_ValidateInput = (input) => {
var validationType = $(input).data("validation");
var required = $(input).prop("required") || $(input).hasClass("js-required");
if (!required) return true;
if (validationType) {
if (validationType === "stars") {
return $(input).val() > "0";
}
if (validationType === "hashtags") {
return ($(input).data("kendoMultiSelect").value().length > 0);
}
if (validationType === "required-text") {
return $(input).val() >= "";
}
}
return true;
}
var Configuration_ValidationRules = { rules: { Configuration_ValidateInput }, validationSummary: false };
var Configuration_Tenure_Validator = $("#divTenureContainer").kendoValidator(Configuration_ValidationRules).data("kendoValidator");

Lost part of page after post page

After clicking start in this page, the value is lost.
What can I do, in order not to make the page reload itself?
<button onclick="start()">Start</button>
Start: this is called when the user clicks start on the setup screen
function start(reuse){
reuse = (typeof reuse === 'undefined') ? false : true;
//user input is read
numberOfQuestions = $("#amount").val();
time = $("#time").val();
showError = $("#showError").prop("checked");
showCorrect = $("#showCorrect").prop("checked");
fullscreen = $("#fullscreen").prop("checked");
//currentIndex is the index of current question in the list while in the quiz
currentIndex = -1;
//reset correct questions
correct = 0;
var pred = {place:1, time:2, other:3};
var _numberOfQuestions = 0;
if (reuse){
_data = filteredData;
} else {
_data = data;
}
//filteredData is the new list of question AFTER filtering it according to setup screen
filteredData = [];
$.each(_shuffle(_data), function(index, entry){
if ($("#ddcl-d1-i"+entry['pad']).prop("checked")){
if ($("#ddcl-d2-i"+pred[entry['pred']]).prop("checked")){
_numberOfQuestions++;
entry['a'] = _shuffle(entry['a']);
filteredData.push(entry);
}
}
if (_numberOfQuestions == numberOfQuestions) return false;
});
if (_numberOfQuestions == 0){
alert("No questions available");
return;
}
$("#quiz").show();
$("#setup").hide();
$("#finish").hide();
secondsLeft = time * numberOfQuestions;
doTimer();
nextQuestion();
if (fullscreen && screenfull.enabled){
screenfull.request(document.getElementById('container'));
}
}
I call Start with JavaScript.
I try to add autopostback ="false", but the outcome remains the same.
You can add type attribute to buttons, because they automatically submit forms.
<button type="button" onclick="start()">Start</button>

Illustrator JavaScript only works once - won't toggle

I'm writing a script which changes the colours of a stick-man's arms and legs. Once "he" is selected, it effectively just mirrors the colours:
//Declare and initialize variables
var msgType = "";
var app;
var docRef = app.activeDocument;
var testColor = docRef.swatches.getByName("CMYK Green");
var leftColor = docRef.swatches.getByName("LeftColor");
var rightColor = docRef.swatches.getByName("RightColor");
function sameColor(CMYKColor1, CMYKColor2) {
"use strict";
var isTheSameColor;
if ((CMYKColor1.cyan === CMYKColor2.cyan) && (CMYKColor1.magenta === CMYKColor2.magenta) && (CMYKColor1.yellow === CMYKColor2.yellow) && (CMYKColor1.black === CMYKColor2.black)) {
isTheSameColor = true;
} else {
isTheSameColor = false;
}
return isTheSameColor;
}
// check if a document is open in Illustrator.
if (app.documents.length > 0) {
var mySelection = app.activeDocument.selection;
var index;
// Loop through all selected objects
for (index = 0; index < mySelection.length; index += 1) {
// Switch left and right colours
if (sameColor(mySelection[index].strokeColor, leftColor.color)) {
mySelection[index].strokeColor = rightColor.color;
}
if (sameColor(mySelection[index].strokeColor, rightColor.color)) {
mySelection[index].strokeColor = leftColor.color;
}
if (sameColor(mySelection[index].fillColor, leftColor.color)) {
mySelection[index].fillColor = rightColor.color;
}
if (sameColor(mySelection[index].fillColor, rightColor.color)) {
mySelection[index].fillColor = leftColor.color;
}
}
}
It works, but it only works once (i.e. I can't toggle the change again). If I undo the change and try again it works again. Why is this?
After a lot of head-scratching / debugging it turns out that it was changing the CMYK values to be not quite the same (by a tiny fraction).
Changed the following:
if ((CMYKColor1.cyan === CMYKColor2.cyan) ...
to:
if ((Math.round(CMYKColor1.cyan) === Math.round(CMYKColor2.cyan)) ...
and it works fine now.

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

Categories