Dynamically display element/label when ratio button is clicked - javascript

I'm trying to hide mailingaddress box and label, and also hide comments box and label. They will only show up when I click on the radio button "mail" (the first choice), and when I switch to another button/choice, those labels and fields will be hidden again. Same for comments - when I click on "I accepted" of Terms of Services - the comments box and label will show up, if I uncheck it, the box and the label disappear. I successfully hide them but I cannot make them appear again when I click on the mail button, neither can I make the comments box and label appear when I click on "I accept" of Terms of Services. Where did I go wrong?
var $ = function(id) { return document.getElementById(id); };
var processEntries = function() {
var isValid = true;
// get values for user entries
var email = $("email_address").value;
var phone = $("phone").value;
var country = $("country").value;
var terms = $("terms").checked; //return true or false indicates whether a check box is checked or not
//remove validity messages if there is any
$("email_address").nextElementSibling.textContent = "";
$("phone").nextElementSibling.textContent = "";
$("country").nextElementSibling.textContent = "";
$("terms").nextElementSibling.textContent = "";
// check user entries for validity
if (email === "") {
$("email_address").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (phone === "") {
$("phone").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (country === "") {
$("country").nextElementSibling.textContent = "Please select a country.";
isValid = false;
}
if (terms === false) {
$("terms").nextElementSibling.textContent = "This box must be checked.";
isValid = false;
}
if(isValid)
{
$("registration_form").submit(); //submit registration form
}
};
var resetForm = function() {
$("registration_form").reset();
$("email_address").nextElementSibling.textContent = "*";
$("phone").nextElementSibling.textContent = "*";
$("country").nextElementSibling.textContent = "*";
$("terms").nextElementSibling.textContent = "*";
$("email_address").focus();
};
$("register").onclick = processEntries;
$("reset_form").onclick = resetForm;
//step 1: hide mailingaddress box and label, hide comments box and label
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
//step 2: define event handler function and add event listener to hide or show mailing address box and label when radio buttons are clicked.
//show mailing addess box and label only when mail button is clicked, when other buttons are clicked, hide mailing address box and label
document.getElementById("mail").addEventListener("click", displayMailOption);
function displayMailOption() {
if (documenet.getElementById("mail").checked){
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
//step 3: define event handler functionn and add event listener to hide or show comment box and label when check box is clicked.
//show comment box and label only when check box is checked. when check box is unchecked, hide comment box and label
document.getElementById("comments").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (documenet.getElementById("comments").checked){
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
html { background-image: url("ginkgo.jpg");}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 730px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
h2 {
font-size: 120%;
margin-bottom: .25em;
}
label {
float: left;
width: 9em;
}
input, select , textarea{
width: 20em;
margin-left: 1em;
margin-bottom: 1em;
}
input[type="checkbox"],[type="radio"] {
width: 1em;
}
#registration_form span {
color: red;
font-size: 80%;
}
.hide {display: none;}
input[type="button"] {
background-color: #000;
border-radius: 5px;
color: #fff;
font-size: 1.2em;
width: 100px;
margin-right: 1.4em;}
input[type="button"]:hover {
background-color: #666;
cursor: pointer;
text-shadow: 2px 2px 2px #000;
box-shadow: inset 0 2px 2px #000;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Account Registration</title>
<link rel="stylesheet" type="text/css" href="register.css">
</head>
<body>
<main>
<h1>Register for an Account</h1>
<form action="register_account.html" method="get"
name="registration_form" id="registration_form">
<label for="email_address">E-Mail:</label>
<input type="text" name="email_address" id="email_address">
<span>*</span><br>
<label for="phone">Mobile Phone:</label>
<input type="text" name="phone" id="phone">
<span>*</span><br>
<label for="country">Country:</label>
<select name="country" id="country">
<option value="">Select an option</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
</select>
<span>*</span><br>
<label>Contact me by:</label>
<input type="radio" name="contact" id="mail" value="mail">Mail
<input type="radio" name="contact" id="email" value="email">Email
<input type="radio" name="contact" id="mphone" value="mobilephone">Mobile Phone
<input type="radio" name="contact" id="none" value="none">Don't contact me
<br>
<label for="mailingaddress">Your Mailing Address:</label>
<textarea id="mailingaddress"></textarea><br>
<label>Terms of Service:</label>
<input type="checkbox" name="terms" id="terms" value="yes">I accept
<span>*</span><br>
<label for="comments">Comments:</label>
<textarea id="comments" cols='20' rows='10' ></textarea><br>
<label> </label>
<input type="button" id="register" value="Register">
<input type="button" id="reset_form" value="Reset">
</form>
</main>
<script src="register.js"> </script>
</body>
</html>

You don't have event listeners for other radio inputs, so no code will run.
Add these:
document.getElementById("email").addEventListener("click", displayMailOption);
document.getElementById("mphone").addEventListener("click", displayMailOption);
document.getElementById("none").addEventListener("click", displayMailOption);
Now on every radio input change, your displayMailOption function will run.
The displayMailOption function should look like this, after fixing the typo and selecting the correct element:
function displayMailOption() {
if (document.getElementById("mail").checked) {
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
}
}
Fix the comment listener ID:
document.getElementById("terms").addEventListener("click", displayCommentOption);
The displayCommentOption function should look like this:
function displayCommentOption() {
if (document.getElementById("terms").checked) {
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("comments").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}

Actually you don't need JavaScript to achieve that. You can do it in pure CSS. But to answer your question first, the problem is that you attach the click event the label and the function is called only when input is clicked. So if "email", "phone" or other labels are clicked the function is not called and therefore the elements are not hidden.
Here is an example of how to do it using only CSS:
var $ = function(id) {
return document.getElementById(id);
};
var processEntries = function() {
var isValid = true;
// get values for user entries
var email = $("email_address").value;
var phone = $("phone").value;
var country = $("country").value;
var terms = $("terms").checked; //return true or false indicates whether a check box is checked or not
//remove validity messages if there is any
$("email_address").nextElementSibling.textContent = "";
$("phone").nextElementSibling.textContent = "";
$("country").nextElementSibling.textContent = "";
$("terms").nextElementSibling.textContent = "";
// check user entries for validity
if (email === "") {
$("email_address").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (phone === "") {
$("phone").nextElementSibling.textContent = "This field is required.";
isValid = false;
}
if (country === "") {
$("country").nextElementSibling.textContent = "Please select a country.";
isValid = false;
}
if (terms === false) {
$("terms").nextElementSibling.textContent = "This box must be checked.";
isValid = false;
}
if (isValid) {
$("registration_form").submit(); //submit registration form
}
};
var resetForm = function() {
$("registration_form").reset();
$("email_address").nextElementSibling.textContent = "*";
$("phone").nextElementSibling.textContent = "*";
$("country").nextElementSibling.textContent = "*";
$("terms").nextElementSibling.textContent = "*";
$("email_address").focus();
};
$("register").onclick = processEntries;
$("reset_form").onclick = resetForm;
//step 1: hide mailingaddress box and label, hide comments box and label
/*
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
*/
//step 2: define event handler function and add event listener to hide or show mailing address box and label when radio buttons are clicked.
//show mailing addess box and label only when mail button is clicked, when other buttons are clicked, hide mailing address box and label
//document.getElementById("mail").addEventListener("click", displayMailOption);
/*
function displayMailOption() {
if (document.getElementById("mail").checked) {
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
//step 3: define event handler functionn and add event listener to hide or show comment box and label when check box is clicked.
//show comment box and label only when check box is checked. when check box is unchecked, hide comment box and label
document.getElementById("comments").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (document.getElementById("comments").checked) {
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}
*/
html {
background-image: url("ginkgo.jpg");
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 730px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
h2 {
font-size: 120%;
margin-bottom: .25em;
}
label {
float: left;
width: 9em;
}
input,
select,
textarea {
width: 20em;
margin-left: 1em;
margin-bottom: 1em;
}
input[type="checkbox"],
[type="radio"] {
width: 1em;
}
#registration_form span {
color: red;
font-size: 80%;
}
.hide {
display: none;
}
input[type="button"] {
background-color: #000;
border-radius: 5px;
color: #fff;
font-size: 1.2em;
width: 100px;
margin-right: 1.4em;
}
input[type="button"]:hover {
background-color: #666;
cursor: pointer;
text-shadow: 2px 2px 2px #000;
box-shadow: inset 0 2px 2px #000;
}
/* Hide elements on load */
#mailingaddress,
#mailadress-label,
#comments-label,
#comments {
display: none;
}
/* Show elements when #mail is checked */
#mail:checked~#mailingaddress,
#mail:checked~#mailadress-label {
display: block;
}
/* Show comments when #terms is checked */
#terms:checked~#comments-label,
#terms:checked~#comments {
display: block;
}
<main>
<h1>Register for an Account</h1>
<form action="register_account.html" method="get" name="registration_form" id="registration_form">
<label for="email_address">E-Mail:</label>
<input type="text" name="email_address" id="email_address">
<span>*</span><br>
<label for="phone">Mobile Phone:</label>
<input type="text" name="phone" id="phone">
<span>*</span><br>
<label for="country">Country:</label>
<select name="country" id="country">
<option value="">Select an option</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
</select>
<span>*</span><br>
<label>Contact me by:</label>
<input type="radio" name="contact" id="mail" value="mail">Mail
<input type="radio" name="contact" id="email" value="email">Email
<input type="radio" name="contact" id="mphone" value="mobilephone">Mobile Phone
<input type="radio" name="contact" id="none" value="none">Don't contact me
<br>
<label for="mailingaddress" id='mailadress-label'>Your Mailing Address:</label>
<textarea id="mailingaddress"></textarea><br>
<label>Terms of Service:</label>
<input type="checkbox" name="terms" id="terms" value="yes">I accept
<span>*</span><br>
<label for="comments" id='comments-label'>Comments:</label>
<textarea id="comments" cols='20' rows='10'></textarea><br>
<label> </label>
<input type="button" id="register" value="Register">
<input type="button" id="reset_form" value="Reset">
</form>
</main>

jQuery('input[type=radio]').change(function(){
if (document.getElementById("mail").checked){
document.getElementsByTagName("label")[4].style.display = "block";
document.getElementById("mailingaddress").style.display = "block";
} else {
document.getElementsByTagName("label")[4].style.display = "none";
document.getElementById("mailingaddress").style.display = "none";
}
})
document.getElementById("terms").addEventListener("click", displayCommentOption);
function displayCommentOption() {
if (document.getElementById("terms").checked){
document.getElementsByTagName("label")[6].style.display = "block";
document.getElementById("comments").style.display = "block";
} else {
document.getElementsByTagName("label")[6].style.display = "none";
document.getElementById("comments").style.display = "none";
}
}

Related

Open new Tab window in Radio Button?

please anyone can help me I am stuck in radio buttons.
when user click on submit button under the radio buttons they should be redirected into new window like target="_blank"
please help me if there is any solution available.
then I change window.location.href
two window.open the code is not working properly
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
input[type=radio] {
-webkit-appearance: radio;
-O-appearance: radio;
-moz-appearance: radio;
opacity:1;
}
#header .bottom-header.blog h1 {
font-size: 64px;
color: red
}
input[type=radio]:hover + label {
border: solid 1px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=radio]:checked + label {
border: solid 2px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=text] {
font-weight:bold;
}
input[type=text]:hover {
}
input[type=email]:hover {
}
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p> <label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label></br>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label></br>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label></br>
</p>
<input type="button" onclick="window.location.href = (getCheckedValue(document.forms['radioExampleForm'].elements['number']));" value="Buy Now">
</form>
You should use window.open(url, '_blank') which will open the url in new tab. Again I would say opening in new tab will get certainly get struck by a popup blocker. I would recommend you using an anchor tag with target="_blank" in place of button (and change a tag's href in onchange of radio button) which will not get blocked by a popup blocker
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
input[type=radio] {
-webkit-appearance: radio;
-O-appearance: radio;
-moz-appearance: radio;
opacity:1;
}
#header .bottom-header.blog h1 {
font-size: 64px;
color: red
}
input[type=radio]:hover + label {
border: solid 1px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=radio]:checked + label {
border: solid 2px white; padding: 5px; border-radius: 1px;
border-color : red;
color : red;
opacity:1;
}
input[type=text] {
font-weight:bold;
}
input[type=text]:hover {
}
input[type=email]:hover {
}
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p> <label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label></br>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label></br>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label></br>
</p>
<input type="button" onclick="window.open(getCheckedValue(document.forms['radioExampleForm'].elements['number']), '_blank');" value="Buy Now">
</form>
Use the below script to do your task
$("input[type='button']").click(function(){
var numbers = document.getElementsByName('number');
var num_value;
for(var i = 0; i < numbers.length; i++){
if(numbers[i].checked){
num_value = numbers[i].value;
// alert(num_value);
window.open(num_value, '_blank');
}
}
});

Hide div when clicked outside without using window and document object

How can I hide a <div> when I click outside it using onblur? I tried with the code below, but when I click the checkbox it disappears, and when I click outside of it, it won’t disappear.
I then tried using window or document object which works, but is not supported by the platform that I’m currently using. I'm using Lightning platform
Is this otherwise possible using JavaScript and/or CSS?
var expanded = false;
function showshow() {
var show = document.getElementById("show");
if (!expanded) {
show.style.display = "block";
expanded = true;
} else {
show.style.display = "none";
expanded = false;
}
}
function hideshow() {
var show = document.getElementById("show");
if (expanded) {
show.style.display = "none";
expanded = false;
}
}
#show {
position: absolute;
width: 200px;
display: none;
border: 1px solid #000000;
background-color: #ffffff;
}
#show label {
display: block;
white-space: nowrap;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
#show label:hover {
background-color: #eff1f4;
}
<form id="input-form">
<button type="button" onclick="showshow()">Select an option</button>
<div id="show" tabindex="1" onblur="hideshow()">
<label for="OptionA">
<input type="checkbox" id="OptionA" value="Option A" />Option A</label>
<label for="OptionB">
<input type="checkbox" id="OptionB" value="Option B" />Option B</label>
<label for="OptionC">
<input type="checkbox" id="OptionC" value="Option C" />Option ABCDEFGHIJKLMNOPQRSTUVWXYZ</label>
</div>
</form>
document.getElementsByTagName("body")[0].addEventListener("click", function(){
if(event.target.parent.id !== "idOfYourDiv") {
// call hideshow() function
}
});
$(document).click(function(event) {
//if you click on anything except the modal itself or the "open modal" link, close the modal
if (!$(event.target).closest(".modal,.js-open-modal").length) {
$("body").find(".modal").removeClass("visible");
}
});
Make show focused when expanded, to hide onblur afterwords:
var expanded = false;
function showshow() {
var show = document.getElementById("show");
if (!expanded) {
show.style.display = "block";
show.focus(); // make show focused
expanded = true;
} else {
show.style.display = "none";
expanded = false;
}
}
function hideshow() {
var show = document.getElementById("show");
if (expanded) {
setTimeout(() => {
show.style.display = "none";
expanded = false;
}, 100);
}
}
#show {
position: absolute;
width: 200px;
display: none;
border: 1px solid #000000;
background-color: #ffffff;
}
#show label {
display: block;
white-space: nowrap;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
#show label:hover {
background-color: #eff1f4;
}
<form id="input-form">
<button type="button" onclick="showshow()">Select an option</button>
<div id="show" tabindex="1" onblur="hideshow()">
<label for="OptionA">
<input type="checkbox" id="OptionA" value="Option A" />Option A</label>
<label for="OptionB">
<input type="checkbox" id="OptionB" value="Option B" />Option B</label>
<label for="OptionC">
<input type="checkbox" id="OptionC" value="Option C" />Option ABCDEFGHIJKLMNOPQRSTUVWXYZ</label>
</div>
</form>

