What I'm trying to achieve is a code checker. Only the first 4 numbers are important, the other numbers can be any number. The form will be used for users to put in productcodes.
The problem is that if the variable changes to say, 5 numbers the variable is false.
See below example:
http://jsfiddle.net/MZfxs/3/
If the user puts in the numbers 3541 the box changes color, but if the user put in the remaining numbers the value is set to false.
Additionally I'm trying to make the box only change color when 13 numbers are inserted AND the first 4 numbers are matching, in that order.
Solved!
Working Example:
http://jsfiddle.net/MZfxs/8/
If I understood correctly, you need a field value validation and the requirement is the value should start from 4 numbers like 7514 or 9268. Here you can use a regular expression to validate input value like:
// Will work for " 123433 " or "12345634 ", etc.
var value = $(this).val(),
re = /^\s*(\d{4})(\d+)\s*$/, // better to initialize only once somewhere in parent scope
matches = re.exec(value),
expectedCode = 3541,
expectedLength = 13;
if(!!matches) {
var code = matches[1]; // first group is exactly first 4 digits
// in matches[2] you'll find the rest numbers.
if(value.length == expectedLength && code == expectedCode) {
// Change the color...
}
}
Also if your requirement is strict to length of 13 than you can modify the regular epression to
var re = /^(\d{4})(\d{9})$/;
and retrieve first 4 numbers in first group and rest 9 in second group:
var matches = re.exec(value);
if(!!matches) {
var first4Digits = matches[1],
rest9Digits = matches[2];
// ...
// Also in this way you'll not need to check value.length to be 13.
}
You can break the string each time on key event fires. You can do this by calling js substring() method and take the first four characters and check it.
Try to use this:
<script>
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
var value2 = $(this).val().substr(0,4);
if(value2 == 3541){
$(".square").css("background-color","#D6D6FF");
}else{
$(".square").css("background-color","yellow");
}
})
</script>
Related
i have to compare a string value from a dropdown with a string entered in a text box. the first 4 numbers itself have to be compared and if matches - pass..
FYI- the text box will be having 16 numbers, but it has to compare only the first four number.
problem below is - it doesnt work when i try to enter more than four numbers
Thanks
<script>
function display()
{
var a=document.getElementById("myList");
var dropdownvalue = a.options [a.selectedIndex].text;
var b=document.getElementById("myText").value;
if(dropdownvalue == b) {
document.getElementById("result").innerHTML = "Pass";
}
else {
document.getElementById("result").innerHTML= "Fail";
}
}
</script>
substring will help you here to grab the first 4 characters before condition check with drop down value. Something like,
if(dropdownvalue == b.substring(0, 4)) {
document.getElementById("result").innerHTML = "Pass";
}
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring
Please use indexOf property, you can solve the problem:
if (dropdownvalue.indexOf(b) > 0) {
// todo
}
You're comparing the values of dropdownvalue and b with an equality comparison (==). If you want to compare only the first four characters, you'll need to retrieve only the first four and compare those. There are a couple of different options.
Option 1: Substring
if (dropdownvalue == b.substring(0, 4)) {
...
}
Option 2: String.prototype.startsWith
if (b.startsWith(dropdownvalue)) {
...
}
You didn't say if the dropdownvalue is always four characters, or if it's longer as well. If the dropdownvalue can also be more than four characters, you'll need to apply the substring to it in both options: dropdownvalue.substring(0, 4).
I want to grab the user input from an input tag including everything after the # symbol and up to a space if the space exists. For example:
If the user input is "hello#yourname"
I want to grab "yourname"
If the user input is "hello#yourname hisname"
I want to grab "yourname" because it is after the # symbol and ends at the space.
I have some code written that attempts to grab the user input based on these rules, but there is a bug present that I can't figure out how to fix. Right now if I type "hello#yourname hisname"
My code will return "yourname hisn"
I don't know why the space and four characters "hisn" are being returned. Please help me figure out where the bug is.
Here is my function which performs the user input extraction.
handleSearch(event) {
let rawName, nameToSearch;
rawName = event.target.value.toLowerCase();
if (rawName.indexOf('#') >= 0 && rawName.indexOf(' ') >= 0) {
nameToSearch = rawName.substr(rawName.indexOf('#') + 1, rawName.indexOf(' ') - 1);
} else if (rawName.indexOf('#') >= 0 && rawName.indexOf(' ') < 0) {
nameToSearch = rawName.substr(rawName.indexOf('#') + 1);
} else {
nameToSearch = '';
}
return nameToSearch;
}
Working example:
handleSearch(event) {
let rawName = event.target.value.toLowerCase();
if (rawName.indexOf("#") === -1) {
return '';
}
return (rawName.split("#")[1].split(" "))[0];
}
You have to handle a lack of "#", but you don't need to handle the case where there is a space or not after the "#". The split function will still behave correctly in either of those scenarios.
Edit: The specific reason why OP's code doesn't work is because the substr method's second argument is not the end index, but the number of characters to return after the start index. You can use the similar SUBSTRING method instead of SUBSTR to make this easier. Change the line after the first if statement as follows:
nameToSearch = rawName.substring(rawName.indexOf('#') + 1, rawName.indexOf(' '));
const testCases = [
"hello#yourname",
"hello#yourname hisname"
];
for (let test of testCases) {
let re = /#(.*?)(?:\s|$)/g;
let result = re.exec(test);
console.log(result[1]);
}
Use regex instead if you know how the string will be created.
You could do something like this--
var string = "me#somename yourname";
var parts = string.split("#");
var parts2 = parts[1];
var yourPart = parts2.split(" ");
console.log(yourPart[0]);
NOTE:
I am suggesting it just because you know your string structure.
Suggestion
For your Piece of code I think you have some white space after hisn that is why it is returning this output. Try to replace all the white spaces with some character see if you are getting any white space after hisn.
I'm not sure of the language your code is in (there are several it 'could be', probably Javascript), but in most languages (including Javascript) a substring function 'starts at' the position of the first parameter, and then 'ends at' that position plus the second parameter. So when your second parameter is 'the position of the first space - 1', you can substitute 'the position of the first space - 1' with the number 13. Thus, you're saying 'get a substring by starting one after the position of the first # character i.e. position 6 in a zero-based system. Then return me the next 13 characters.'
In other words, you seem to be trying to say 'give me the characters between position 6 and position 12 (inclusive)', but you're really saying 'give me the characters between position 6 and position 18 (inclusive)'.
This is
y o u r n a m e h i s n
1 2 3 4 5 6 7 8 9 10 11 12 13
(For some reason I can't get my spaces and newlines to get preserved in this answer; but if you count the letters in 'yourname hisn' it should make sense :) )
This is why you could use Neophyte's code so long as you can presume what the string would be. To expand on Neophyte's answer, here's the code I would use (in the true branch of the conditional - you could also probably rename the variables based on this logic, etc.):
nameToSearch = rawName.substr(rawName.indexOf('#') + 1;
var nameFromNameToSearch = nameToSearch.substr(nameToSearch.indexof(' ') - 1;
nameFromNameToSearch would contain the string you're looking for. I haven't completely tested this code, but I hope it 'conceptually' gives you the answer you're looking for. Also, 'conceptually', it should work whether there are more than one '#' sign, etc.
P.S. In that first 'rawName.substr' I'm not giving a second parameter, which in Javascript et al. effectively says 'start at the first position and give me every character up to the end of the string'.
I need help when you enter a single digit month in a date of birth that will automatically add a 0 digit in a single digit in an input.Here's my code:
$('#dob_dd').blur(function(){
var addzero = $('#dob_dd').val().length;
if (addzero.length != 2) {
addzero = '0' + addzero;
} else {
return addzero;
}
});
If you want to update the displayed value. it's as simple as
$('#dob_dd').blur(function(){
var $this = $(this);
$this.value(('0' + $this.value()).substr(-2));
});
This will function correctly if the selector selects multiple targets as well
You already specify that you want to check the length of $('#dob_dd'). So maybe it should be :
if (addzero != 2)
Then of course you need to update the value using for instance $('#dob_dd').val("new value")
I have a number of HTML inputs in a website. They are inside a form, but the form is not submitted to the server. Rather, values of the assorted inputs (number inputs, text inputs, and check boxes) are used to ultimately 'stitch together' a product code based on the inputs and selected options. (using JavaScript)
My problem is this: while the number input
<input type='number'/>
only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called.
What I need is a way to detect if a given string contains an alphabetical character, instead of just numbers. My idea was something like this:
<input type='number' id='inp' />
<script>
input=document.getElementById('inp');
val=input.value;
checkforletters(val);
input.onchange=function(){
if(checkforletters){
//resetting the value to blank if there is an alphabet character in the string
input.value='';
}
}
</script>
You'll notice that there is a function in there called
checkforletters()
I have not written it. This function would check and see if there is an alphabet character inside the string that comes from the value of my input; and if there is, the function would return true.
This function is what I need. The rest of the code resets the value of the input to blank if there is an alphabet character.
So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise.
Note
Please use pure JavaScript only. No jQuery or other libraries/frameworks.
You can use isNaN() function to make your own function that check if the given string is numeric :
//Will return true if the given string is number, false if is contain characters
function isNumeric(yourString){
return !isNaN(yourString)
}
Hope this helps.
My problem is this: while the number input only allows a number value when used in a server-side submit, I am using JavaScript to check the assorted values of the different inputs. This allows for a letter (alphabet) character to be put in the number input. IF you do this, the input becomes outlined in red, but it still allows the function that stitches together the product code to be called.
You can utilize the built in HTML5 constraint validation with JavaScript. This means that instead of having to check whether the value is valid, the value can never be invalid to begin with.
The following example will disallow any invalid input at the user level. It does this by checking the validity then storing the value for future use if it is valid or, if the value is not valid, setting the value to the previously stored valid value if there is one, an empty string if not.
This means that the value can never be invalid.
<input type="number"
oninput="(validity.valid&&(dataset['prev']=value))||(value=dataset['prev'])">
The following is the same method, without using inline JavaScript
document.getElementById('test').oninput = function() {
if(this.validity.valid) this.dataset['prev'] = this.value;
else this.value = this.dataset['prev'];
}
<input type="number" id="test">
So, to summarize, what I need is a function that, when passed a string as an argument, returns true if there is an alphabet letter in it, and false otherwise.
If a number input's value is invalid, it will return an empty string.
This means that you cannot compare the returned value to check it's validity, because if it is in fact invalid the returned value will be an empty string.
The following example shows that even if the value is invalid, checking it with isNaN won't show you that, nor will any of the other methods mentioned here.
<input type="number" oninput="document.getElementById('value').textContent = value; document.getElementById('isnum').textContent = !isNaN(value)"><br>
Returned Value: <span id="value"></span><br>
Is a number: <span id="isnum"></span>
If you really want to validate the input element while running your script, you can check the input element's validity at that time.
var test = document.getElementById('test');
document.getElementById('button').onclick = function(e) {
if(!test.validity.valid) {
alert('Its Invalid!');
} else {
alert('Its valid!');
}
}
<input id="test" type="number"><button id="button">Check It</button>
Alternatively, if your input elements are inside a form and you run your script on the form submission event, it will automatically validate for you, and disallow submission unless the value is valid.
var test = document.getElementById('test');
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
alert("Its valid!"); // this will only happen if the inputs are valid.
}
<form id="form"><input id="test" type="number"><button>Check It</button></form>
Use a regular expression that matches any non-digits.
var myString = 'aaaaa1';
var reg = new RegExp(/\D+/);
console.log(reg.test(myString));
// true
here is simplest way- handle onkeyup:(http://jsfiddle.net/vittore/g7xe0drp/)
var inp2= document.getElementById('inp2')
inp2.onkeydown = onlyNumbers
function onlyNumbers(e) {
console.log(e)
if (e.which <=49 || e.which >=57) {
e.preventDefault()
return false;
}
}
Check that string contains only numbers (\d):
function checkforletters(val) {
var pattern = /^\d+$/;
return pattern.test(val);
}
If you need other characters beside numbers instead of \d use [\d,-] (, and - are characters that you want to allow).
Please use this to check for alphabets or special characters in your input:
checkforletters(val){
var pattern = /[\D]+/
if (pattern.test(val)) {
// val contains a non-digit character, it contains alphabet or special character
}
else{
// val only contains digits
}
}
pattern.test(val) will only return true if val contains alphabet
You could try this I found on the filter page of developer mozilla org.
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
array filter
Of course you will need to rework it a little to make isString(), you could try typeof(obj) === 'string' && isNaN(obj).
you can get a list of obj from a string with theString.split('')
For example:
let s = 'Is this 1 or 2 and not 3 strings? .! : '
let c = s.split('')
let d = c.map((c,i) => {
let v = typeof(c) === 'string' && isNaN(c) ? 'string': 'not-string'
return {c, v}
})
console.log(d)
I have a string that contains a number, eg,
images/cerberus5
The desired result
images/cerberus4
How can I subtract 1 from the '5' in the first string to obtain the '4' in the second?
This is a raw example, but you could do something like this:
$old_var = 'images/cerberus4';
$matches = [];
$success = preg_match_all('/^([^\d]+)(\d+)$/', $old_var, $matches);
$new_val = '';
if (isset($matches[2]) && $success) {
$new_val = $matches[2][0].((int)$matches[2][0] + 1);
}
It's not meant to be the perfect solution, but just to give a direction of a possible option.
What the RegEx doesn't detect (because it's more strict) is that it won't work without a trailing number (like images/cerberus), but as it seems an 'expected' pattern I also wouldn't allow the RegEx to be more loose.
By putting this code into a function or class-method you could add a parameter to automatically be able to tell the code to add, subtract or do other modifications to the trailing number.
function addOne(string){
//- Get first digit and then store it as a variable
var num = string.match(/\d+/)[0];
//- Return the string after removing the digits and append the incremented ones on the end
return (string.replace(/\d+/g,'')) + (++num);
}
function subOne(string){
var num = string.match(/\d+/)[0];
//- Same here just decrementing it
return (string.replace(/\d+/g,'')) + (--num);
}
Don't know if this is good enough but this is just two functions that return the string. If this has to be done via JavaScript so doing:
var test = addOne("images/cerberus5");
Will return images/cerberus6
and
var test = subOne("images/cerberus5");
Will return images/cerberus4