Show/hide fieldset based on radio button using Javascript - javascript

I'm trying to have the email/phone number section of a contact form hidden or visible depending on whether the user picks the phone or email radio button, but I cannot figure out why it is not working for me.
I've searched through stack overflow & w3Schools, and I'm pretty certain I'm using the correct syntax but it will still not show/hide depending on the radio buttons.
Any help would be hugely appreciated!
HTML
<form name="contactForm" id="contactForm" method="post" action="result.php">
<fieldset>
<!-- Client's contact details -->
<legend>Contact Details</legend>
<label for="fullname">Full Name:</label>
<input type="text" name="contact" id="fullname" required>
<label>Preferred contact method:</label>
<input type="radio" name="contact" value="rdoPhone" id="rdoPhone" checked="checked" onclick="cPhone()" >Phone
<input type="radio" name="contact" value="rdoEmail" id="rdoEmail" onclick="cEmail()" >Email
<label for="phonenumber">Phone Number:</label>
<input type="text" name="contact" id="phonenumber">
<label for="email">Email:</label>
<input type="text" name="contact" id="email">
</fieldset>
</form>
CSS
#email {
display:none;
}
#phonenumber {
display:none;
}
Javascript
function cPhone() {
if (document.getElementById("rdoPhone").checked)
{ document.getElementById("phonenumber").style.display = "block"; }
}
function cEmail(){
if (document.getElementById("rdoEmail").checked)
{ document.getElementById("email").style.display = "block"; }
}

Since phone number is checked by default, you should not hide it initially.
You don't have to check for the checked property on click of a radio in a radio button group, because a click will always select it.
You can use a common function for this purpose as follows -
apply the class hide given below initially for the email.
call the function showHide(this) given below onClick of both radios
css
.hide {
display:none;
}
js
function showHide(elm) {
var phone = document.getElementById("phonenumber");
var email = document.getElementById("email")
if(elm.id == 'rdoPhone'){
phone.classList.remove('hide');
email.classList.add('hide');
}
else
{
phone.classList.add('hide');
email.classList.remove('hide');
}
}
Demo

It is faster to apply it directly in javascript:
$('#id-element').css('display', 'block');
$('#id-element').css('display', 'none');

Related

Use javascript with POST method

sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form

copy text into field using radio selection

I am wanting to create the following using CSS, HTML and JavaScript
Course1 //dropdown selection//
....
Course2 //dropdown selection//
.....
WINNER
(RADIO checked for Course1) OR (RADIO clicked for Course2)
//automatically populated from either Course1 or Course2 depending on Radio checked//
but my dropdown selection and radio selection hamper each other.
When I have the name from the radio the same "winnerselected" the radio works, but the copying from the course1 or course2 doesn't work.
Maybe someone has created code like this somewhere else and knows how to get around it?
Any assistance will be appreciate.
code as follows:
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 1
<input id="myInput" type="text" name="golfcoursename1" placeholder="Golf
Course">
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
Course 2
<input id="myInput1" type="text" name="golfcoursename2" placeholder="Golf
Course">
</div>
<p>
WINNER
<p>
<input type="radio" id="Course1" name="winnerselected" value="Course1"
onclick="FillWinner(this.form)">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2"
onclick="FillWinner2(this.form)">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
<p>
</p>
<input type="submit">
</form>
<script>
function FillWinner(f) {
if(f.winnerselected.checked == true) {
f.winner.value = f.golfcoursename1.value;
if(f.winnerselected.checked == true)
f.winner.value = f.golfcoursename2.value;
}}
</script>
First, your HTML is not valid as you have a second form, with no closing tag, nested in the first one. Also, while is is legal to not close a p element, you really should for clarity sake.
Next, remove inline styles and inline JavaScript from your HTML. It just clutters up the code, causes redundancy, and is harder to read and maintain. Instead break your work into HTML, CSS, and JavaScript sections.
It's not clear what you exactly want, but my guess is that whichever radio button is clicked should dictate which textbox value becomes the winner. Based on that, see the comments inline below for a description of how the code works.
.autocomplete { width:300px; }
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off" action="/action_page.php">
<div class="courses">
<div class="autocomplete">
Course 1 <input id="myInput" name="golfcoursename1" placeholder="Golf Course">
</div>
<div class="autocomplete">
Course 2 <input id="myInput1" name="golfcoursename2" placeholder="Golf Course">
</div>
</div>
<p>WINNER</p>
<p id="radioContainer">
<input type="radio" id="Course1" name="winnerselected" value="Course1">
<label for="Course1">Course 1</label>
<input type="radio" id="Course2" name="winnerselected" value="Course2">
<label for="Course2">Course 2</label><br>
<input type="text" id="winner" name="Winner" placeholder="Winner">
</p>
<input type="submit">
</form>
<script>
// Don't use inline HTML event attributes like onclick.
// Separate your JavaScript from your HTML
// Get references to the element(s) you'll need to work with
// Get all the elements that have a name attribute that starts with "golfcoursename"
const courseNames = document.querySelectorAll("[name^='golfcoursename']");
// Get all the elements that have a name attribute that is exactly "winnerselected"
const radioButtons = document.querySelectorAll("[name='winnerselected']");
const winner = document.getElementById("winner");
// Here's how to set up events in JS
const radCont = document.getElementById("radioContainer").addEventListener("click", fillWinner);
function fillWinner(event) {
// Look at the radiobuttons collection and get the index of the selected radio button from it.
const indexOfTextbox = Array.from(radioButtons).indexOf(event.target);
// Set the value of the winner textbox to textbox with the same index as the clicked radio button
winner.value = courseNames[indexOfTextbox].value;
}
</script>

