Uncaught ReferenceError: changePhone is not defined - javascript

I have some text inputs on my site for phone numbers. I want to keep all numbers in one format not some like 123-456-7890 and others 1234567890. I've tried writing a code to change this but it is giving me an error of Uncaught ReferenceError: changePhone is not defined.
Here is my code:
<input type="text" id="phone" onblur="changePhone(this.id)">
function changePhone(id){
$(id).text(function(i, number) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
return number;
});
}
When running validation my code checks out as valid so I am not understanding why it doesn't work.
On a side note: Is there a PHP solution to achieve this or is jquery my best option?
EDIT: Here is a fiddle of my code: http://jsfiddle.net/4uk9hhtc/

There are so many things wrong with this.
$(id) does not work because you need a # before ID. You are doing $('whateverID') should be $('#whateverID')
The .text()does not work because you are running on an input element.
Your fiddle is missing jquery, and the code should in <head>
http://jsfiddle.net/4uk9hhtc/13
function changePhone(id){
var number = $("#"+id).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
alert( number )
}
OR you could just use jquery and get rid of inline onclick like in the other answers

Here is something that actually works
$(function() {
$('#phone').on('blur', function(){
var val = ""+this.value;
this.value = val.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="phone" />
Pure JS with inline invocation
function changePhone(field) {
var val = ""+field.value;
field.value = val.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
}
<input type="text" id="phone" onblur="changePhone(this)"/>

Pure jQuery solution. Your fiddle isn't including jQuery by the way. I'm making assumptions that you know how to include jQuery correctly. You should be using val().
http://jsfiddle.net/2kLywwpu/1/
<input type="text" class="phone" id="theText">
using
var textbox = $('#theText').on('blur', function(){
textbox.val(function(i, number) {
number = number.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
return number;
});
});
Here's a fiddle that's not using your regular expression so you can see that the basic functionality works.
http://jsfiddle.net/2kLywwpu/2/

Related

Format input with regex

I have a input field which is a percent value, i am trying for it to display as % when not focused in and when focused in it will loose the %, also the input field needs to avoid chars on it. I'm using a type"text" input field with some jQuery.
$(document).ready(function() {
$('input.percent').percentInput();
});
(function($) {
$.fn.percentInput = function() {
$(this).change(function(){
var c = this.selectionStart,
r = /[^0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
$(this).focusout(function(){
$(this).val(this.value + "%");
});
$(this).focusin(function(){
$(this).val(this.value.replace('%',''));
});
};
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2"></input>
<input class="percent" value="4"></input>
on the snippet it does not behave the same as on my app, not sure why but the intended result is for it to erase any char that is not a digit or "only" 1 % sign.
Would change this approach only slightly:
use keypress (and eventually paste) to block invalid characters
use parseFloat (or int if you don't allow decimals) to remove leading 0's --> '00009.6' => '9.6%'
However I'd use <input type="number"> (btw: </input> closing tag is invalid HTML)
these days with a % sign just after the input. (number type has better display on mobile)
(function($) {
$.fn.percentInput = function() {
$(this)
// remove formatting on focus
.focus(function(){
this.value = this.value.replace('%','');
})
// add formatting on blur, do parseFloat so values like '00009.6' => '9.6%'
.blur(function(){
var r = /[^\d.]/g,
v = this.value;
this.value = parseFloat(v.replace(r, '')) + '%';
})
// prevent invalid chars
.keypress(function(e) {
if (/[^\d.%]/g.test(String.fromCharCode(e.keyCode)))
e.preventDefault();
});
};
})(jQuery);
$(document).ready(function() {
$('input.percent').percentInput();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2%">
<input class="percent" value="4%">
It is my understanding that the snippet you provided is the desired behavior, but your app isn't behaving in the desired way you've demonstrated. So, the question is: what's different between this snippet and your app? Does your app throw any errors into the console?
When I encounter problems like this, I'll usually run my page through an HTML validator. Sometimes, invalid html can corrupt more than you'd think.
When I put your html into a standard HTML5 template, the validator finds these errors in your snippet:
Basically, it is saying that you don't need </input>. Do this instead:
<input class="percent" value="2">
<input class="percent" value="4">
Perhaps this is completely unrelated, but I thought I'd mention it. I'd put your actual app through the html validator to see if you find more errors that could be ultimately corrupting your javascript's ability to achieve the desired behavior showcased by your snippet.

Javascript can't read null

I'm using javascript integration to submit a form that will call the factorial function in my javascript. I use the scripts and style plugin to integrate the javascript code. But it ends with an error at var n in the script.
Cannot read property 'value' of null at HTMLInputElement.factorial
Below is the code.
In my post I put:
<form id="cal_factorial">
Enter No:<input type="number" id="num" name="number"/><br/>
<input type="button" value="factorial" id="factorialize"/>
</form>
<p id="answer"></p>
In the head I have the script as:
document.addEventListener("DOMContentLoaded", function(){
document.querySelector("#factorialize").onclick = factorial;
});
function factorial(){
var n=document.getElementById("#num").value;
var ans =1;
if(n>1){
var trail = n*(n-1)
ans = ans *trail;
n-=1;
}
document.querySelector("#answer").innerHTML = ans;
}
Anything wrong with the definition?
document.getElementById("#num").value;
is incorrect.
it should be
document.getElementById("num").value;
without the #
Remove the hashtag in getElementById,
var n=document.getElementById("num").value;
There might be something wrong with scope, the code look ok
have a look here
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onsubmit

Jquery: Combine multiple user inputs into one text area?

I'm trying to put together multiple user inputs and then combine them into one textarea after button click.
For example:
User1:Hey, I just met you
User2:And this is crazy
User3:But Here's my number so call me maybe
Combined Result:
Hey, I just met you, And this is crazy, But Here's my number so call me maybe
Here's my code the button click is currently not working but when I tried it before it did work so I was thinking I have some problem w/ my Jquery that triggers this unusual result:
HTML and Imports:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input class="combine" id="input1" disabled="true"></input>
<input class="combine" id="input2" disabled="true"></input>
<input class="combine" id="input3" disabled="true"></input>
<input class="combine" id="input4" disabled="true"></input>
<input class="combine" id="input5" disabled="true"></input>
<input class="combine" id="input6" disabled="true"></input>
<input class="combine" id="Voltes5" disabled="true" size="45"></input>
<button id="setVal">Set</button>
Jquery
$(document).ready(function(){
$('#setVal').on('click',function(){
jQuery(function(){
var form = $('.combine');
form.each(function(){
$('.Voltes5').append($(this).text()+ ' ');
});
});
});
});
Update for sir Arun P Johny
User1: If theres a (no comma when combined)
User2: will
User3: there's a way
Combined Result:
If theres a will, there's a way
Try
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.combine').not('#Voltes5');
var vals = form.map(function () {
var value = $.trim(this.value)
return value ? value : undefined;
}).get();
$('#Voltes5').val(vals.join(', '))
});
});
Demo: Fiddle
Here's a one-liner for non-readability ;)
$('#setVal').click(function(){$('#Voltes5').val($('.combine').not('#Voltes5').map(function(){return $(this).val();}).get().join(''))});
Expanded:
$('#setVal').click(function(){
$('#Voltes5').val(
$('.combine')
.not('#Voltes5')
.map(
function(){
return $(this).val();
})
.get()
.join('')
);
});
Get fiddly with it: http://jsfiddle.net/ArtBIT/u57Zp/
Here is one way to do this:
$('#setVal').on('click', function () {
$(".combine[id^=input]").each(function () {
if(this.value) {
$("#Voltes5")[0].value += ' ' + this.value;
}
});
});
There are several different ways to do this..
I'd do it this way using an array:
$(document).ready(function () {
$('#setVal').on('click', function () {
//create an array for the values
var inpAry = [];
$('.combine').each(function () {
//add each value to the array
inpAry.push($(this).val+' ');
});
//set the final input val
$('#Voltes5').val(inpAry);
});
});
but you would need to remove the combine class from #setVal because that would be included in the .each.
This way it would also be possible to have the final box updated on keyup as I'm not just appending the values, the combined values are set each time.
$(document).ready(function(){
$('#setVal').on('click',function(){
var val='';
$('.combine').not('#Voltes5').each(function(){
val+=$(this).val();
});
$('#Voltes5').val(val);
});
});
.text() will give text of the element ,for input val u have to use .val()
So there's immediate big problem in the code, which is that you're referring to your Voltes5 element as a class, not an ID. The jQuery selector you want is:
#Voltes5
instead of:
.Voltes5
There are a few other things to think about too, though, for the sake of functionality and best practices. Firstly, the Voltes5 element also has class combine, meaning that the $('.combine').each() call will include this element. The outcome of this is that it will also append its current text to itself when the code is run (or, when the code is run with the above correction).
When grabbing the current entered text of an input element, a jQuery .val() call is what you want, not .text() - see this answer for some more discussion.
Another thing that could be noted is that you should really explicitly specify what sort of input these elements are; <input type="text"> is hugely preferable to <input>.
Finally, input is a void element (reading), meaning it shouldn't have any content between opening and closing tags. Ideally, you wouldn't even give a closing tag; either have just the opening tag, or self-close it:
<input>
<input />
HTH
replace $('.Voltes5').append($(this).text()+ ' ');
with
$('#Voltes5').append($(this).text()+ ' ');

How to display message with the help of jquery?

i m trying to do a validation using jquery.
Enter Account no:
here is my html code
<input type="text" name="Assets" id="Assets" size="25" /><br />
<div id="eb"> Please Enter Valid Account no </div>
Enter Amount<input type="text" name="Liability" id="Liability" size="25" /><br />
and here is my jquery code
$(document).ready(function(){
$("#Assets").change(function(){
var Assets = $('input#Assets').val();
var expression=/[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets == "" || Assets == " ") {
$('#eb').show();
}
else if(Assets.test(expression)){
$('#eb').hide();
}
$('#eb').toggle();
}
i want to display a mesage when user write a account no then at a time he can see the message that Please Enter Valid Account no and if he insert correct then that message can be hide.
here is my jsfiddle - http://jsfiddle.net/BzdfN/5/
please help
Try this code:
$(document).ready(function () {
$("#Assets").change(function () {
var Assets = this.value;
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
if (Assets.match(expression)) {
$('#eb').hide();
} else {
$('#eb').show();
}
});
});
This is a suggestion for more simple code. Notice I used match() which takes a regex as paramenter, if you want to use test() you should use the value/string as paramenter and use like expression.test(Assets).
Fiddle
About your code/fiddle:
you missed adding jQuery library to the fiddle
you missed ) closing the change() function
you missed }) closing the ready() function
you used test() with wrong order, check my text above about match() and test()
your fiddle with corrections: Fiddle
jQuery was not included and multiple syntax errors
$(document).ready(function () {
var expression = /[0-9]{4}\s[0-9]{4}\s[0-9]{2}\s[0-9]{10}/;
$("#Assets").change(function () {
$('#eb').toggle(!expression.test(this.value));
})
})//missing brackets
Demo: Fiddle
Try this - http://jsfiddle.net/dangoodspeed/BzdfN/9/ I made a bunch of changes, including activating jQuery, closing some functions, and reversed Assets and expression for the .test call
else if(expression.test(Assets)){

Validate TextBox In JavaScript

i need a validate textbox which is accepted like this $250.00 here is '$' will accepted only one time and then never accepted '$' as well as '.'(dot).
You could use a masked input for example
your mask would be
$('#input').mask('$9?.99');
You can do:
var x = document.getElementById('your-text-box').value;
if(x.match(/^\$[0-9]+\.[0-9]+$/) == null) {
// invalid
}
else {
// valid
}
The regex /^\$[0-9]+\.[0-9]+$/ will match any string meeting the following constraints
Should start with a $
Should have 1 or more numbers after the $
Should have a . after the first set of numbers
Should end with 1 or more numbers after the .
Is jquery an option?
Here is a jquery solution. First of all I wouldn't validate expecting user to put '$'. I would put that outside the form and just allow people to enter the amount. That's weird, but I guess I don't really have the context on what you are doing. See Jquery validation:
$("#myform").validate({
rules: {
field: {
required: true,
digits: true
}
}
});
This is using digits to allow only numbers. Otherwise if you really need $ in there you need to create a custom validation rule.
<!-- wherever your jquery file is -->
<script src="../../jquery.min.js"></script>
<input type="text" id="cost"><input type="button" id="check" value="Check!">
<script>
// jquery solution
$(document).ready( function (){
$('#check').click( function (){
var cost = $('#cost').val();
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
});
});
</script>
Of course you can use pure java script as well to reduce the dependency
<input type="text" id="cost">
<input type="button" id="check" value="Check!" onClick="check();">
<script>
// Pure Javascript Solution
var check = function (){
var cost = document.getElementById('cost').value;
var patt=/^(\$)?\d+(\.\d+)?$/;
var result=patt.test(cost);
alert(result);
}
</script>

Categories