javascript conditional returning unexpected result - javascript

I'm doing a simple number comparison on the keyUp event of an input field. For some reason, I'm not getting the expected result, and I can't figure out why. What should happen is that if the user-entered number is larger than that stored in the html attribute, the background should turn red, otherwise it stays white. Simply entering '9' will turn the background red. ??
var admin = $('input[name="diskStorage"]').attr('data-adminstorage'); // 2097152000
$('#new-user input[name="diskStorage"]').keyup(function(){
if(admin < $(this).val())
$(this).css('background','red');
else
$(this).css('background','white');
});
When I debug these values, if(2097152000 < 549) is returning true. Here's the html, in case that makes any difference:
<form action="administrate.php" method="post" id="new-user">
<table><tbody><tr>
...
</tr><tr>
<td>Disk Storage Limit:</td>
<td>
<input type="text" data-adminStorage="2097152000" name="diskStorage" value="" /> megaBytes<br />
<span id="info"></span></td>
...
</tr></tbody></table>
Here it is live: http://jsfiddle.net/JMC_Creative/dqAJj/2/

.attr and .val() return String objects - use the unary + operator to convert it to a numeric value.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage');
admin = +admin;
if(admin < +$(this).val()) {
//...
}

Try adding a /1 after retrieving the admin value, to make it a number not a string.
var admin = $('input[name="diskStorage"]').attr('data-adminstorage')/1;
Edit: also on the this.val:
$(this).val()/1;

They are probably both strings. You should convert them to numbers first:
var admin = Number($('input[name="diskStorage"]').attr('data-adminstorage')); // 2097152000
$('#new-user input[name="diskStorage"]').keyup(function(){
if(admin < Number($(this).val()))
$(this).css('background','red');
else
$(this).css('background','white');
});

Related

How do a maintain an accurate character count between input from separate fields using JS?

I am using a form to build a block of text, the final output of which needs to be kept under a certain character count.
For the user, I need to be able to provide real-time character counting so they can adjust their entries as appropriate.
Basic HTML would be as follows:
<form>
<input type="text" id="#input1">
<input type="text" id="#input2">
</form>
<div class="character-counter">0</div>
However my JS/jQuery is not working very well: while it is outputting a counter in real time, it seems to be concatenating the final results in the output despite me parsing the variables as integers.
$('#input1').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
$('#input2').keyup(function() {
// Variables
var currentCharCount = parseInt($('.character-counter').text());
var fieldLength = parseInt($(this).val().length, 10);
var newCharCount = fieldLength + currentCharCount;
// Counter output
$('.character-counter').text(Number(newCharCount));
});
The correct solution will update the '.character-counter' div with the correct total character count between the fields every time a character is typed or deleted or pasted in.
Thanks!
You don't want the old value of the character-counter element at all, you purely want to use the lengths of the text in the two inputs. Separately: Don't use keyup, use input. (What if the user right-clicks and pastes? No keyup occurs...)
Separately, the id attributes of your input fields are incorrect: They shouldn't have the # on them.
So (see comments):
// You can hook the event on both fields with the same call
// Note using `input`, not `keyup`
$("#input1, #input2").on("input", function() {
// Get the length of each input's current value, then put it
// in the .character-counter div
$('.character-counter').text($("#input1").val().length + $("#input2").val().length);
});
<form>
<input type="text" id="input1">
<!-- No # here --------^ -->
<input type="text" id="input2">
<!-- Nor here ---------^ -->
</form>
<div class="character-counter">0</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

jquery if input contains phrase from array-child friendly global chat