Submit HTML form when confirm checkbox is checked

I 've created an HTML form with validations, when I directly click the sign-up button, without entering any data it alerts the user to accept the privacy policy and validation messages are displayed. Now when I fill the form and click the checkbox and then click the sign-up button it still alerts me to accept the privacy policy. Here is my code
$(function() {
$('#first-name-warning-message').hide();
$('#last-name-warning-message').hide();
var first_name_error = false;
var last_name_error = false;
$('#first-name').focusout(function() {
validate_first_name();
});
$('#last-name').focusout(function() {
validate_last_name();
});
function validate_first_name() {
var first_name = $('#first-name').val();
var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (first_name.length == '') {
$('#first-name-warning-message').html("Please Enter Your First Name !");
$('#first-name-warning-message').show();
first_name_error = true;
} else if (first_name.length < 3) {
$('#first-name-warning-message').html("First Name Not Valid !");
$('#first-name-warning-message').show();
first_name_error = true;
} else if (!first_name_regex.test(first_name)) {
$('#first-name-warning-message').html("First Name Must Not Contain Any Digits Or Symbols !");
$('#first-name-warning-message').show();
first_name_error = true;
} else {
$('#first-name-warning-message').hide();
}
}
function validate_last_name() {
var last_name = $('#last-name').val();
var last_name_regex = /^[a-zA-Z ]{3,15}$/;
if (last_name.length == '') {
$('#last-name-warning-message').html("Please Enter Your Last Name !");
$('#last-name-warning-message').show();
last_name_error = true;
} else if (last_name.length < 3) {
$('#last-name-warning-message').html("Last Name Not Valid !");
$('#last-name-warning-message').show();
last_name_error = true;
} else if (!last_name_regex.test(last_name)) {
$('#last-name-warning-message').html("Last Name Must Not Contain Any Digits Or Symbols !");
$('#last-name-warning-message').show();
last_name_error = true;
} else {
$('#last-name-warning-message').hide();
}
}
$('#sign-up-form').submit(function(e) {
first_name_error = false;
last_name_error = false;
age_error = false;
validate_first_name();
validate_last_name();
check_confirmation();
function check_confirmation() {
if (!$('privacy-policy').is(":checked")) {
window.alert("Please Accept Our Privacy Policy !");
e.preventDefault();
} else {
window.alert("Thank You For Accepting Our Privacy Policy !");
}
}
if ((first_name_error == false) && (last_name_error == false)) {
return true;
} else {
return false;
}
});
});
#first-name {
width: 300px;
margin-top: 10px;
margin-left: 200px;
padding-left: 10px;
border: 1px solid grey;
border-radius: 5px;
}
#last-name {
width: 300px;
margin-top: 5px;
margin-left: 200px;
padding-left: 10px;
border: 1px solid grey;
border-radius: 5px;
}
#first-name-warning-message {
padding-left: 350px;
font-size: 18px;
font-weight: bold;
}
#last-name-warning-message {
padding-left: 350px;
font-size: 18px;
font-weight: bold;
}
#privacy-policy {
margin-left: 10px;
}
#sign-up-button {
width: 200px;
margin-top: 10px;
margin-left: 240px;
font-size: 18px;
border-radius: 50px;
}
<!DOCTYPE html>
<html id="html">
<head id="html">
<title> E-Chatz_Online.com - Sign Up </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body id="body">
<form id="sign-up-form" method="post">
<div id="row-one">
<input type="text" id="first-name" name="first_name" placeholder="First Name" maxlength="15" autocomplete="off">
</div>
<div id="span-container">
<span id="first-name-warning-message" class="text-danger"> </span>
</div>
<div id="row-two">
<input type="text" id="last-name" name="last_name" placeholder="Last Name" maxlength="15" autocomplete="off">
</div>
<div id="span-container">
<span id="last-name-warning-message" class="text-danger"> </span>
</div>
<div id="row-three">
<input type="checkbox" id="privacy-policy"> By clicking the <b> Sign Up </b> button, you acknowledge that you have read and agree our Privacy Policy . </input>
</div>
<div id="row-four">
<button id="sign-up-button" name="sign_up_button" class="btn btn-primary" type="submit"> Sign Up </button>
</div>
</form>
</body>
</html>
How to solve this problem.
Use # infront of the variable.
Use privacy-policy in function check_confirmation()
It was a simple mistake. Your selector was not correct. You need to change
$('privacy-policy').is(":checked")
to
$('#privacy-policy').is(":checked")
as privacy-policy is an id that you want to refer to.
<!DOCTYPE html>
<html id="html">
<head id="html">
<title> E-Chatz_Online.com - Sign Up </title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
#first-name {
width: 300px;
margin-top: 10px;
margin-left: 200px;
padding-left: 10px;
border: 1px solid grey;
border-radius: 5px;
}
#last-name {
width: 300px;
margin-top: 5px;
margin-left: 200px;
padding-left: 10px;
border: 1px solid grey;
border-radius: 5px;
}
#first-name-warning-message {
padding-left: 350px;
font-size: 18px;
font-weight: bold;
}
#last-name-warning-message {
padding-left: 350px;
font-size: 18px;
font-weight: bold;
}
#privacy-policy {
margin-left: 10px;
}
#sign-up-button {
width: 200px;
margin-top: 10px;
margin-left: 240px;
font-size: 18px;
border-radius: 50px;
}
</style>
</head>
<body id="body">
<form id="sign-up-form" method="post">
<div id="row-one">
<input type="text" id="first-name" name="first_name" placeholder="First Name" maxlength="15" autocomplete="off">
</div>
<div id="span-container">
<span id="first-name-warning-message" class="text-danger"> </span>
</div>
<div id="row-two">
<input type="text" id="last-name" name="last_name" placeholder="Last Name" maxlength="15" autocomplete="off">
</div>
<div id="span-container">
<span id="last-name-warning-message" class="text-danger"> </span>
</div>
<div id="row-three">
<input type="checkbox" id="privacy-policy"> By clicking the <b> Sign Up </b> button, you acknowledge that you have read and agree our Privacy Policy . </input>
</div>
<div id="row-four">
<button id="sign-up-button" name="sign_up_button" class="btn btn-primary" type="submit"> Sign Up </button>
</div>
</form>
<script>
$(function() {
$('#first-name-warning-message').hide();
$('#last-name-warning-message').hide();
var first_name_error = false;
var last_name_error = false;
$('#first-name').focusout(function() {
validate_first_name();
});
$('#last-name').focusout(function() {
validate_last_name();
});
function validate_first_name() {
var first_name = $('#first-name').val();
var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (first_name.length == '') {
$('#first-name-warning-message').html("Please Enter Your First Name !");
$('#first-name-warning-message').show();
first_name_error = true;
} else if (first_name.length < 3) {
$('#first-name-warning-message').html("First Name Not Valid !");
$('#first-name-warning-message').show();
first_name_error = true;
} else if (!first_name_regex.test(first_name)) {
$('#first-name-warning-message').html("First Name Must Not Contain Any Digits Or Symbols !");
$('#first-name-warning-message').show();
first_name_error = true;
} else {
$('#first-name-warning-message').hide();
}
}
function validate_last_name() {
var last_name = $('#last-name').val();
var last_name_regex = /^[a-zA-Z ]{3,15}$/;
if (last_name.length == '') {
$('#last-name-warning-message').html("Please Enter Your Last Name !");
$('#last-name-warning-message').show();
last_name_error = true;
} else if (last_name.length < 3) {
$('#last-name-warning-message').html("Last Name Not Valid !");
$('#last-name-warning-message').show();
last_name_error = true;
} else if (!last_name_regex.test(last_name)) {
$('#last-name-warning-message').html("Last Name Must Not Contain Any Digits Or Symbols !");
$('#last-name-warning-message').show();
last_name_error = true;
} else {
$('#last-name-warning-message').hide();
}
}
$('#sign-up-form').submit(function(e) {
first_name_error = false;
last_name_error = false;
age_error = false;
validate_first_name();
validate_last_name();
check_confirmation();
function check_confirmation() {
if (!$('#privacy-policy').is(":checked")) {
window.alert("Please Accept Our Privacy Policy !");
e.preventDefault();
} else {
window.alert("Thank You For Accepting Our Privacy Policy !");
}
}
if ((first_name_error == false) && (last_name_error == false)) {
return true;
} else {
return false;
}
});
});
</script>
</body>
</html>

