jQuery Math - No calculation with empty fields - javascript

I have a simple parse to get the sum of a collection of textareas. It works fine, but if there's no value placed in the field, then the calculation just doesn't run.
How can I make the default value 0 without having the contents actually have to be 0? Like, I don't want the fields to load up with a 0 already waiting in the box - I just want the formula to not worry about empty fields.
Here's the jQuery:
jQuery(document).ready(function(){
jQuery(".button1").click(function(){
var set1 = function() {
var calc1 = 0;
$('.calc1').each( function(index,item) {
calc1 += parseInt(jQuery(item).val());
});
$('.result1').html(calc1);
}
set1();
});
});
The codepen can be seen here if you'd like to get a better idea: https://codepen.io/JTBennett/pen/NENMdP
I appreciate any help with this! I know it's probably a stupid mistake, but I've tried a few different things and not gotten anywhere yet.

Try parseInt(jQuery(item).val() || 0). The || operator will return the second value if the first is falsey. Therefore if the value is empty, it will try to parse '0' which it will successfully.

Just make an if statement that looks for an empty field and then replace it with 0.
$('.calc1').each( function(index,item) {
var itemValue = jQuery(item).val();
if (itemValue === "") {itemValue = 0;}
calc1 += parseInt(itemValue);
});

You can just replace your line with this:
calc1 += parseInt(jQuery(item).val() || 0);

Related

The problem of changing multiple of 3 to red using jquery on the presented screen

Only jquery script should be used to mark the number of multiples of 3 in red.
Each number is made up of <table>.
I made the code below, but there's an error.
$(function(){
$("#Q2_1").find(function(){
var num = $("#Q2_1").val();
num = Number(num) + 1;
return num % 3 == 0;
});
.css({"color":"#f00"});
});
Please advise me what the problem is.
Or can you give me a similar but simple example?
Use a selector that returns all the td elements in the table.
Use filter() to restrict this based on a condition.
The condition should get the text of the element; value is for user inputs.
Get rid of the ; after the call, so you can append .css().
$(function() {
$("#tableid td").filter(function() {
let num = Number(this.innerText);
return num % 3 == 0;
}).css("color", "red");
});

Need help looping JSON with JavaScript. Weird behaviours

Although, it ran fine on small data. I need help looping through JSON in this form:
var current_value = 2;
json_data = {"2":"first information","3":"Second informaton","4":"Third information"}
What I want to do is get the value in the json_data that corresponds to current_value of 2
The problem is that I keep getting " anytime I run this loop:
for(x in json_data){
if(x === current_value){
extracted = json_data[current_value];
}
}
JavaScript property names are strings. 2 is a number. === does not do type conversion. "2" !== 2.
You should set current_value to "2" instead of 2.
The loop is pointless though.
A more sensible approach would be:
var extracted;
if (current_value in json_data) {
extracted = json_data[current_value];
}
… or even just skip the if statement. extracted will be undefined either way if the property doesn't exist.

click only one random button from the true condition response jquery/javascript

I'm a newbie in jquery/javascript and i need some help!
I'm trying to click only one button from the true condition response, but all the time the script will click on all the buttons of the true condition response.. I don't know how to solve this.
$(".enemy-box").each(function(index) {
var pret = Number($(this).find('.attack-price').text().replace(/,/g, '').split('$')[1]);
var name = $(this).find('.enemy-name').text().replace(/\s+/g, " ");
var x = $(this).find(document.getElementsByClassName("btn attack-btn")); // this will click on all the true conditions buttons
/* I have tried with this but stil not working. the script will click on all the true conditions buttons!
var len = $(this).find(document.getElementsByClassName("btn attack-btn")).length;
var random = Math.floor( Math.random() * len ) + 0;
var x = $(this).find(document.getElementsByClassName("btn attack-btn")).eq(random);
*/
if (name.indexOf("Test") == -1 && pret <= 39.99 ) {
x.click();
}
});
Any help is much appreciated, thank you in advance!
Try replacing $(this).find(document.getElementsByClassName("btn attack-btn")); with $(this).find('.attack-btn:first);.
getElementByClassName is unnecessary when using jQuery. :first will return only the first occurrence of the selector.
This is happening because you are passing the document as context to the find() function. And, since you are using jQuery, you don't need to use JS method. Simply pass the selector to the method find().
You can do that either by
var x = $(this).find('btn.attack-btn:first');
or
var x = $(this).find($('btn.attack-btn').eq(0));

Javascript function skips statements

I have a simple function as follows:
function FUNCTION1() {
document.getElementById('Preview1').innerHTML = ''){
if (document.UserData.input1.value.length !== 0;
var input1 = document.UserData.input1.value;
document.getElementById('Preview1').innerHTML = '<div>Hello ' + input1 + '</div>';}
}
I run the above script and everything is just fine.
Then I run another function to clear the div which has the form "UserData".
document.getElementById('UserDataDiv').innerHTML = '';
And then I run the FUNCTION1 again, It brings up old value This value should not be there as div was cleared.
Is there a way to avoid this behaviour or am i doing something wrong?
I think you should just check that the string is empty instead of the length of the value: document.UserData.input1.value.length:
if (document.UserData.input1.value == '')
Oh, as someone else has pointed out, it also looks like there's an extra semi-colon at the end of your first line.

Strange results with javascript array.length function

I have piece of JavaScript code which cycles through form elements and builds an object.
I have a mixture of HTML input fields and ASP.NET input fields. ASP.NET changes the ID of the fields to the form xxxxx_yyyy_id, so I am attempting to use the split function to extract the original id.
// Iterate over all the text fields and build an object
$(':text').each(function () {
var tokens = this.id.split("_");
if (tokens.length = 3) {
// Assume this is a .net inputbox - extract the original id
inFormData[tokens[2]] = this.value;
} else {
inFormData[this.id] = this.value;
}
});
Stepping through the above code, the first id is ctl00_ContentPlaceHolderCol1_forenameField, so the tokens.length = 3 code is run.
On the second iteration, the id is forenameField2 so I would expect the tokens.length to be 1, but it is actually 3. The else statement is never run.
This could be something simple, but I cant work it out. If I inspect the tokens array it has only 1 element in on the second iteration. I have also tried setting the array.length to 0 after each iteration.
Any help appreciated.
Correct this:
== instead of =. === is more better
if (tokens.length == 3) {
// Assume this is a .net inputbox - extract the original id
inFormData[tokens[2]] = this.value;
} else {
inFormData[this.id] = this.value;
}
Change your = 3 to === 3
At the moment you're overwriting tokens.length every time.
NB: === is preferred to == because it's an exact equality check. The two-equals version will attempt to cast the two operands to the same type before comparison, which is 1. unnecessary, 2. inefficient, 3. sometimes error prone.
That is why you should always put the constant first when testing. If you forget a comparison sign it will throw an error:
if( 3 = tokens.length ) // throws an error
if( 3 == tokens.length ) // ok
if( 3 === tokens.length) // ok
from:
if (tokens.length = 3) {
to:
if (tokens.length == 3) {

Categories