i have a span tag in javascript file like that
<input type="text" id="name" onblur="submitFormEmail()"/>
<span class="error">This is an error</span>
and here is its style in the css
.form_wrapper span.error{
visibility:hidden;
color:red;
font-size:11px;
font-style:italic;
display:block;
margin:4px 30px;
}
how can i change the visibility of the span when calling the function submitFormEmail()??
function submitFormEmail(){
}
Just
document.getElementsByClassName(".error")[0].style.visibility="visible";
To call it in your function you can do the following:
function submitFormEmail(){
document.querySelector('.error').style.visibility = 'visible';
}
Assuming there has many input elements, so the function should find out which node be match.
function submitFormEmail(obj) {
var nextSpan = obj.nextSibling;
while(nextSpan.nodeType != 1){
nextSpan = nextSpan.nextSibling;
}
nextSpan.style.visibility = 'visible';
}
.error {
visibility: hidden;
color: red;
font-size: 11px;
font-style: italic;
display: block;
margin: 4px 30px;
}
<input type="text" id="name" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name1" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span> <br/>
<input type="text" id="name2" onblur="submitFormEmail(this)" /> <span class="error">This is an error</span>
Related
I am trying to get the text in a multiple text box as the user types in it (jsfiddle playground):
function Input1(a) {
document.getElementById("Input11").innerHTML = a.value;
document.getElementById("Input12").innerHTML = a.value;
document.getElementById("Input13").innerHTML = a.value;
}
function Input2(b) {
document.getElementById("Input21").innerHTML = b.value;
document.getElementById("Input22").innerHTML = b.value;
document.getElementById("Input23").innerHTML = b.value;
}
And Result as
<span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span id="Input11">Input11</span><br>
<span id="Input12">Input12</span><br>
<span id="Input13">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span id="Input21">Input21</span><br>
<span id="Input22">Input22</span><br>
<span id="Input23">Input23</span><br><br>
The above code is working fine.
But I want to Display each "onkeyup" input multiple times on-page. So here I need to update the function and span id (As if I use the same id then it will not display anything after 2nd call)
Please help me to reformat the above JavaScript and HTML so Just Define function for input and display it on all HTML span id without changing span id each time...
you can use class instead of id and use querySelectorAll to select all elements here is sample code
function Input1(a) {
const elements = document.querySelectorAll(".Input1");
elements.forEach((e)=>{
e.innerHTML = a.value;
})
}
function Input2(b) {
const elements = document.querySelectorAll(".Input2");
elements.forEach((e)=>{
e.innerHTML = b.value;
})
}
<html>
<body><span id="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input1(this);">
</span><br><br>
<span class="Input1">Input11</span><br>
<span class="Input1">Input12</span><br>
<span class="Input1">Input13</span><br><br>
<span id="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input2(this);">
</span><br><br>
<span class="Input2">Input21</span><br>
<span class="Input2">Input22</span><br>
<span class="Input2">Input23</span><br><br>
</body>
</html>
you can do somthing like that:
document.querySelectorAll('div.text-box').forEach( (box,i) =>
{
let
intxt = box.querySelector('input')
, spTxts = box.querySelectorAll('span')
;
intxt.mane = `Jname${++i}`
intxt.placeholder = `Input${i}`
intxt.onkeyup = () => spTxts.forEach(sp=>sp.textContent = intxt.value)
})
.text-box {
margin : 20px 0 15px 0;
}
.text-box input {
width : 100%;
font-size : 13px;
padding : 5px;
margin-top : -5px;
margin-bottom : 1em;
box-shadow : 1px 5px 7px #75757578;
}
.text-box span {
display : block;
}
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
<div class="text-box">
<input type="text">
<span>...</span>
<span>...</span>
<span>...</span>
</div>
this is the best for you!
function Input(a, n) {
var spans = document.querySelectorAll('#tb' + n + ' span')
spans.forEach(function(span){
span.innerHTML = a.value;
})
}
.textbox-value {
width: 100%;
font-size: 13px;
padding: 5px;
margin-top: -5px;
box-shadow: 1px 5px 7px #75757578;
}
<html>
<body>
<div id="tb1" class="text-box">
<input class="textbox-value" type="text" name="Jname" placeholder="Input1" onkeyup="Input(this, '1');" />
<br><br>
<span>Input11</span><br>
<span>Input12</span><br>
<span>Input13</span><br>
</div>
<br>
<div id="tb2" class="text-box">
<input class="textbox-value" type="text" name="Jbname" placeholder="Input2" onkeyup="Input(this, '2');">
<br><br>
<span>Input21</span><br>
<span>Input22</span><br>
<span>Input23</span><br>
</div>
<br>
</body>
</html>
In this Favourite place Dynamic Web Application achieving the design with HTML, CSS, and functionality with JS. I had not getting to do the functionality with JS, I'm facing problem as
When the Submit button is clicked
Text content in the HTML paragraph element should contain the value
of the checked HTML radio input element.
Below is the image of expected output:-
Favourite Place output image:
Note :-
The HTML radio input element with value Agra, should have checked atrribute by default.
You can use HTML form element.
Here is the code I tried
let questionsFormElement = document.getElementById("questionsForm");
let inputElement = document.getElementById("favouritePlace");
let input1Element = document.getElementById("favouritePlace1");
let input2Element = document.getElementById("favouritePlace2");
let label1Element = document.getElementById("label1");
let label2Element = document.getElementById("label2");
let label3Element = document.getElementById("label3");
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(){
inputElement.textContent = "Your favourite place is:" + label1Element.textContent;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="Lucknow" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="Agra" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="Varanasi" />
<label for="favouritePlace1" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
For the radio buttons, you have to give the same name for all the input tags which you want to group in one tag. And you have used form so when you press submit button it will send a request and the page will reload. solution for that is to use e.preventDefault().
And also you need to add final text into the p tag :
textParagraphElement.textContent
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(e){
e.preventDefault()
textParagraphElement.textContent = "Your favourite place is:" + document.querySelector('input[name="location"]:checked').value;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="location" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="location" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="location" />
<label for="favouritePlace2" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
You are missing several things:
Prevent default on your submit function so the page does not refresh after clicking the submit button.
For radios to work as a group you need to give them the same name (see "myRadio" on my snippet)
You are missing a way to know which radio was checked, see my callback function where I get radio and iterate over the values to see which one was checked, this can be done in many different ways, this is just one approach.
EDIT: Jay Patel suggested a better approach to get the value directly.
let questionsFormElement = document.getElementById("questionsForm");
let inputElement = document.getElementById("favouritePlace");
let input1Element = document.getElementById("favouritePlace1");
let input2Element = document.getElementById("favouritePlace2");
let label1Element = document.getElementById("label1");
let label2Element = document.getElementById("label2");
let label3Element = document.getElementById("label3");
let submitBtnElement = document.getElementById("submitBtn");
let textParagraphElement = document.getElementById("textParagraph");
submitBtnElement.addEventListener("click", function(e) {
e.preventDefault();
const radio = document.querySelector('input[name="myRadio"]:checked').value
textParagraphElement.innerHTML = 'Your favorite place is: ' + radio;
});
#import url("https://fonts.googleapis.com/css2?family=Bree+Serif&family=Caveat:wght#400;700&family=Lobster&family=Monoton&family=Open+Sans:ital,wght#0,400;0,700;1,400;1,700&family=Playfair+Display+SC:ital,wght#0,400;0,700;1,700&family=Playfair+Display:ital,wght#0,400;0,700;1,700&family=Roboto:ital,wght#0,400;0,700;1,400;1,700&family=Source+Sans+Pro:ital,wght#0,400;0,700;1,700&family=Work+Sans:ital,wght#0,400;0,700;1,700&display=swap");
.heading {
font-family: "Roboto";
font-size: 30px;
}
.label-element {
font-family: "Roboto";
font-size: 14px;
}
.button {
height: 30px;
width: 65px;
font-size: 15px;
margin-top: 10px;
margin-left: 10px;
color: white;
background-color: #327fa8;
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1 class="heading">Select Your Favourite Place</h1>
<form id="questionsForm" class="p-4 questions-form">
<input type="radio" id="favouritePlace" value="Lucknow" name="myRadio" />
<label for="favouritePlace" id="label1" class="label-element">Lucknow</label>
<br/>
<input type="radio" id="favouritePlace1" value="Agra" name="myRadio" checked />
<label for="favouritePlace1" id="label2" class="label-element">Agra</label>
<br/>
<input type="radio" id="favouritePlace2" value="Varanasi" name="myRadio" />
<label for="favouritePlace2" id="label3" class="label-element">Varanasi</label>
<br/>
<button class="button" id="submitBtn">Submit</button>
<p id="textParagraph"></p>
</form>
</body>
</html>
I am having one link as 'Add more' which adds input element as many as I want. I want to call blur function on that.
Following html gets added while click on 'Add more' link:
<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
Blur event works only for first element which is there in DOM by default. When I add new element, blur event doesn't get bind to the element.
Following is the javascript code.
$(document).ready(function() {
$(".timetoadd").blur(function(){
this.value = parseFloat(this.value).toFixed(2);
});
)};
It is in separate file called as backend.js. I am using webpack to minify the file and it is included in html file.
How to do that? Please help me out.
Use jQuery's on() method on a parent element with an additional selector as the second argument:
$(document).ready(function() {
$("#btnAdd").click(function() {
$('<br/><input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">').appendTo(document.body);
});
$(document.body).on('blur', '.timetoadd', function(){
this.value = parseFloat(this.value).toFixed(2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnAdd">Add more</button>
<br/><input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
Instead of document.body, you could also use any other parent that contains the inputs.
By adding the html attribute onblur and some javascript...
function myFunc(input) {
input.value = 0;
}
<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="" onblur="myFunc(this)">
Here's an example I've made for you. Do this for your input. It should work fine
function GetValue(e){
alert(e.target.value);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="inputgroup">
<input type="text" name="Dynamic_0" onblur="GetValue(event)">
<input type="text" name="Dynamic_1" onblur="GetValue(event)">
<input type="text" name="Dynamic_2" onblur="GetValue(event)">
</div>
// find elements
var id = $("#id > div")
var id1 = $("#id1")
var input = $("input")
var inputCopy;
var button = $("button")
// handle click and add class
button.on("click", function() {
$('<input required="" class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value=""><br>').appendTo(id);
/* addMore(e.currentTarget, e.currentTarget.value);
console.log('new input', e.currentTarget); */
})
$(document.body).on("blur", '.timetoadd', function() {
this.value = parseFloat(this.value).toFixed(2);
inputCopy = input;
})
function addMore(e, value) {
inputCopy = e.clone()
id.prepend($(inputCopy));
}
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#id {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#id.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#id.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="id">
<button>Add more</button>
<div>
<input required class="form-control js-validate-hoursToAdd timetoadd" step="0.01" name="calculations[settingIndex][hoursToAdd][calculationIndex]" type="number" value="">
</div>
</div>
JSFiddle: https://jsfiddle.net/kutec/c4pvLoua/
I have a form here that I'm trying to get an error message when either 3 boxes are empty when I click submit but it's not working, what am I doing wrong? I put in a onsubmit in my form but still doesnt work
HTML:
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
message.textContent = n + " is empty";
return false;
}
}
}
<!doctype html>
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="task2.js"></script>
</head>
<body>
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
</body>
</html>
Fix this:
<form id="myForm" method="get" onsubmit="checkforblank()">
</form>
See here
There is no need for return statement
The type of the button should be submit instead of button. Since you are comparing the value inside the function, you have to set the input's placeholder property instead of value
<button id="submitButton" type="submit"> Submit </button>
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
message.textContent = n + " is empty";
return false;
}
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
Though I will prefer the following:
var message = document.getElementById("ErrorMessage");
function clearMyField(el) {
if(el.placeholder !='') {
el.placeholder = '';
}
}
function checkforblank() {
var allInputs = document.querySelectorAll('input[type=text]');
for(let i = 0; i<allInputs.length; i++){
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if(v == ""){
return false;
}
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);" required></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);" required></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);" required></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
</form>
You can use html5 attributes to do this easily. (required, placeholder attributes)
Try below code.
<!doctype html>
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form id="myForm" method="get">
<h1> Form Submit </h1>
<p><span>Name:</span> <input id="input1" placeholder="Enter Name" name="Name" required></p>
<p><span>Student Id:</span> <input id="input2" placeholder="Enter Student ID" name="StudentID" required></p>
<p><span>Email:</span> <input id="input3" placeholder="Enter Email" name="Email" required></p>
<p>
<button id="submitButton" type="submit">Submit </button>
<input type="reset" value="Reset"/>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
</body>
</html>
You cannot see the error messages because the form submission refreshes the page. To see the errors, use event.preventDefault to get the errors.
Try the below code.
<html lang="en">
<head>
<title> Lab 6 - Task 2 </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
</head>
<body>
<form id="myForm" method="get">
<h1> Form Submit </h1>
<p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
<p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
<p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
<p>
<button id="submitButton" type="submit"> Submit </button>
<input type="reset" value="Reset">
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>
<script>
var message = document.getElementById("ErrorMessage");
//document.getElementById('myForm')
function clearMyField(el) {
if (el.placeholder != '') {
el.placeholder = '';
}
}
//Add event listener
document.getElementById('myForm')
.addEventListener('submit', function (e) {
console.log('submit')
//prevent the default submission to see the errors.
e.preventDefault()
var allInputs = document.querySelectorAll('input[type=text]');
for (let i = 0; i < allInputs.length; i++) {
let v = allInputs[i].value.trim();
let n = allInputs[i].name;
if (v == "") {
message.textContent = n + " is empty";
return false;
}
}
})
</script>
</body>
</html>
I have created a simple payment form using HTML/CSS/JS and i want to make checks of what the user gives as inputs using html patterns. But i also want to create a pop up alert using JS to confirm the form which must pop after all required inputs are filled correctly and patterns are ok.The pop up alert must also contain the name the user provided and return it.But the problem is that when i press submit button, even though the required info is not filled, the alert does come up and says "Order Completed" ....How can i make the pop up come up only after all info is given correctly?Here is my code:
<!DOCTYPE html>
<html>
<style>
body {
border:10px solid black;
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 150px;
}
p.thick {
font-weight: bold;
}
input[type=text], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=text]:focus {
border: 3px solid #555;
}
input[type=password]:focus {
border: 3px solid #555;
}
input[type=password], select {
width: 100%;
padding: 20px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: red;
}
div {
border-radius: 5px;
background-color:rgb(238, 238, 232);
padding: 40px;
}
</style>
<body onload="CreditCard();">
<form id="Myform">
<div class="login-page">
<div class="form">
<fieldset>
<h1>Log in </h1>
<p>Username*: <input type="text" name="Username" pattern=".{3,}" title="3 or more characters"></p>
<p>Password*: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[A-Z]).{5,}"placeholder="Password must contain 1 uppercaser and 1 number and must be atleast 5 digits." title="Must contain at least one number and one uppercase letter, and at least 5 or more characters."></p>
</fieldset>
<fieldset>
<h1> Payment </h1>
<select id="paymentmethod" onchange="CreditCard();">
<option value ="Payment on pickup">Payment on pickup</option>
<option value="Bank transfer/deposit">Bank transfer/deposit</option>
<option value="Credit/Debit card">Credit/Debit card</option>
</select>
<fieldset>
<div id="credit/debit card" style="display: block;">
<select name="cardtype" class="form">
<option value="VISA">VISA</option>
<option value="MasterCard">MasterCard</option>
</select>
<br>Card Number*:<br>
<input type="text" name="cardnumber" pattern="(?=.*\d).{16,16}" title="Enter a 16-digit card number please." style="width:80%;" maxlength="20" value="" required>
<tr>
<td height="22" align="right" valign="middle">Expiry Date:</td>
<td colspan="2" align="left">
<SELECT NAME="CCExpiresMonth" >
<OPTION VALUE="01">January (01)
<OPTION VALUE="02">February (02)
<OPTION VALUE="03">March (03)
<OPTION VALUE="04"SELECTED>April (04)
<OPTION VALUE="05">May (05)
<OPTION VALUE="06">June (06)
<OPTION VALUE="07">July (07)
<OPTION VALUE="08">August (08)
<OPTION VALUE="09">September (09)
<OPTION VALUE="10">October (10)
<OPTION VALUE="11">November (11)
<OPTION VALUE="12">December (12)
</SELECT>
<SELECT NAME="CardExpiresYear">
<OPTION VALUE="04"SELECTED>2016
<OPTION VALUE="05">2017
<OPTION VALUE="06">2018
<OPTION VALUE="07">2019
<OPTION VALUE="08">2020
<OPTION VALUE="09">2021
<OPTION VALUE="10">2022
<OPTION VALUE="11">2023
<OPTION VALUE="12">2024
<OPTION VALUE="13">2025
</SELECT>
</td>
</tr>
</fieldset>
</fieldset>
<h1> Order Information </h1>
<p class="thick"> Name*: </p> <input type="text" id="customername" style="width:55% name="cardholder" value="" pattern=".{1,}" title="Please enter a name" required>
<p class="thick"> Adress*: </p> <input type="text"style="width:55;" name="cardholderadr" value="" pattern=".{3,}" title="Please enter an adress" required>
<p class="thick"> Phone </p> <input type="text"style="width:55;" pattern="(?=.*\d).{10,10}" title="Enter a 10 digit number please." name="cardholderpho" value="" >
<p class="thick"> email <input type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" title="Please enter a valid email adress" placeholder="example#email.com" >
<p class="thick"> Delivery comments </p> <input type="text" style="width:55; padding: 50px ;" name="cardholdercomm" value="" >
<p style="color:blue;"> I agree with the <a href="https://en.wikipedia.org/wiki/Terms_of_service">
*terms</a> <input type="radio" name="terms" title="Please agree to our terms." unchecked required onclick="terms();"></p>
<input type="submit" value="Submit" onclick="confirmed();">
<input type="button" onclick="reset()" value="Reset form">
</div>
</div>
</form>
<script>
function CreditCard() {
prefer = document.forms[0].paymentmethod.value;
if (prefer == "Credit/Debit card") {
document.getElementById("credit/debit card").style.visibility = "visible";
} else {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
}
function paymentwithcard() {
document.getElementById("credit/debit card").style.visibility = "hidden";
}
function reset() {
document.getElementById("Myform").reset();
}
function confirmed() {
var x = document.getElementById("customername").value;
alert("Order completed.Name used:" + x);
}
function terms() {
}
</script>
</body>
</html>
Focus on the inputs and the function confirmed().
The submit method executes when you press submit.
First you have to let the submit method wait that the comfirm method can execute, after it the submit method can be executed.
To accessing the attribute in your js you can use an id.
document.getElementById('submit-form').submit(function(ev) {
ev.preventDefault(); // to stop the form from submitting
confirmed();
this.submit(); // If confirmed succeeded
});
<input id="submit-form" type="submit" value="Submit">
To prevent form from submitting you need to change `onclick attribute
<input type="submit" value="Submit" onclick="return confirmed();">
and your function must return true or false depending on your form validation.
You are listening onclick, instead, you should listen for the submit event
Don't only rely on client-side validation, it's good for a clean UX but never trust the client
HTML5 provides some validation options in the form of the required and pattern attributes
window.addEventListener('load', function () {
document.getElementById('example-submit').addEventListener('submit', function () {
alert('done');
});
});
input:invalid {border: 1px solid red;}
input:valid {border: 1px solid green;}
<form action="?" method="post">
<input type="text" id="expire-year" required pattern="20[123]\d" placeholder="YYYY" />
<input type="text" id="expire-month" required pattern="0?[1-9]|1[012]" placeholder="MM" />
<input type="text" id="expire-day" required pattern="0?[1-9]|2\d|3[01]" placeholder="DD" />
<input type="submit" id="example-submit" />
</form>
Side notes
In your code, CreditCard isn't a constructor. Consider using a cammel case name creditCard instead
Try to cut down the code in your question to the bare minimum/example case if you want good quality answers, nearly all of the HTML provided is irrelevant to the question
I didn't use a snippet because the embedded iframe here on SO doesn't let you submit forms :)