Can someone help me with a working html/jquery script that will read the text input of an html textarea box and test if the text input on the box contains a numeric string of 11 characters as part of its content, if it does, the script should come up with a dialog box that will ask if the client will like to reformat that numeric content of the textarea box. if the yes option of the dialog box is selected by the client, the script should then reformat the numeric string by adding spaces after the 3rd, 6th and 9th characters e.g change 08293434565 to 082 934 345 65, and thereafter return the reformatted data into the html textarea box
function Confirm() {
var data = $('#fix').val();
var arr = data.split(' ');
//check if numeric and 11 numbers
if (isNaN(arr[5]) == true && arr[5].length == 11) {
//show popup, if yes run the format function
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
confirm_value.value = "Yes";
format();
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
function format() {
var first = arr[5].substring(0, 4);
var second = arr[5].substring(4, 20);
second = second.replace(/(.{3})/g, "$1 ")
$('#fix').val("This is my mobile number " + first + " " + second);
};
<input type="textbox" id="fix" name="fix" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
Your test for numeric and 11 numbers isn't correct.
function Confirm() {
var data = $('#fix').val();
//check if numeric and 11 numbers
if (!isNaN(data) == true && data.length == 11) {
//show popup, if yes run the format function
if (window.confirm("Message contains numeric characters which might make the message not delivered to some networks. Do you want us to reformat the message ?. This might increase the numbers of pages of the message and the cost?")) {
format(data);
}
} else {
alert('Check number format');
}
}
function format(data) {
var first = data.substring(0, 4);
var second = data.substring(4, 20);
second = second.replace(/(.{3})/g, "$1 ")
$('#fix').val("This is my mobile number " + first + " " + second);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="textbox" id="fix" name="fix" />
<button ID="button1" OnClick="Confirm();" runat="server">Confirm</button>
Related
I'm trying to automatically convert a phone number typed in an input box to (xxx) xxx-xxxx format where x is the phone number someone types in. I can actually get it working when the input box loses focus but I'm trying to also change it once the 10th character is typed in the input. It's working but not until you click the 11th character and I cannot figure out why.
<input type="tel" class='tel' placeholder="(555) 555-1212" maxlength=10>
<div class="result"></div>
var convert_phone = function () {
var phone_num = $('.tel').val();
var phone_check = phone_num.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (phone_check == 0) {
var parts = phone_num.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
$('.tel').val('('+parts[1]+') '+parts[2]+'-'+parts[3]);
}
}
$('.tel').on('keypress', function () {
var current_val = $(this).val().length;
$('.result').text(current_val);
if (current_val == 10) {
convert_phone();
}
})
$('.tel').on('blur', function() {
convert_phone();
})
JSFiddle: https://jsfiddle.net/s6frnp2k/3/
The result div is just there to show click value and isn't needed for the final version.
Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online
I had a task to enter a °F and convert it to °C. I also has to show a error messege instead of a number if entered value is not a number. What ever I do I can't get it to work properly. When I type letter it just shows -17.77777777777778 °C instead of messege. Can I get some help from you ?
function temperatura(){
var temp = document.getElementById("tempF").value;
if (isNaN(temp)){
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
}
}
function uCelzije(f){
return (5/9) * ( Number(f) - 32 );
}
<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
<input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p><br>
It's because your input is type of number. If you type a letter, this value is not accepted and it remains an empty string:
isNaN(''); // false
then this empty string is converted to 0 in your uCelzije function:
(5/9) * ( 0 - 32 ); // -17.77777777777778
so you should also check if the input isn't empty, e.g.:
if (temp == '' || isNaN(temp)){
Antonio, if i understood well, maybe you only need to add a new validation to check an empty string, following how you construct your code. Try to add an empty string validation to your script.
var temp = document.getElementById("tempF").value;
if (isNaN(temp) || temp.trim() == ""){
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp)+" °C";
}
You need to parse the temp value as int. This will make sure that temp is either a number or NaN. Everything will work just fine.
Edit: This was suggested by #Servuc as well in the question comments.
<p>Enter Fahrenheit to convert it to Celsius.</p>
<form>
<input type="number" id="tempF">°F
</form>
<button onclick="temperatura()">Try it</button>
<p id="demo2"></p>
<br>
<script>
function temperatura() {
var temp = parseInt(document.getElementById("tempF").value);
if (isNaN(temp)) {
document.getElementById("demo2").innerHTML =
"You need to enter a number!";
} else {
document.getElementById("demo2").innerHTML = uCelzije(temp) + " °C";
}
}
function uCelzije(f) {
return (5 / 9) * (Number(f) - 32);
}
</script>
Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.
I have seen in a few "username" fields where you type in a username, and below it, in something like a span, it will append it to a url. A lot like what is happening as I type this in StackOverflow at the bottom.
I would like to show only allowed characters from a list, ignore any input of characters not in that list.
I am really new to JS. In this case, I am using Jquery, and have a sort of works with some parts, and other parts I do not, or I have not gotten there yet.
Desire:
Input form field accepts only characters from a list, others are ignored.
Get the new key as entered, and append it to an element.
Here is the mess I have so far:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keyup(function(e) {
var entered = $('#cart-name').val();
entered = entered.toUpperCase();
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
// fromCharCode always returns uppercase?
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
var pos = allowed.indexOf(entered_char);
console.log('position is: ' + pos);
if (pos <= 0) {
console.log('does not contain');
} else {
console.log('contains');
}
$('#live').text(entered);
console.log(entered);
});
});
</script>
In the html I have:
<input type="text" name="cart_name" value="" id="cart-name" autocomplete="off" />
<br />
http://example.com/
<span id="live"></span>
<br />
Why not use a regular exprsession to replace non alphanumeric characters?
entered = entered.replace(/[^a-zA-Z 0-9]+/g,'');
Looking at your comments, you have some confusion over the different Key events:
keyup (and keydown) tell you which physical key has been pressed, while keypress will tell you which character has been typed - which is why you're always getting uppercase letters from fromCharCode.
I'm using something like this to sort out urls:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#cart-name').keypress(function(e) {
var entered = $('#cart-name').val();
// Regular Express to perform match on all alphanumeric characters,
// and - and _
var matchPattern = /[\w/_/-]/g;
var entered_char = String.fromCharCode(e.which);
console.log('You entered: ' + entered_char);
if (entered_char.match(matchPattern)) {
$('#live').text(entered + entered_char);
}
else if (enteredKey == " ") {
// Replace spaces with hyphens for SEO
$('#live').text(entered + "-");
}
});
});
</script>
Should see you right.