How to display a table onclick submit if textbox is not null demo: https://jsfiddle.net/21bbc4wm/

I want to display a table on click submit only if text box is not null
Demo: https://jsfiddle.net/21bbc4wm/
When i click submit button it returns no table, pls can someone help me out of this
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required />
<div id= "container1" style="display:none;">
<p style="text-align:center; font-size:160%;">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
<td><button style="background-color: #4CAF50;" id = "buttonSubmit"
type="submit" value="Submit" onclick ='check(); return
false'>Submit</button></td>
Javascript:
function check()
{
if(document.getElementById("note").value == null ||
document.getElementById("note").value == "")
{
alert("You must mention User ID for the result!!!");
document.getElementById("note").focus();
return false
var x = document.getElementById("container1");
if (x.style.display = "none") {
x.style.display = "block";
} else {
x.style.display = "true";
}
}
document.addEventListener("click", function(e){
var table = document.getElementById("demo");
var content = document.getElementById("container1");
var val = document.getElementById("note");
if(e.target.id === "buttonSubmit") {
if(val.value === null || val.value === "") {
alert("You must mention User ID for the result!!!");
content.classList.remove("active");
val.focus();
}
else {
var date = new Date();
/* remove this line for stacking */ table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
table.innerHTML += '<tr><td>' + val.value + '</th><td>'+ date.toDateString() +'</th><tr>';
val.value = "";
content.classList.remove("active");
content.classList.add("active");
}
}
if(e.target.id === "buttonReset") {
table.innerHTML = '<tr><th>User ID</th><th>Date</th><tr>';
val.value = "";
content.classList.remove("active");
}
});
input {
font-size: 1em;
}
#container1 {
display: none;
}
#container1.active {
display: block;
}
#result {
text-align: center;
font-size: 160%;
}
#buttonSubmit {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
#buttonReset {
background-color: #4CAF50;
padding: 3px;
border: 1px solid black;
display: inline-block;
font-size: 1em;
cursor: pointer;
}
<input type="text" list="user" id="note" name="Username"
placeholder="User ID*" autocomplete="off" required>
<div id="container1">
<p id="result">Search Result</p>
<table id="demo">
<tr><th>User ID</th>
<th>Date</th><tr>
</table>
</div>
<a id="buttonSubmit">Submit</a>
<a id="buttonReset">Reset</a>