custom web component with vanilla javascript and validations

I am working in a web component, but I want to add it validations with javascript constrains, but It looks like this just work for inputs elements and my main container is a div.
I am not sure if it exists some workaround for this. I had tried to use an input with display none or size 0x0, but this dislike to me and does not work good.
<form action="">
<input type="text" required="" name="field1">
<input type="text" required="" name="field2">
<div name="mycustominput" myValidation="true">
<!--
children html elements render list and another things
I want to validate this with the form
-->
</div>
</form>
Can you help me?
if you try some inputs validate together like this:
<form id="passwordForm" novalidate>
<fieldset>
<legend>Change Your Password</legend>
<ul>
<li>
<label for="password1">Password 1:</label>
<input type="password" required id="password1" />
</li>
<li>
<label for="password2">Password 2:</label>
<input type="password" required id="password2" />
</li>
</ul>
<input type="submit" />
</fieldset>
js
var password1 = document.getElementById('password1');
var password2 = document.getElementById('password2');
var checkPasswordValidity = function() {
if (password1.value != password2.value) {
password1.setCustomValidity('Passwords must match.');
} else {
password1.setCustomValidity('');
}
};
password1.addEventListener('change', checkPasswordValidity, false);
password2.addEventListener('change', checkPasswordValidity, false);
var form = document.getElementById('passwordForm');
form.addEventListener('submit', function() {
checkPasswordValidity();
if (!this.checkValidity()) {
event.preventDefault();
//Implement you own means of displaying error messages to the user here.
password1.focus();
}
}, false);
this link (http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/) is yours.
have a good day.

run.google.script only if form is complete

I'm trying to create a form using the google scripts that will not allow submission unless all the fields are entered. Currently, I use the "onclick" command to run a google script that send the form data and files to my google drive. However, I only want the form to be submittable if certain fields are filled in (those marked required). If I remove the google.script.run command from the "onclick" portion of the submit button, then the form creates alerts/messages that say the user must fill in the required form. These messages do not appear when the google.script.run command is included. I haven't figured out a way to make it so that the google.script.run command only runs if all fields are completed.
<!-- Include the Google CSS package -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<!-- You can also include your own CSS styles -->
<style>
form { margin: 40px auto; }
input { display:inline-block; margin: 20px; }
</style>
<form id="myForm" name="myForm">
<label for="myFirstName"> First Name *</label>
<input type="text" name="myFirstName" placeholder="First name" style="width: 150px;" required>
<fieldset>
<legend> Personal Information </legend>
<div class="inline form-group">
</div>
<div class="inline form-group">
<label for="myLastName"> Last Name* </label>
<input type="text" name="myLastName" placeholder="Last Name" style="width: 150px;" required>
</div>
<div class="inline form-group">
<label for="myEmail"> Email* </label>
<input type="email" name="myEmail" placeholder="" style="width: 150px;" required>
</div>
<div class="inline form-group">
<label for="visa"> Check if you will require visa assistance. Otherwise, ignore. </label>
<input type="checkbox" name="visa" value="Yes">
</div>
</fieldset>
<fieldset>
<legend> Documents </legend>
<div class="inline form-group">
<label for="CV"> CV* </label>
<input type="file" name="CV" required>
</div>
<div class="inline form-group">
<label for="CoverLetter"> Cover Letter </label>
<input type="file" name="CoverLetter">
</div>
</fieldset>
<p> </p>
<input id="submitbutton" type="submit" style="margin-left:450px" value="Submit Application"
onclick="this.value='Submitting...';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
The googlescript runs fine. I'm also aware of some similar questions about form validation. The google script specific ones do not use the same form format (they create the form in google script). I would like to make as minimal changes as possible to achieve the required functionality.
Any help would be appreciated.
Current code for jquery:
$('#submitbutton').on('click', function() {
$(this).val("Validating...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
if ($(this).val().length === 0){
$(this).addClass("warning")
return true
} else {
return false
}
});
if (emptyFields.length === 0) {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
$(this).val("Submit Application")
}
});
Your form is submitting before the messages can appear. One way to handle this is to change your button to a button (instead of type submit), and then trigger an event on click. Check for your validation, and if everything passes, submit your form.
example:
change your button to:
<input id="submitbutton" type="button" style="margin-left:450px" value="Submit Application" >
and the click event:
$('#submitbutton').on('click', function() {
$(this).val("Validating...");
//check for required fields
var emptyFields = $('[required]').filter(function() {
$(this).removeClass("warning");
return $(this).val().length === 0;
});
if (emptyFields.length > 0) {
emptyFields.addClass("warning");
} else {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
$('#myForm').submit();
}
});
and CSS
.warning {border: 1px solid red; }

jQuery, submit() with multiple forms using .each()

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>
Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Categories

Resources