I have found some code for a chat system. I am going to be using it as a child-friendly (so I can't be blamed for anything) global chat. The way the code works is by checking the input to see if it contains any word from an array, if it does then the program will display something to a <ol> tag, for me to see if it works. Otherwise is does nothing.
JQUERY
var banned_words = {
'songs': ['hello', 'sorry', 'blame'],
'music': ['tempo', 'blues', 'rhythm']
};
function contains(words) {
return function(word) {
return (words.indexOf(word) > -1);
};
};
function getTags(input, banned_words) {
var words = input.match(/\w+/g);
return Object.keys(banned_words).reduce(function(tags, classification) {
var keywords = banned_words[classification];
if (words.some(contains(keywords)))
tags.push(classification);
return tags;
}, []);
};
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
$('#tags').empty();
var tags = getTags($(this).val().toLowerCase(), banned_words);
var children = tags.forEach(function(tag) {
$('#tags').append($('<li>').text(tag));
});
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
HTML
<form id="send-message-area">
<p style="text-align:center">Your message: </p>
<input id="sendie" maxlength = '100' />
</form>
<ol id="tags">
</ol>
But, what I'm also wanting to do is check if the input value contains phrases from the array so I can ban phrases that are too sensitive for children. How can I add this in, or is there another more efficient way to check the input?
UPDATE
I have already tried to place the phrase directly into the banned_words (I changed them as this post would get flagged for inappropriate language) and using the hexadecimal character for the space-bar. None of these worked.
You can try either of the following since the space is also a known charachter:
test 1:
Just put your phrase between quotes such as 'cry baby','red apple' etc.
sometimes it does not work, you can try
test 2:
replace the space with the hexidecimal character \x20 such as 'cry\x20baby','red\x20apple'
I hope one or both of these works for you.
I have done some more research and have found a cool plugin for JQuery. It's called jQuery.profanityFilter. It uses a json file filled with sensative words.
Link to github download: https://github.com/ChaseFlorell/jQuery.ProfanityFilter

passing element id to function as parameter

this is my .js function
function validateSNo(inputtxt,elem){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(inputtxt)){
document.getElementById(elem).innerHTML = "";
return true;
}
else {
document.getElementById(elem).innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
this is the html code
<label>Student No.</label>
<input type="text" name="sNo" size="6" maxlength="6" onblur="return validateSNo(document.FormStuReg.sNo.value,sNo-validation)" autofocus><span class="errorMsg">*</span>
<br>
<span class="errorMsg" id="sNo-validation"></span>
i want to display the validation message in the span area when an invalid input is detected.this code doesn't work..It works fine without the parameters when the function is written like this.
function validateSNo(){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(document.FormStuReg.sNo.value)){
document.getElementById("sNo-validation").innerHTML = "";
return true;
}
else {
document.getElementById("sNo-validation").innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
}
I have to use the same validation in few other places so its better if i can pass the values as parameters to single function or else i have to write the same function over n over again with different element id's.
Look at the onblur attribute in your HTML.
onblur="return validateSNo(document.FormStuReg.sNo.value,sNo-validation)"
Notice that sNo-validation is not in quotation marks. That means that it's interpreted as two variables: sNo and validation, which are undefined, and the - is interpreted as a minus sign. Subtracting two undefined variables doesn't make sense, so that's why you get an error.
Just add quotation marks. Since it's already inside quotation marks because it's an HTML attribute, use single quotes.
onblur="return validateSNo(document.FormStuReg.sNo.value, 'sNo-validation')"
BTW, since you are using a scheme like sNo and sNo-validation then you don't need to pass the ID. I'll guess that document.FormStuReg.sNo.value is the input that the listener is on, so you can just pass a reference to the element using this:
<input ... name="sNo" ... onblur="return validateSNo(this)" ... >
And then in the function:
// element will reference the input
function validateSNo(element){
var SNoFormat = /^\d{6}$/;
if (SNoFormat.test(element.value)){
// Use the element name to get the message element
document.getElementById(element.name + "-validation").innerHTML = "";
return true;
}
else {
document.getElementById(element.name + "-validation").innerHTML = "This should only contain 6 numbers XXXXXX";
return false;
}
}
and the if..else can use the conditional ? : operator:
document.getElementById(element.name + "-validation").innerHTML = SNoFormat.test(element.value)? '' : 'This should only contain 6 numbers XXXXXX';
Returning true or false from the listener has no effect whatever.
If you take this one step further, you can define the validation to run in a class value or data- attribute, then you don't need to pass anything. Just validate all form controls based on their class or data- values.

I have issues with my JavaScript

I don't what happen with my script can i please point out where is my mistake. 1 to 9 all condition working fine but when you put 10-12 is not work
<form method="post" enctype="multipart/form-data" action="#">
<input type="hidden" value="2" id="itemstock" name="itemstock">
<input value="1" name="quantity" id="quantity" class="text">
<button type="submit" onClick="return checkoption();" >Click </button>
</form>
Javascript
function checkoption()
{
var itemqty = document.getElementById('quantity');
var iss = document.getElementById('itemstock');
if(itemqty.value > iss.value)
{
alert('We have Currently '+iss.value+' In Stock');
}
else
{
alert('add to cart');
}
}
Thank you in advance
Screen short see qty i put 13 but its not showing error
Using the < or > operators with strings will compare the values alphabetically, which is probably not what you want.
You need to compare these as numbers, not as strings. JavaScript allows you to easily cast a string to a number using +, like so:
var qty = +itemqty.value;
var isv = +iss.value;
if(qty > isv)
{
// ...
}
However, you can also use parseInt (which will return NaN if the value is invalid) if you want to add more error checking in your code.
The .value attribute on a text field such as input is a string, not a number. Therefore, you compare strings lexicographically. Change them into numbers, either via parseInt(str, 10) or via +str.

Change color of text if value becomes > original value, Jquery

I have a div that looks like this:
<div class="Value">
<em id="ProductPrice" class="ProductPrice VariationProductPrice">$83.00</em>
</div>
I need a script that changes the color of the price value to red if it changes.
I started with this:
var original_value = $("#ProductPrice").text()
if ($("#ProductPrice").text() > original_value) {
$("#ProductPrice").css("color","red");
}
It doesn't work at all, but I don't get any errors.
Also the price value is set by a variable and can change based on what page it is on.
Any input is appreciated! Thanks!
You are comparing strings, not numbers. Convert your string to a number.
Basic idea to get the number:
var str = "$12.23";
var muNumber = parseFloat(str.replace("$",""));

Categories

Resources