Sum with jquery not working - javascript

I have a lot of labels as shown on a page. I want to sum the values and store them in final_cpa.
HTML :
<label class="tmpcpa">32.1</label>
JS :
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).val() != 0) {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
var run = setInterval(calculate_final_cpa, 500);
However final_cpa is always 0 and allfilled remains false.

That because label don't have a value attribute so the .val() function will always return an empty string, you have to use .text() instead to get the text content inside the label element :
if ($(this).val() != 0) {
Should be :
if ($(this).text() != 0) {
NOTE : as Rayon mentioned in the comment below text() will always return string so better to change the zero in condition to string '0'.
Hope this helps.
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != '0') {
final_cpa += parseInt($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>

Check $(this).text() != "" instead of $(this).val() != 0 as You can not use .val() for getting label text. .text() will give you text of label
if ($(this).text() != "" && $(this).text() != "0") {
....
}

First thing, you need to use .text() instead of .val() to get the text inside a label. Also, if you are expecting your result to contain decimal digits, you need to use parseFloat():
function calculate_final_cpa() {
var final_cpa = 0;
var allfilled = false;
$('.tmpcpa').each(function () {
if ($(this).text() != 0) {
final_cpa += parseFloat($(this).text()) || 0;
allfilled = true;
} else {
allfilled = false;
}
});
console.log(final_cpa);
console.log(allfilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<br />
<label class="tmpcpa">32.1</label>

Change
if ($(this).val() != 0)
to
if (parseInt($(this).text()) != 0)

Beside your code had an error, you should check the content of the table before parsing them. And because you use decimals in your example, you should switch from parseInt to parseFloat too.
And your allfilled varibale makes no sense, because if the last element of .tmpcpa was empty, it will be false again. So i removed it.
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
var content = $(this).text();
final_cpa += IsNumeric(content) ? parseFloat(content) : 0;
});
console.log(final_cpa);
}

Test it with .text instead of val() as label has no value property
Use Unary plus(+)/Number operator instead of parseInt as parseInt will ignore floating point
Use length of lable-elements to test whether all the label has values !== 0
function calculate_final_cpa() {
var final_cpa = 0;
var countOfFilled = 0;
$('.tmpcpa').each(function() {
if ($(this).text() !== '0') {
final_cpa += +($(this).text()) || 0;
++countOfFilled;
}
});
console.log('Total: ' + final_cpa);
console.log('All filled ' + $('.tmpcpa').length === countOfFilled);
}
calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">32.1</label>
<label class="tmpcpa">0</label>

Related

remove duplicate entry from html input boxes in JavaScript/jQuery

I have a fiddle which checks for any duplicate entry entered in html input boxes.
It works in a way that if any duplicate entry is entered in a newly added row or the rows which are already there then the alert message "duplicate" is displayed.
I have used the following script in order to make that happen.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) { alert('duplicate'); }
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
What I am trying to achieve now is when any duplicate entry is entered in html input boxes then it should get disappeared automatically and the text "Please enter different text" left to the row should be displayed, something like this
http://jsfiddle.net/zHJSF/
This is what I have tried but it doesn't seem to work.
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
$('#addRow').on('click', function(){
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) {
alert('duplicate');
($(this).val()).stop(false,true).after(' <span style="color:red;" class="error">Please enter different text</span>');
$('.error').delay(600).fadeOut();
$(this).val('');
}
}
});
});
$(this).addClass('e');
});
});
Problem Statement:
I am wondering what changes I should make in the script above so that it get rid of any duplicate entry entered in the html input boxes.
EDIT
This should work. It will get the input values and put them into an array, then check if the value exists in the array.
javascript
$('input[name*="code"]').each(function() {
$(this).change(function(){
let element = this;
var array = $('input[name*="code"]').map(function() {
if (this != element)
return $(this).val()
return null;
}).get();
if (array.includes($(this).val())) {
$(this).val("");
$(this).attr("placeholder", "Please enter different text");
$(this).addClass("error");
} else if ($(this).hasClass("error")) {
$(this).removeClass("error");
}
});
$(this).addClass('e');
});
css
.error {
border: 1px solid red;
}

Textbox Maxlength Issue for amount field

