Want to have a notification box displayed if amount in fieldA is higher than amount in fieldB.
Currently have some code working but the notification box toggles on and off not depending on the actual amount.
What am I missing?
jquery:
$(document).ready(function() {
$('#fieldA').change(function(){
if($(this).val()>$('#fieldb').val()){
//display it on the form
$('.labelNotification').toggle();
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
HTML:
< p style="display: none;" class="error labelNotification">
This is tailor-made for the toggle(boolean) method. Also, you have to be careful about appending to the notification label ... what if the user changes his answer twice? It's better to have multiple notification objects, each of which can contain stuff for a single type of notification.
$(function() {
$('#fieldA').change(function() {
var isLarger = +$(this).val() > +$('#fieldB').val(); // Note: convert to number with '+'
var $labelNotification = $('.labelNotification');
$labelNotification.toggle(isLarger);
if (isLarger) {
//display it on the form
$labelNotification.html('Not recommended to have FieldA figure higher than FieldB.');
}
})
});
If you're comparing numerical values (which it seems like you are), you should use parseInt or parseFloat to convert the (string) value returned by val() to an integer. According to the documentation for val, the function always returns a string value.
I found the problem ,
First thing is you need to have semicolon properly as below
$('#fieldA').change(function () {
if ($(this).val() > $('#fieldB').val()) {
alert("its greater");
//display it on the form
$('.labelNotification').append('Not recommended to have FieldA figure higher than FieldB.');
$('.labelNotification').show();
}
else {$('.labelNotification').hide();
$('.labelNotification').html('');}
});
Second thing , when you toggle it it won't show for the second time
if 40 > 30
and again if you entery 50 and 50 > 30 it won't show
this is second problem
final problem is empty the label all the time
$('.labelNotification').html('')'
Toggle is not the best approach for your situation.
You want to compare and then decide.
Since you are looking at numbers I would strongly suggest using a number type to do the comparison, either using parseInt() or parseFloat().
The text in the notification label only needs to be set once, since you don't have any comment for it showing something when B > A. I would suggest setting this in your HTML.
<span class="labelNotification" style="display:none">Your Warning Text</span>
<!-- if your CSS class has `display:none` remove the style attribute -->
as for the jQuery.
$(function() {
$("#fieldA").change(function() {
var a = parseInt($(this).val());
var b = parseInt($("#fieldb").val());
// handle if a or b is not a number --> isNaN(a) || isNaN(b)
if( a > b ) {
$('.labelNotification').show()
} else {
$('.labelNotification').hide()
}
});
});
Related
I'm trying to create a simple calculator using jQuery.
I have a paragraph tag that I'm using as a display. After pressing 'AC' button that clears my display the paragraph tag contains '0'.
What I wanna do is when I press a button with a number I need this '0' to be replaced with the number I pressed because now it goes like '07' or '05'.
I tried:
$('#7').on('click', function() {
if ($('#mainline') == '0')) {
$('#mainline').remove('0');
}
$('#mainline').append('7');
})
But I guess I'm doing something wrong. How should I check if #mainline has '0'?
Using regexp is a good way,but if you do not understand regexp,you can try this:
$('#7').on('click', function() {
if ($('#mainline').text() == '0')) {
$('#mainline').text('7');
}else{
$('#mainline').append('7');
}
})
If '#mainline' is a input or textarea,use 'val()' instead of 'text()'
If #mainline is a DIV, get its text, then remove leading zeroes with a regexp, then append 7.
$('#7').click(function() {
$("#mainline").text(function(i, oldtext) {
return oldtext.replace(/^0+/, '') + '7';
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainline">0</div>
<button id="7">7</button>
If it's an input, use .val() instead of .text().
Maybe you can try to get the value $('#mainline').text() then parseInt() or parseFloat() if $('#mainline').text().indexOf('.') > -1.
parseInt() and parseFloat() will automatically remove the excessive ZEROs from head of your string.
I have ran into this problem where I am specifying a Quanitity by both Units and Price. If Units is given, price must also be supplied and if price is given, Units must also be supplied. But they are both blank, then it is ok.
+----------+-------+
| Quantity | Units |
+----------+-------+
| | |
+----------+-------+
I have used the following code to check this condition and it does work for the first instance of the classes but not the proceeding ones.
$(".Quantity").rules("add",{
required:function(element){
return $(".Quantity").next('input').val() > 0;
},
});
$(".Units").rules("add",{
required:function(element){
return $(".Units").prev('input').val() > 0;
},
});
So basically it check only the first value of occurance and not the rest. What I want is it go through complete page and compare prev next value of each occurance. In my case, data is arranged in table and each cell contains Quantity and Price input boxes which I want to retrieve by prev next. but it is not working.
Here is codepen demo. Note that I am using bootstrap dialog as well in the example which shows total number of errors and again it stops at the first instances of the class, not showing all errors because I am using class based rules. Any help would be appreciated.
With this plugin's methods, when using a selector that targets more than one element, you must enclose the method within a jQuery .each()...
$(".Quantity").each(function() {
$(this).rules("add",{
required: function(element) {
return $(".Quantity").next('input').val() > 0;
},
});
});
Otherwise, when you don't use an each(), only the first matching element is considered.
Answering it myself. I had to use the following code to fix my issue
$('.Units').each(function () {
$(this).rules("add", {
onkeyup: false,
required: function (element) {
return element.nextElementSibling.nextElementSibling.value > 0 ? true : false;
},
})
});
$('.Cost').each(function () {
$(this).rules("add", {
required: function (element) {
return element.previousElementSibling.previousElementSibling.value > 0 ? true : false;
},
})
});
The actual code I used is more complicated where prev and next values were dependent on each other.
for example i have a p tag and i have a javascript function to increase it's value by 10 every time when a user click on a button.
HTML:
<p id="test">0</p>
<button id="trigger">test</button>
Jquery:
var empty;
$(document).ready(function() {
$("#trigger").click(function(){
empty = $("#test").html()+10;
$("#test").html(empty);
console.log($("#test").html());
}
})
})
This should update the p tag's number but the console.log always display 0 still.
is there any eorror inside? The below is just an example, i just want to know how to make a if statement run everytime when a user click on a specify button.
You should use parseInt to convert string to integer
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
Read More
var empty;
$(document).ready(function() {
$("#trigger").click(function() {
empty = parseInt($("#test").html()) + 10;
$("#test").html(empty);
console.log($("#test").html());
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">0</p>
<button id="trigger">test</button>
You are adding string to number which results in string only, user parseInt() to covert text into number then do addition, as shown below
Note: your code has one extra } that need to be removed
var empty;
$(document).ready(function() {
$("#trigger").click(function(){
empty = parseInt($("#test").html()) + 10;
$("#test").html(empty);
console.log($("#test").html());
//remove extra } from here
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="test">0</p>
<button id="trigger">test</button>
convert to int parseInt($("#test").html()) and than do 10 +
I am trying to validate a form and I want to be able to toggle the error messages off and on when the user inputs a value into the form field. This is what I have so far that is not working:
$('#uTagNum').blur(function() {
var tagNumber=$(this).val();
if (tagNumber.length < 9){
$('#tagErrorMsg').html('<div>Invalid format.Hover over Tag Number column name to see valid formats</div>');
$('#uTagNum').blur(function() {
$('#tagErrorMsg').hide();
});
});
If the user puts in "Dgfh578" and it is not 9 characters or digits long then I need the tagErrorMsG to appear below the field. If the user deletes what they typed the the error message will disappear unless again they type less then 9 characters or digits.
You have some syntax errors and you probably don't want to use hide(), just clear the HTML for #tagErrorMsg. Have a look at this example - http://jsfiddle.net/jayblanchard/mqeCj/
$('#uTagNum').blur(function () {
var tagNumber = $(this).val();
console.log(tagNumber);
if (tagNumber.length < 9) {
$('#tagErrorMsg').html('<div>Invalid format.Hover over Tag Number column name to see valid formats</div>');
} else {
$('#tagErrorMsg').html('');
}
});
I'm having a problem with my following logic.
Jsfiddle
The logic
var budgetCalc = function (financeBudget, totalCost, remainingBudget, changeOn) {
var reloadCalc = function () {
var formula = parseFloat($(financeBudget).val()) - parseFloat($(totalCost).val());
$(remainingBudget).val(Math.abs(formula.toFixed(0)));
if ( formula >= 0 ) {
$('.toolbar-budget').addClass('is-positive').append('<p>Remaining</p>');
} else {
$('.toolbar-budget').addClass('is-negative').append('<p>Over Budget</p>');
}
};
$(document).ready(function () {
// Price Input
$(changeOn).change(function () {
reloadCalc();
});
$(changeOn).trigger('change');
});
};
What works fine
The interface has multiple selects, inputs and a jQuery sliders that change the value of formula. The logic works fine when the page loads and the formula value is >= 0. If the value is < 0 than the formula works fine as well.
The Issue
If the value of the formula is < 0 and then becomes > 0 again because the user changes the values contributing to formula, the logic does not change the class back to .is-positive unless the page refreshes.
My goal
I want the class of .is-positive to be applied without the page refreshing if the value goes from < 0 to >= 0.
Seems like the simplest solution would be to remove both classes before adding the appropriate one but adding $('.toolbar-budget').removeClass('is-positive is-negative'); before your check:
$('.toolbar-budget').removeClass('is-positive is-negative');
if (formula >= 0) {
$('.toolbar-budget').addClass('is-positive').append('<p>Remaining</p>');
} else {
$('.toolbar-budget').addClass('is-negative').append('<p>Over Budget</p>');
}
jsFiddle example
You use addClass() and do not clear existing classes, so you end up with both classes set. You should remove previously set classes via removeClass() or toggleClass().
Also, I'd recommend to do the same with .append('<p>Remaining</p>'); part, so you don't just append paragraphs but swich them.