Im making a little form where you can pick your value.
If the value is not filled in correctly(I have given some example answers)
I want an alertbox to pop-up which indicates the incorrectly filled in textfields.
Cant seem to make it work...
This is what I tried
if(document.getElementById("BS").value.match ("thin","thick","medium")
{
alert("Fill in the correct values");
}
Here is the fiddle.
http://jsfiddle.net/vuc8Z/
Here is my suggestion:
var val = document.getElementById("BD").value;
if (!(val == "thin" || val =="thick" || val =="medium")) {
alert("Vul een geldige waarde in bij de aangegeven velden");
}
Demo here
Notice that you were using getElementById("BS"), but you wanted BD i think. I changed your match function to a triple || (or) if statement.
I moved your if statement to inside the "go" button click handler so it is fired when the button is clicked.
The match() function expects a regex, you can read more here (MDN: .match()).
EDIT:
To check if the color text input is in the right format you can use this:
var filter = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
if (!color.match(filter)) {
alert('Color code Error!');
}
Updated demo here
If you want to use match method then you can use like :
var str = document.getElementById("BD").value;
if(str.match('thin') || str.match('thick') || str.match('medium'))
{
alert("Fill in the correct values");
}
As per my knowledge match takes regular expression as parameter and don't take multiple values.
Related
I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.
my code:-
<div myCondition="1 == 2" id="hey"></a>
<script>
var a = document.getElementById('hey');
var x = a.getAttribute('myCondition');
if(x){
console.log('accepted')
}else{
console.log('not accepted')
}
</script>
above program should return not accepted
value of myCondition attribute can be very complex for example:-
'hello' == 'hello'
5>1 etc
I guess what you need is the eval function. As it says in the provided link:
The eval() function evaluates JavaScript code represented as a string.
So, you can change your code like this:
if( eval(x) ){
console.log('accepted')
}else{
console.log('not accepted')
}
P.S: That being said, I don't think doing it like this really safe.
How would you, with JS or jQuery, determine if what the user is typing is a new word?
What I want to do:
I am writing a documentation tool with autocompletion for different types. If you type f.e. # it will populate Java Classes in a box, # would populate test classes, etc. Now I don't want to populate these values, if the user is writing something like an email like yourname#domain.com. So I need the values to populate only when it's the beginning of the word.
I am aware of keydown, keyup events, etc. I just don't know how to check for this certain kind of event properly.
One way would be to save every typed letter in a variable and then check if the previous "letter" was a space and if it was, we know it's a new word. Is this the best/most efficient way to do this?
One way is to check what's before the # in the input box, using selectionStart:
onload = function() {
var io = document.getElementById("io");
io.onkeypress = function(e) {
if(e.charCode == 64 && (
io.selectionStart == 0 || io.value[io.selectionStart-1].match(/\s/)))
document.getElementById("ac").innerHTML = "autocomplete!";
else
document.getElementById("ac").innerHTML = "";
}
}
<input id="io">
<div id="ac"></div>
Try this JSFiddle. I'm performing the check like so:
var text = $("#test").val();
if (text.length == 0 || text.charAt(text.length - 1).match(/[\s\b]/)) {
$("#result").html("new word");
} else {
$("#result").html("no new word");
}
You can easily adapt the .match() pattern if you like to include other characters as "whitespaces" (e.g. curly braces) for your Editor.
Assuming text is entered in a text input with id="txtchangedetection":
$("#txtchangedetection").change(function(){
console.log("The text has been changed.");
});
/*This is `JQuery`*/
I've understood you want to detect word changes in the input. Please precise if I'm wrong. What do you mean by 'new word' ?
One solution will be like this :
1- declare a variable "newWord = true"
2- with keydown event check if the key pressed is a space
if YES : newWord = true
if NO : newWord = false
var newWord=true;
$("#textarea").keydown(function(e){
if(e.keyCode == 32){
newWord=true;
}else{
newWord=false;
switch(e.keyCode){
//work to do
}
}
})
use keypress on your input field... populate the array inside the if with your special chars
if(prev == 13 || prev == 32 || $('#doc').val().length==0 || prev==null){
listen = true;
}else{
listen = false;
}
prev = e.which;
if(listen && $.inArray(String.fromCharCode(e.which),["#","#"]) != -1){
e.preventDefault();
alert("populate box here");
listen = false;
prev = null;
}
the fiddle https://jsfiddle.net/6okfqub4/
I have a unit conversion script; my HTML contains radio buttons (to pick the units), an input field, an output field and a button.
Here's a sample of my Javascript file:
[...]
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
document.getElementById("answer").innerHTML = convertObj.converted(initial);
});
[...]
});
function ConvertClass(){}
ConvertClass.prototype.converted = function(initialAmount){
if(document.getElementById("kilograms").checked) {
this.calculation = this.multiply(initialAmount, 2.2046);
} else if(document.getElementById("pounds").checked) {
this.calculation = this.divide(initialAmount, 2.2046);
}
return this.calculation.toFixed(2);
}
[...]
var convertObj = new ConvertClass();
I would like to add something that ensures a) an empty input field isn't considered a "0", and b) something other than a number doesn't display "NaN" as the answer. In both cases, I'd simply like my output to return nothing (blank). I don't want it to do nothing, in case the user submits a blank field or an invalid value after a correct number submission (which I think would result in the previous answer still being displayed.)
How do I write that? I'm assuming I should use conditions, but I don't know which ones. I did a bit of research and apparently using isNaN() isn't entirely accurate, at least not in this context.
Where do I put the code, in the function triggered by the page load or the one triggered by the button?
I'm still learning so, if possible, I'd really appreciate explanations along with the edited code. Thank you!
Inside ConvertClass.prototype.converted at the beginning of the function, add:
// this coerces it to a number instead of a string
// or NaN if it can't convert to a number
initialAmount = initialAmount.length > 0 ? +initialAmount : 0/0;
// if not a number, return empty string
if (isNaN(initialAmount)) {
return "";
}
If the input is an empty string 0/0 evaluates to NaN.
Add the following function to check whether a value in Integer.
function isInt(value) {
return !isNaN(value) &&
parseInt(Number(value)) == value &&
!isNaN(parseInt(value, 10));
}
Change your load function like this:
window.addEventListener("load", function(){
document.getElementById("convert").addEventListener("click", function(){
var initial = document.getElementById("initial").value;
if(isInt(initial)){
document.getElementById("answer").innerHTML = convertObj.converted(initial);
}else{
document.getElementById("answer").innerHTML = '';
}
});
This will make sure that when a valid integer is supplied then only it will convert otherwise answer remain empty.
For further reading on how to check integer check this:
How to check if a variable is an integer in JavaScript?
Edit: setting answer to empty string when number not integer.
I need to replace a code example: OD3 - The first must always be alpha character, 2nd alphanumeric and the last must always be numeric. What's the regular expression to check and replace the first and regulate the rest to enter correctly? A user could enter in the number 0 instead of the letter O, so I want to correct it immediately...
this is what I have so far: onkeyup="this.value=this.value.replace(/[^a-zA-z]/g,'')
First, I'd suggest just indicating the error to a user instead of replacing the values. Something like
oninput="if (! /^[a-z][a-z0-9]\d$/i.test(this.value) ) displayMessage('incorrect code');"
If you definitely have to replace the value on the fly, you could do somthing like that:
oninput='validateValue()';
...
function validateValue() {
var val = this.value;
if (! /[a-z]/i.test(val[0]) this.value = '';
else if (! /[a-z0-9]/i.test(val[1]) this.value = val.slice(0,1);
else if (! /\d/.test(val[2]) this.value = val.slice(0,2);
}
Better have like this.
onkeyup="testRegex(this.value)";
It is not .replace() it is .test()
function testRegex(value) {
if(value.test(/[^a-zA-z]/g)) {
alert("Please enter correct value");
return false;
}
}
This might be some odd question but it is the problem I am facing. I have textBox with Id like:
"pax_9495237e-5c9e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9h7e-489f-8700-2f82e211fd51__Age"
"pax_9495237e-9k2e-489f-8700-2f82e211fd51__Age"
Now I want to check if all Textboxes consist of __Age at the end, has numeric value or not. If not numeric(INT) i.e. characters(no .) not allowed then make an alert.
Please help me I don't know how to do it. I know I have a class option but I want to do by Id.
To select you input, you can use this :
$('[id$="__Age"]')
Then to know if is a number
$('[id$="__Age"]').each(function(){
if(isNaN(parseInt($(this).val()))){
alert(this,id + ' is not a number');
}
})
Fiddle : http://jsfiddle.net/3B9Vp/
In order to get all input ending with "__Age" you can use the jquery selector
jQuery( "[attribute$='value']" )
You can find more details here
So, in your occasion you can call:
$('input[id$="__Age"]');
where all text boxes with an id ending in "__Age" will be returned.
In order to validate if the input is numeric you can check the value of each textbox and use isNaN function provided in Javascript
Here is an example where there are 3 text boxes and you call a function to check if their current value is numeric or not.
Try like this
$(document).ready(function(){
$("input[type='text'][id$='__Age']").each(function(){
if(isNaN(parseInt($(this).val())))
alert('Not an Integer');
else
alert('It is an Integer');
});
});
It will check all the textbox values that are ids ended with '__Age'
Something like:
$("textarea").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; })
http://api.jquery.com/filter/
http://api.jquery.com/jQuery.inArray/
How to check whether a string contains a substring in JavaScript?
Working Example
// an array of e.which|e.key codes that is every key code for every number and control (like shift, backspace, etc..)
var numsNcontrols = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,8,9,13,16,17,18,19,20,32,33,34,35,36,45,46,44,145,37,38,39,40];
// first grab all inputs ending with "__Age", then asign "keydown" check for improper characters
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).on("keydown", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) return false;
}) // now, using jQuery Chaining, we continue and asign keyup event to alert users they cannot enter anything but numbers
.on("keyup", function(e) {
if ($.inArray(e.which, numsNcontrols) == -1) alert('Numbers only please!');
})
// simple check value update to show how many textboxes end in "__Age"
$("#bil").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1; }).length
+ " textboxes have __Age at end of ID."
);
// Shows in a textbox how many textboxes end in "__Age" && have a numeric value
$("#bad").val(
$("input[type=text]").filter(function(i) { return $(this).prop("id").indexOf("__Age") !== -1 && !isNaN(parseInt($(this).val())); }).length
+ " textboxes have __Age at end of ID && numeric value."
);
¡ALSO! Find a pretty full listing in one big object (full of smaller objects and arrays) of Key Codes here
If you only need to show one alert when any of the inputs with __Age at the end has nonNumeric values then you can try something like this:
if($("input[type='text'][id$='__Age']").filter(function(){
return !isNaN($(this).val()); //leave only those inputs with nonNumeric value
}).length) //count their lenght - if it's > 0 then show alert
alert('There are inputs with "nonNumeric" values!');