I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`

jquery change text once on change function

The problem is that when i change the option it keeps summing, and i would like for it to only sum one time the value of 10.00, and subtract only once if the value is AR .
LIVE LINK: http://jsfiddle.net/A3qLG/1/
JQUERY:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
HTML:
<label id="subt0">8.90</label>
<select id="country">
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="AR">Argentina</option>
<option value="CU">Cuba</option>
</select>
I would change the HTML to this to store the original value:
<label id="subt0" data-original="8.90">8.90</label>
And then adjust the Javascript to this:
$(document).ready( function() {
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
});
try this code
$(document).ready( function() {
$('#country').on('keypress change', function(e){
var subt_value = $('#subt0').text();
if($(this).val() == 'AR' || $(this).val() == ''){
if(subt_value != '0.00' ){$('#subt0').text(parseFloat(subt_value-10).toFixed(2));}
}else{
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
}
});
});
You need to remember previous #country select value, and use it when making decision:
$(document).ready(function () {
var prevValue = '';
$('#country').on('keyup change', function (e) {
var newValue = $(this).val();
var subt_value = parseFloat($('#subt0').text());
if ((newValue == 'AR' || newValue == '')) {
if (prevValue != '' && prevValue != 'AR') {
$('#subt0').text((subt_value - 10).toFixed(2));
}
} else {
if (prevValue == 'AR' || prevValue == '') {
$('#subt0').text((subt_value + 10).toFixed(2));
}
}
prevValue = newValue;
});
});
http://jsfiddle.net/A3qLG/5/
Simply remove the onkeyup and onchange event handler functions after they have done their work.
$('#country').off('keyup change');
Jquery provide a .change() specifically for <select>
You want to sum only one time and substract only one time base on the condition of the selected value AR. Therefore you only need to check the selected value if there is change and do the math within the if-else statement. Finally attach the result with .toFixed(2)
var subt_value = $('#subt0').text();
var add_sub = 0, f=10.00;
$('#country').change(function(){
if ($(this).val() != 'AR'){
add_sub = parseFloat(subt_value)+f;
}else{
add_sub = parseFloat(subt_value)-f;
}
$('#subt0').text(add_sub.toFixed(2));
});
JSFiddle Demo

form validation with radio buttons and specific errors

I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.

Validate different fields depending on what is selected in a dropdown in a form with jQuery?

I have the following code to validate some fields on a sharepoint newform.aspx. To not submit the form in sharepoint I must return a false statement to the default function PreSaveItem.
Validation:
//bind a change event to all controls to validate
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").change(function(){
checkControls()
});
//the change event function - check the status of each control
function checkControls(){
//set a variable to count the number of valid controls
var controlsPassed = 0;
//set up a selector to pick .each() of the target controls
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
//if the control value is not zero AND is not zero-length
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
//call the PreSaveItem function and pass the true/false statement of 5 valid controls
return (controlsPassed == 5)
}
function PreSaveItem() {
return checkControls()
}
I want to validate different elements depending on what I have selected in a dropdown list called Item Level.
I get the values from Item Level with:
$("select[title='Item Level']").change(function() {
var itemLevel = $(this).val();
if (itemLevel == "Strategic Objective") {
alert(itemLevel);
}
if (itemLevel == "Strategic Priority") {
alert(itemLevel);
}
if (itemLevel == "Milestone Action") {
alert(itemLevel);
}
if (itemLevel == "Performance Measure") {
alert(itemLevel);
}
});
I thought it would be easy to just chuck the validation code into the if's but it doesn't work.
For example:
$("select[title='Item Level']").change(function() {
var itemLevel = $(this).val();
if (itemLevel == "Strategic Objective") {
alert(itemLevel);
}
if (itemLevel == "Strategic Priority") {
alert(itemLevel);
}
if (itemLevel == "Milestone Action") {
//bind a change event to all controls to validate
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").change(function(){
checkControls()
});
//the change event function - check the status of each control
function checkControls(){
//set a variable to count the number of valid controls
var controlsPassed = 0;
//set up a selector to pick .each() of the target controls
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
//if the control value is not zero AND is not zero-length
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
//call the PreSaveItem function and pass the true/false statement of 5 valid controls
return (controlsPassed == 5)
}
function PreSaveItem() {
return checkControls()
}
alert(itemLevel);
}
if (itemLevel == "Performance Measure") {
alert(itemLevel);
}
});
and in the item level item Strategic Objective validate some other elements. Any ideas?
Thanks in advance.
Edit: the working code with help from casablanca:
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
var controlsPassed = 0;
$("input[id$=UserField_hiddenSpanData]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if(val != 0 && val.length != 0 && txt.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 1)
case 'Milestone Action':
var controlsPassed = 0;
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective],select[title=Strategic
Priority]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 5)
case 'Performance Measure':
var controlsPassed = 0;
$("select[title=Strategic Objective],select[title=Strategic Priority]").each(function(){
var val = $(this).val();
if(val != 0 && val.length != 0) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 2)
case 'Strategic Priority':
var controlsPassed = 0;
$("input[title=Target Date],input[id$=UserField_hiddenSpanData],input[title=Start Date],select[title=Strategic Objective]").each(function(){
var txt = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_UserField_hiddenSpanData').val();
var val = $(this).val();
if($(this).is(':hidden') || (val != 0 && val.length != 0 && txt.length != 0)) {
//add one to the counter
controlsPassed += 1;
}
});
return (controlsPassed == 4)
}
}
function PreSaveItem()
{
return checkControls()
}
Okay, so this is the problem I see in your current script: binding an event handler is permanent, so if you choose "Milestone Action" even once and then switch to another option, you will still validate the original selection.
You can do away with all the change handlers and instead add your conditions directly in checkControls, validating the necessary elements based on the current selection. I've also replaced your ifs with a switch since it's cleaner:
function checkControls() {
var itemLevel = $("select[title='Item Level']").val();
switch (itemLevel) {
case 'Strategic Objective':
// Perform validation for this item level
return result; // true or false
case 'Milestone Action':
// Perform validation for this item level
return result; // true or false
// etc...
}
}
Update: For example, if when "Milestone Action" is selected, you would like to check if some text field is not empty, then under case 'Milestone Action':, you would add something like this:
if ($('something').val().length > 0)
return true;
else
return false;
Edit: If you have access to the form code (I'm not familiar with SharePoint), you should assign IDs to your form elements so you can reference them like $('#itemLevel') instead of having to use a long selector.

Categories

Resources