Force HTML form validation via JavaScript

I have created a HTML form which has two buttons (instead of a submit button), each programmatically sending the form to a unique form action address.
<form id="formExample">
<input type="text" id="input1" required>
<label type="button" onClick="form1()">Form Action 1</label>
<label type="button" onClick="form2()">Form Action 2</label>
</form>
The scripts:
form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
form.submit();
}
function form2() {
form.action="example2.php";
form.submit();
}
Work well, responding to which button you press. However, the same html form validation that worked before (when using a 'submit' button), no longer shows a hint and the form sends regardless of whether there is input or not.
I have read that because I am calling the form.submit() programmatically, it bypasses the onSubmit() function of a form, which is where the validation takes place.
My question is: Can I programmatically force the onSubmit() so that I get the validation pop up? I must make clear that I am NOT wanting to create a JavaScript form validation, i.e. using an alert; rather, use JavaScript to enforce the HTML validation as found here, when you click submit: https://jsfiddle.net/qdzxfm9u/
You can merely change your button's type to submit and drop the form.submit() from your JS part.
So the HTML part becomes:
<form id="formExample">
<input type="text" id="input1" required>
<button type="submit" onClick="form1()">Form Action 1</button>
<button type="submit" onClick="form2()">Form Action 2</button>
</form>
This way, clicking any button does submit by itself, but before is executed the JS part:
form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
}
function form2() {
form.action="example2.php";
}
EDIT
Warning: I originally based my solution on a copy of the OP HTML part, where the "pseudo-buttons" used a strange element <label type="input"...>, so I read (too quickly) as if it was <button type="button"...> and simply changed type from input to submit!
This way, it couldn't work as expected.
It is now corrected in the above code.
Maybe something like this :
var form = document.getElementById("formExample");
function form1() {
form.action="example1.php";
}
function form2() {
form.action="example2.php";
}
<form id="formExample">
<input type="text" id="input1" required>
<input type="submit" onClick="form1()" value="Form Action 1" />
<input type="submit" onClick="form2()" value="Form Action 2" />
</form>
How about making a dropdown list - could be radio buttons instead - containing the form two actions with one submit button like in this JS Fiddle, then having one function on form submit
var form = document.getElementById("formExample"),
select = document.getElementById("slct");
form.addEventListener('submit', function() {
if (select.value == 1) {
form.action = "example1.php";
} else {
form.action = "example2.php";
}
// alert for demo only
alert(form.action);
form.submit();
});
<form id="formExample">
<input type="text" id="input1" required>
<select id="slct" required>
<option></option>
<option value="1">Form Action 1</option>
<option value="2">Form Action 2</option>
</select>
<button type="submit">Submit</button>
</form>
function togglePassword(el){
var checked = el.checked;
if (checked) {
document.getElementById("password").type = 'text';
document.getElementById("toggleText").textContent= "Hide";
} else {
document.getElementById("password").type = 'password';
document.getElementById("toggleText").textContent= "Show";
}
}
function login()
{
var uname = document.getElementById("uname").value;
var password = document.getElementById("password").value;
if(uname === '')
{
alert("Please enter the user name.");
}
else if(password === '')
{
alert("Enter the password");
}
else
{
alert('Login Successful. Thank You!');
}
}
function clearFunc()
{
document.getElementById("uname").value="";
document.getElementById("password").value="";
<script type="text/javascript">
function togglePassword(el){
var checked = el.checked;
if (checked) {
document.getElementById("password").type = 'text';
document.getElementById("toggleText").textContent= "Hide";
} else {
document.getElementById("password").type = 'password';
document.getElementById("toggleText").textContent= "Show";
}
}
function login()
{
var uname = document.getElementById("uname").value;
var password = document.getElementById("password").value;
if(uname === '')
{
alert("Please enter the user name.");
}
else if(password === '')
{
alert("Enter the password");
}
else
{
alert('Login Successful. Thank You!');
}
}
function clearFunc()
{
document.getElementById("uname").value="";
document.getElementById("password").value="";
}
</script>
/* heading */
h1 {
display: block;
font-size: 2em;
font-weight: bold;
/* padding: 0% 1% 3% 6.5%; */
margin: 0% 35% -10% 36%;
}
h1:hover{
color:#4499d9 ;
transform: translateY(-5px);
}
/* bg image */
body {
background-image: url('img/bg4.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% 100%;
}
/* Bordered form */
form {
/* border: 13px solid black; */
width: 27%;
height: auto;
position: absolute;
left: 10%;
margin-left: -3px;
top: 18%;
}
/* Full-width inputs */
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Set a style for all buttons */
button {
background-color: #17234b;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 49%;
}
/* Add a hover effect for buttons */
button:hover {
background-color: #4499d9;
transform: translateY(-5px);
box-shadow: 1px 3px 7px #6f6d72;
}
#toggleText {
display: block;
}
/* Center the avatar image inside this container */
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
/* Avatar image */
img.avatar {
width: 30%;
border-radius: 20%;
box-shadow: 1px 3px 9px #6f6d72;
}
img.avatar:hover{
transform: translateY(-5px);
box-shadow: 7px 9px 9px #6f6d72;
}
/* Add padding to containers */
.container {
padding: 16px;
}
span.buttons{
width: 100%;
display: flow-root;
}
#toggleText{
float: left;
}
#toggle{
float: left;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>LOGIN PANEL</h1>
<!-- Login Form -->
<div class="form">
<form >
<div class="imgcontainer">
<img src="img/Login.jfif" alt="Login Avatar" class="avatar">
</div>
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id="uname" name="uname"/>
<label for="password"><b>Password</b></label>
<input type='password'placeholder="Enter Your Password" name="password" id='password'/>
<input type='checkbox' id='toggle' onchange='togglePassword(this)'><span id='toggleText'>Show</span>
<span class="buttons">
<button type="submit" value="Reset" onclick="clearFunc()" class="btn">Reset</button>
<button type="submit" value="Login" class="btn" onClick="login()">Login</button>
</span>
</div>
</form>
</div>
</body>
</html>

Categories

Resources