Flag appending on input tel js so validation not working properly - javascript

In this code i want to try make validation phone number field.
I am using Tel-Input-Js.
if i am using
initialCountry: "AE",
for showing default selection country. but it's not working properly as you can see in image AE country flag is just append on US flag so volition not working properly.
Here my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>International telephone input</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- <link rel="stylesheet" href="style.css" /> -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
</head>
<style>
.container {
max-width: 800px;
margin-left: auto;
margin-right: auto;
padding: 10px;
}
#phone,
.btn {
padding-top: 6px;
padding-bottom: 6px;
border: 1px solid #ccc;
border-radius: 4px;
}
.btn {
color: #ffffff;
background-color: #428BCA;
border-color: #357EBD;
font-size: 14px;
outline: none;
cursor: pointer;
padding-left: 12px;
padding-right: 12px;
}
.btn:focus,
.btn:hover {
background-color: #3276B1;
border-color: #285E8E;
}
.btn:active {
box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125);
}
.alert {
padding: 15px;
margin-top: 10px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert-info {
border-color: #bce8f1;
color: #31708f;
background-color: #d9edf7;
}
.alert-error {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
© 2022 GitHub,
Inc. Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About
</style>
<body>
<div class="container">
<form id="login" onsubmit="process(event)">
<p>Enter your phone number:</p>
<input id="phone" type="tel" name="phone" />
<input type="submit" class="btn" value="Verify" />
</form>
<div class="alert alert-info" style="display: none"></div>
<div class="alert alert-error" style="display: none"></div>
</div>
</body>
<script>
const phoneInputField = document.querySelector("#phone");
const phoneInput = window.intlTelInput(phoneInputField, {
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
});
const info = document.querySelector(".alert-info");
const error = document.querySelector(".alert-error");
function process(event) {
event.preventDefault();
const phoneNumber = phoneInput.getNumber();
info.style.display = "none";
error.style.display = "none";
if (phoneInput.isValidNumber()) {
info.style.display = "";
// info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
info.innerHTML = `Phone number in Valid`;
} else {
error.style.display = "";
error.innerHTML = `Invalid phone number.`;
}
}
var input = document.querySelector("#phone");
window.intlTelInput(input, {
excludeCountries: ["US","IN"],
preferredCountries: [ "AE" ],
initialCountry: "AE", //change according to your own country.
utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
});
</script>
</html>
I am using
excludeCountries: ["US","IN"],
for removing us country but also it's appending on us flag.
i want to show default country as a AE and without country change "00971551234567" this number should be need to validate.
and i also need custom placeholder for the AE country how can i do it.?
help me to solve out this problem. advance thanks for who's help me to solve out this problem.

Related

JavaScript Login Form Problem Related to Remember me Button

I have made this login form from my basic HTML CSS and JavaScript knowledge. There is a Remember me button in this login form I have created and now I have to give it a functionality.
I want to click OK button and then it should:
Create a cookie if Remember Me is set and save Student Id and Name.
I am using Visual Studio Code.
Here is my HTML + JavaScript Code:
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Login Form</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<div class = "f1">
<label for = "uname">
<b>Username</b>
</label>
<input type = "text"
placeholder = "Enter Username"
id = "user"
name = "uname" requitred>
<span id = "username" class = "text-danger font-weight-bold"></span>
<label for = "psw">
<b>Password</b>
</label>
<input type = "text"
placeholder = "Enter Password"
id = "pass"
name = "psw" requitred>
<button type="button" onclick="alert('Login is clicked')">OK</button>
<button type="button" onclick="alert('Cancel is clicked')">Cancel</button>
<input type="checkbox" value="lsRememberMe" id="rememberMe">
<label for="rememberMe">Remember me</label>
<input type="submit" value="Login" onclick="lsRememberMe()">
<script>
if (onclick == "alert('Login is clicked')"){
window.location.assign("Home.html");
}
</script>
</form>
</body>
</html>
CSS Code:-
form{
border: 3px solid black;
}
input[type=text],
input[type=password]{
width:27%;
padding:12px 20px;
margin:8px 0;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
button{
background-color: #04aa6d;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 27%;
}
input[type="checkbox"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
display: inline-block;
width: auto;
}
body {
background-image: url('cool.jpg');
color: #FFFFFF;
}
input[type = Clear]{
font-size : 18px;
padding : 5px;
width : 20%;
border-radius: 0 10px;
border : none;
}
I have tried a lot of different techniques but it not work for me. (Code must be in JavaScript and HTML).
Thanks.
It would be better to save under the localStorage instead of a cookie because cookie is being sent to server every request. But both are ok if you are just saving the name (although that's something most browsers do anyway).
So basically you want to setItem when remeberMe is checked. you want to removeItem otherwise. When onload, restore the value using getItem
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var rememberMe = document.getElementById("rememberMe");
window.addEventListener("load", function() {
console.log('run this: user.value = localStorage.removeItem("login-user-name") || "";');
})
function do_submit() {
if (rememberMe.checked) {
console.log('run this: localStorage.setItem("login-user-name", user.value);');
} else {
console.log('run this: localStorage.removeItem("login-user-name");');
}
alert("will cancel because return false explicitly")
return false;
}
form {
border: 3px solid black;
}
input[type=text],
input[type=password] {
width: 27%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
button {
background-color: #04aa6d;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 27%;
}
input[type="checkbox"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
display: inline-block;
width: auto;
}
body {
background-image: url('cool.jpg');
color: #FFFFFF;
}
input[type=Clear] {
font-size: 18px;
padding: 5px;
width: 20%;
border-radius: 0 10px;
border: none;
}
<form class="f1" action="home.html" onsubmit="return do_submit()">
<label for="user">
<b>Username</b>
</label>
<input type="text" placeholder="Enter Username" id="user" name="uname" required>
<span id="username" class="text-danger font-weight-bold"></span>
<label for="pass">
<b>Password</b>
</label>
<input type="text" placeholder="Enter Password" id="pass" name="psw" required>
<!--
<button type="button" onclick="alert('Login is clicked')">OK</button>
<button type="button" onclick="alert('Cancel is clicked')">Cancel</button>
-->
<input type="checkbox" value="lsRememberMe" id="rememberMe">
<label for="rememberMe">Remember me</label>
<input type="submit" value="Login">
</form>
Is student ID a part of the response that you get from the server?
To create cookies, save the student name value in a variable:
const username = document.getElementById("user").value;
and save it as cookie if the Remember me checkbox is checked:
const rememberMe = document.querySelector("rememberMe");
if (rememberMe.checked) {
document.cookie = "username=" + username;
}
Next time on page loads, app reads the cookie value from browser and you can show previous username.
You may use js-cookie for easier cookie manipulation.
More info about JavaScript cookie.

Is there a error in my scripts or is my editor just bugged

So i'm making my game engine's login and i'm running into a lot of errors with my MongoDB Scripts and my If Statement's seem to not work can someone help me with it? This is the javascript that wont run for some reason and yet I dont see anything wrong with the code apparently my editor does and im wondering if it can be helped.
var punct = "'"
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
function adduser(){
if(user.length > 5){
if(pass.length > 5){
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = "mongodb+srv://"+punct+document.getElementById("username").value+punct+":"+punct+document.getElementById("password").value+punct+"#cluster0.sc5bo.mongodb.net/AccountData?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
window.location.href = "https://rag3d-download.glitch.me/app-home"
}
}
if(user.length < 5){
if(pass.length < 5){
alert("Username AND Password Needs To Be 5+ Characters")
}
}
}
center{
text-align: center;
padding-top: 90px;
}
html{
color: white;
background:black;
font-family: 'Fredoka One', cursive;
background-image: url('https://cdn.glitch.global/63a42bac-4e7e-4d64-bb57-1057823f5775/download%20(9).png?v=1647105325819');
}
pre{
font-family: 'Fredoka One', cursive;
color: white;
}
b{
font-family: 'Fredoka One', cursive;
}
button{
font-family: 'Fredoka One', cursive;
font-size: 40px;
height: 55px;
width: 400px;
border: 5px solid black;
border-radius: 10px;
color: black;
background:white;
transition: 0.5s all;
}
button:hover{
background: grey;
border: 5px solid black;
border-radius: 25px;
font-size: 40px;
}
#signup{
top:25px;
left:425px;
position: absolute;
background: black;
width: 500px;
height: 600px;
border: 5px solid black;
border-radius: 25px;
}
input{
font-family: 'Fredoka One', cursive;
border: 5px solid grey;
border-radius: 10px;
height: 50px;
width: 300px;
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet">
<html lang="en">
<head>
<title>Login To Rag3D</title>
<link rel="manifest" href="manifest.json" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<center>
<div id="signup">
<center>
<pre>Email:</pre>
<br /><input id="email" type="email" placeholder="Email"/><br /><br />
<pre>Username:</pre>
<br /><input id="username" type="text" placeholder="Username"/><br /><br />
<pre>Password:</pre>
<br /><input id="password" type="password" placeholder="Password" /><br/><br/>
<button >Create Account</button>
</center>
</div>
</center>
Can someone help me identify the errors in the code? I really need it a will most likely give the helper credit. I just want my stuff to run smoothly because my IDE was already supposed to have been released but I only got the scripting part done and nothing else since I am just only finding MongoDB. I used the connection code for the login scripts and I dont know what's happening. I feel like it might be my editor bugging out which is why I came here.

Python http.server not responding back to the client

I am creating a chatting project using python module http.server as server and on the client side i am using jquery ajax to send and recieve messages... But matter is that the client is able to send messages to the server and server is recieving messages(checked with print statement) but when its time to return back the messages again to all clients, i think the server is not responding the messages to clients. I am not getting what's problem with the code. It would be great help if you find the bug...
from http.server import BaseHTTPRequestHandler,HTTPServer,ThreadingHTTPServer
import json
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Access-Control-Allow-Origin","*")
self.send_header('Content-type','text/html')
self.end_headers()
#just trying
message = {"room4":1,"room5":1,"room6":1}
self.wfile.write(json.dumps(message).encode())
def do_POST(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
if content_length:
data=json.loads(body.decode())
keys=list(data.keys())
if keys[0]=="message":
self.send_response(200)
self.send_header("Access-Control-Allow-Origin","*")
self.send_header('Content-type','text/html')
self.send_header('Cache-Control', 'no-store')
self.end_headers()
message = {"welcome_msg":"success"}
print("Data:",data)
self.wfile.write(json.dumps(message).encode())
else:
self.send_response(200)
self.send_header("Access-Control-Allow-Origin","*")
self.send_header('Content-type','text/html')
self.send_header('Cache-Control', 'no-store')
self.end_headers()
serv=HTTPServer(("localhost",9889),handler)
serv.serve_forever()
javascript code:
$(document).ready(function(){
load();
var entereddata;
$("#submitbtn").click(function(){
var d=new Date()
var t=d.getTime()
var time = d.toLocaleTimeString();
entereddata=$("#msgarea").val()
$("#chat").append("<div id='msg' style='background-color:#dcf8c6;padding:5px 10px; border-radius:5px;margin-bottom:8px;width:fit-content' class='container_new' style='margin-left:200px;'>"+"You: "+entereddata+"<p class='time-right'> "+time+"</p>"+"</div>")
//var element = document.getElementById("msgarea");
//window.scrollTo(0,document.body.scrollHeight-element.clientHeight);
$.post("http://localhost:9889/",JSON.stringify({
"message":entereddata,
"port":location.port,
})
)
})
function load(){
//console.log("hhh")
$.post("http://localhost:9889/",JSON.stringify({
"port":location.port,
}),function(data,status){
console.log("ds")
console.log(data)
}
)
}
setInterval(load,1000)
})
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="test.js"></script>
<style>
body {
margin: 0;
overflow:hidden;
}
#chat{
height:88vh;
overflow:hidden;
padding: 10px;;
}
.container_new {
border: 2px solid #dedede;
background-color: #f1f1f1;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
}
.darker {
border-color: #ccc;
background-color: #ddd;
}
.container::after {
content: "";
clear: both;
display: table;
}
.container img {
float: left;
max-width: 60px;
width: 100%;
margin-right: 20px;
border-radius: 50%;
}
.container img.right {
float: right;
margin-left: 20px;
margin-right:0;
}
.time-right {
float: right;
color: #aaa;
}
.time-left {
float: left;
color: #999;
}
#form{
display: flex;
}
input{
font-size:1.2rem;
padding:10px;
margin:10px 5px;
appearance:none;
border: 1px solid #ccc;
border-radius: 5px;
}
#msgarea{
flex:2
}
#msg{
background-color: #dcf8c6;
padding:5px 10px;
border-radius: 5px;
margin-bottom: 8px;
}
</style>
<link rel="stylesheet" href="bootstrap.min.css">
</head>
<body id="bod">
<h2 id="head2"></h2>
<div class="container-fluid " id="chat">
</div>
<div id="form">
<input autofocus placeholder="Enter Message..." name="" id="msgarea" ></input>
<input type="button" id="submitbtn" value="Send">
</div>
</body>
</html>
Thanks

Html-css responsive sliding Feedback Form

Slinding Feedback Form isn't responsive at the moment. I've tested it on the phone and the text goes over the screen.
I've changed the CSS #mrova-feedback to: max-with:90%; still not working.
I have tried nearly everything and my issue is that I can not make it responsive.
What am I doing wrong?
Any thoughts?
(function($) {
$.fn.vAlign = function() {
return this.each(function(i) {
var h = $(this).height();
var oh = $(this).outerHeight();
var mt = (h + (oh - h)) / 2;
$(this).css("margin-top", "-" + mt + "px");
$(this).css("top", "50%");
});
};
$.fn.toggleClick = function() {
var functions = arguments;
return this.click(function() {
var iteration = $(this).data('iteration') || 0;
functions[iteration].apply(this, arguments);
iteration = (iteration + 1) % functions.length;
$(this).data('iteration', iteration);
});
};
})(jQuery);
$(window).load(function() {
//cache
$img_control = $("#mrova-img-control");
$mrova_feedback = $('#mrova-feedback');
$mrova_contactform = $('#mrova-contactform');
//setback to block state and vertical align to center
$mrova_feedback.vAlign()
.css({
'display': 'block',
'height': $mrova_feedback.outerHeight()
});
//Aligning feedback button to center with the parent div
$img_control.vAlign()
//animate the form
.toggleClick(function() {
$mrova_feedback.animate({
'right': '-2px'
}, 1000);
}, function() {
$mrova_feedback.animate({
'right': '-' + $mrova_feedback.outerWidth()
}, 1000);
});
//Form handling
$('#mrova-sendbutton').click(function() {
var url = 'send.php';
var error = 0;
$('.required', $mrova_contactform).each(function(i) {
if ($(this).val() === '') {
error++;
}
});
// each
if (error > 0) {
alert('Please fill in all the mandatory fields. Mandatory fields are marked with an asterisk *.');
} else {
$str = $mrova_contactform.serialize();
//submit the form
$.ajax({
type: "GET",
url: url,
data: $str,
success: function(data) {
if (data == 'success') {
// show thank you
$('#mrova-contact-thankyou').show();
$mrova_contactform.hide();
} else {
alert('Unable to send your message. Please try again.');
}
}
});
//$.ajax
}
return false;
});
});
label {
display: block;
padding-bottom: 5px;
margin-top: 20px;
}
#mrova-feedback {
display: hidden;
width: 420px;
position: fixed;
right: -462px;
border: 1px solid #3cb58c;
padding: 8px 20px;
background-color: #fff;
}
#mrova-contactform ul {
margin: 0;
padding: 0;
}
#mrova-contactform input,
#mrova-contactform textarea {
width: 400px;
padding: 10px;
border: 1px solid #ccc;
}
#mrova-contactform ul li {
list-style: none;
padding-bottom: 20px;
}
#mrova-img-control {
cursor: pointer;
position: absolute;
left: -52px;
width: 52px;
background: transparent url('feedback_buttons/feedback.jpg');
height: 168px;
}
#mrova-contactform #mrova-sendbutton {
width: 60px;
background: #db4f4a;
color: #fff;
cursor: pointer;
padding: 5px 10px;
border: none;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>
Feedback Form Demo
</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<!-- Files For mRova Feedback Form [Dependency: jQuery] -->
<script src="mrova-feedback-form.js" type="text/javascript"></script>
<link rel="stylesheet" href="mrova-feedback-form.css" type="text/css" />
<!-- END -->
<!-- Just For Demo -->
<style type="text/css">
html,
body {
padding: 0;
margin: 0;
height: 100%;
}
body {
background-color: #f2f2f2;
font-family: helvetica, arial, tahoma, verdana, sans-serif;
}
h1 {
text-align: center;
margin-top: 40px;
color: #333;
}
</style>
<!-- END -->
</head>
<body>
<h1>Free Feedback Form</h1>
<!--Feedback Form HTML START -->
<div id="mrova-feedback">
<div id="mrova-contact-thankyou" style="display: none;">
Thank you. We'hv received your feedback.
</div>
<div id="mrova-form">
<form id="mrova-contactform" action="#" method="post">
<ul>
<li>
<label for="mrova-name">Your Name*</label> <input type="text" name="mrova-name" class="required" id="mrova-name" value="">
</li>
<li>
<label for="mrova-email">Email*</label> <input type="text" name="mrova-email" class="required" id="mrova-email" value="">
</li>
<li>
<label for="mrova-message">Message*</label>
<textarea class="required" id="mrova-message" name="mrova-message" rows="8" cols="30"></textarea>
</li>
</ul>
<input type="submit" value="Send" id="mrova-sendbutton" name="mrova-sendbutton">
</form>
</div>
<div id="mrova-img-control"></div>
</div>
<!-- Feedback Form HTML END -->
</body>
</html>
Many things are wrong.
I've tweaked your code and improved it.
The edit was made only on your HTML and CSS.
* {
box-sizing: border-box;
}
body{
background-color: #f2f2f2;
font-family: helvetica,arial,tahoma,verdana,sans-serif;
}
h1{
text-align: center;
margin-top: 40px;
color: #333;
}
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
label {
padding: 12px 12px 12px 0;
display: inline-block;
}
input[type=submit] {
background-color: #db4f4a;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
float: right;
}
input[type=submit]:hover {
background-color: #45a049;
}
.container {
border-radius: 5px;
/*background-color: #f2f2f2;*/
padding: 20px;
display: hidden;
/*width: 420px;*/
/*position: fixed;*/
/*right: -462px;*/
border: 1px solid #3cb58c;
/*padding: 8px 20px;*/
background-color: #fff;
}
.col-25 {
float: left;
width: 25%;
margin-top: 6px;
}
.col-75 {
float: left;
width: 75%;
margin-top: 6px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Responsive layout - when the screen is less than 600px wide, make the two columns stack on top of each other instead of next to each other */
#media screen and (max-width: 600px) {
.col-25, .col-75, input[type=submit] {
width: 100%;
margin-top: 0;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<h1>ReFree Feedback Form</h1>
<div class="container">
<form action="/action_page.php">
<div class="row">
<div class="col-25">
<label for="fname">First Name*</label>
</div>
<div class="col-75">
<input type="text" id="fname" name="firstname" placeholder="Your name..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="lname">Last Name*</label>
</div>
<div class="col-75">
<input type="text" id="lname" name="lastname" placeholder="Your last name..">
</div>
</div>
<div class="row">
<div class="col-25">
<label for="message">Message*</label>
</div>
<div class="col-75">
<textarea id="message" name="message" placeholder="Write youre message.." style="height:200px"></textarea>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</div>
</body>
</html>
Well forget my HTML & CSS code
the problem in this script:
$img_control.vAlign()
//animate the form
.toggleClick(function() {
$mrova_feedback.animate({
'right': '-2px'
}, 1000);
}, function() {
$mrova_feedback.animate({
'right': '-' + $mrova_feedback.outerWidth()
}, 1000);
});
The script after modification:
You must change the value of 'right': '-2px'.
I think -120 is very appropriate, try it and tell me the result.
$img_control.vAlign()
//animate the form
.toggleClick(function() {
$mrova_feedback.animate({
'right': '-120px'
}, 1000);
}, function() {
$mrova_feedback.animate({
'right': '-' + $mrova_feedback.outerWidth()
}, 1000);
});
Do not forget this tag to make the page responsive :
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This tag should be in <head>

Stripe payment example is not displaying

I am trying to create a really simple example of using Stripe payments.
This is my code:
// Create a Stripe client
var stripe = Stripe('pk_test_XSHE4IYLLy9qCPe7lW7pK4ZE');
// Create an instance of Elements
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
lineHeight: '24px',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(result.token);
}
});
});
.StripeElement {
background-color: white;
padding: 8px 12px;
border-radius: 4px;
border: 1px solid transparent;
box-shadow: 0 1px 3px 0 #e6ebf1;
-webkit-transition: box-shadow 150ms ease;
transition: box-shadow 150ms ease;
}
.StripeElement--focus {
box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
border-color: #fa755a;
}
.StripeElement--webkit-autofill {
background-color: #fefde5 !important;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://js.stripe.com/v3/"></script>
<title>test</title>
</head>
<body>
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors -->
<div id="card-errors"></div>
</div>
<button>Submit Payment</button>
</form>
</body>
</html>
I followed the example from Stripe.
This is the error that I got from the Javascript console:
Uncaught Error: The selector you specified (#card-element) applies to no DOM elements that are currently on the page.
Make sure the element exists on the page before calling mount().
at new t (js.stripe.com/:1)
at t.value (js.stripe.com/:1)
Based on the error, I think the Stripe JavaScript could not find any #card-element, but it is there.
This could be a dumb question, but this is my first time using Stripe, so it would be great if someone could help me. Thank you so much.
Don't add the script in the head, instead, add it right before you close the body.
<html lang= "en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
</head>
<body>
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors -->
<div id="card-errors"></div>
</div>
<button>Submit Payment</button>
</form>
<script src="https://js.stripe.com/v3/"></script>
</body>
</html>
Putting your script at the bottom ensures that the DOM is rendered prior to executing the script, so that'll do the trick!
Put your script after the html from,
<form></form>
//after your stripe form put stripe script
<script></script>
As below
<style type="text/css">
* {
font-family: "Helvetica Neue", Helvetica;
font-size: 15px;
font-variant: normal;
padding: 0;
margin: 0;
}
html {
height: 100%;
}
body {
background: #E6EBF1;
align-items: center;
min-height: 100%;
display: flex;
width: 100%;
}
form {
width: 480px;
margin: 20px auto;
}
.group {
background: white;
box-shadow: 0 7px 14px 0 rgba(49,49,93,0.10),
0 3px 6px 0 rgba(0,0,0,0.08);
border-radius: 4px;
margin-bottom: 20px;
}
label {
position: relative;
color: #8898AA;
font-weight: 300;
height: 40px;
line-height: 40px;
margin-left: 20px;
display: block;
}
.group label:not(:last-child) {
border-bottom: 1px solid #F0F5FA;
}
label > span {
width: 20%;
text-align: right;
float: left;
}
.field {
background: transparent;
font-weight: 300;
border: 0;
color: #31325F;
outline: none;
padding-right: 10px;
padding-left: 10px;
cursor: text;
width: 70%;
height: 40px;
float: right;
}
.field::-webkit-input-placeholder { color: #CFD7E0; }
.field::-moz-placeholder { color: #CFD7E0; }
.field:-ms-input-placeholder { color: #CFD7E0; }
button {
float: left;
display: block;
background: #666EE8;
color: white;
box-shadow: 0 7px 14px 0 rgba(49,49,93,0.10),
0 3px 6px 0 rgba(0,0,0,0.08);
border-radius: 4px;
border: 0;
margin-top: 20px;
font-size: 15px;
font-weight: 400;
width: 100%;
height: 40px;
line-height: 38px;
outline: none;
}
button:focus {
background: #555ABF;
}
button:active {
background: #43458B;
}
.outcome {
float: left;
width: 100%;
padding-top: 8px;
min-height: 24px;
text-align: center;
}
.success, .error {
display: none;
font-size: 13px;
}
.success.visible, .error.visible {
display: inline;
}
.error {
color: #E4584C;
}
.success {
color: #666EE8;
}
.success .token {
font-weight: 500;
font-size: 13px;
}
</style>
<form action="subscription.php" method="post">
<div class="group">
<label>
<span>Name</span>
<input name="cardholder-name" class="field" placeholder="Jane Doe" />
</label>
<label>
<span>Phone</span>
<input class="field" placeholder="(123) 456-7890" type="tel" />
</label>
</div>
<div class="group">
<label>
<span>Card</span>
<div id="card-element" class="field"></div>
</label>
</div>
<button type="submit">Pay $25</button>
<div class="outcome">
<div class="error" role="alert"></div>
<div class="success">
Success! Your Stripe token is <span class="token"></span>
</div>
</div>
</form>
<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
var stripe = Stripe('YOUR_PUBLIC_KEY');
var elements = stripe.elements();
var card = elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
function setOutcome(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
// Use the token to create a charge or a customer
// https://stripe.com/docs/charges
successElement.querySelector('.token').textContent = result.token.id;
successElement.classList.add('visible');
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
card.on('change', function(event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
var form = document.querySelector('form');
var extraDetails = {
name: form.querySelector('input[name=cardholder-name]').value,
};
stripe.createToken(card, extraDetails).then(setOutcome);
});
</script>
For anyone else with this same problem - the code snippet in Stripe's docs is incomplete. So the suggested fixes above may in fact be necessary to ensure proper order of operations, but the whole thing won't work unless you define a stripeTokenHandler method.
Stripe's docs define the method (further down the page) as:
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
Stripe.js renders the inputs for credit card number, expiration, CVC in iFrames. You cannot create these or get at them with JavaScript. You can however style the containers as you want which will enable you to get pretty close matching to the UI of your website - Bootstrap, MDC-Web, or whatever.
If your elements are not displaying, try the below to get started.
<div class="stripe-custom-element">
<label for="stripe-card">Card Number</label>
<div class="" id="stripe-card"></div>
</div>
<div class="stripe-custom-element">
<label for="stripe-exp">Expiration</label>
<div class="" id="stripe-exp"></div>
</div>
<div class="stripe-custom-element">
<label for="stripe-cvc">CVC</label>
<div class="" id="stripe-cvc"></div>
</div>
var cardNumberElement = doc.getElementById("stripe-card");
var cardExpiryElement = doc.getElementById("stripe-exp");
var cardCvcElement = doc.getElementById("stripe-cvc");
var cardNumber = elements.create('cardNumber', {});
var cardExpiry = elements.create('cardExpiry', {});
var cardCvc = elements.create('cardCvc', {});
cardNumber.mount(cardNumberElement);
cardExpiry.mount(cardExpiryElement);
cardCvc.mount(cardCvcElement);
registerElements([cardNumber, cardExpiry, cardCvc]);
I may be be late, but this worked for me , make sure to add the charge.js script below the stripe script , also, add them before the closing body tag
<html lang= "en">
<head>
<link rel="stylesheet" href="style.css"/>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
</head>
<body>
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- a Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors -->
<div id="card-errors"></div>
</div>
<button>Submit Payment</button>
</form>
<script type ="text/javascript" src="https://js.stripe.com/v3/"></script>
<script src="charge.js"></script>
</body>
</html>

Categories

Resources