Reputation: 1899
I have a function that formats telephone numbers as a user types their phone number in. I also have a blade.php template that has the phone number field as part of the form. How do I get the blade template to invoke my telephone() function from my main.js file?
Contact.blade.php
<div class="field">
<label for="name" class="label">Phone Number</label>
<div class="control">
<input type="text" id="phonenumber" class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
name="phonenumber" placeholder="Enter phone number" value="{{old('phonenumber')}}">
</div>
</div>
main.js
function telephone(){
document.getElementById('phonenumber').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
}
app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
<link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
@include('inc.contact')
</body>
Upvotes: 0
Views: 724
Reputation: 1817
A server side language (php) can not invoke an action in a client browser; there is a physical boundary that separates the two.
What you are looking for is a an event in the client browser that can trigger your function.
main.js
function telephone(e){
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
}
document.getElementById("phonenumber").input = telephone
You will also want to make sure your javascript executes after the content of the DOM is available.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="{{url('/css/style.css')}}" type="text/css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
@include('inc.contact')
<script type="text/javascript" src="{{URL::asset('js/main.js')}}"></script>
</body>
Upvotes: 1
Reputation: 41
You can use onKeyDown or onKeyUp on the phonenumber
input tag and point it to your telephone()
function
Upvotes: 1