If Div containing html input is hidden, remove required attribute - javascript

Looking for help with this please, tried to run with many articles on here but can't seem to get what I'm after.
What you will see in the following snippet works for showing and hiding the different options depending on whether the first option is Yes or No.
However I want all fields to be required but I need a way of them only being required, if they are shown.
Believe there will be something I could add or alter with the JavaScript to remove the required attributes?
function yesnoCheck(that) {
if (that.value == "Yes") {
document.getElementById("ifYes").style.display = "block";
} else {
document.getElementById("ifYes").style.display = "none";
}
if (that.value == "No") {
document.getElementById("ifNo").style.display = "block";
document.getElementById("ifNo2").style.display = "block";
} else {
document.getElementById("ifNo").style.display = "none";
document.getElementById("ifNo2").style.display = "none";
}
}
<form name="emailsend" class="form-check" method="post" action="send.php">
<label>Decision maker selection</label>
<br>
<select name='resolved' onchange="yesnoCheck(this);">
<option value='' selected disabled hidden></option>
<option value='No' > No </option>
<option value='Yes' > Yes </option>
</select>
<br>
<div id="ifYes" style="display: none;">
<br>
<label>Showifresolvedisyes</label>
<br>
<select name='ref2' required>
<option value='Test' > Test </option>
</select>
</div>
<div id="ifNo" style="display: none;">
<label>Showifresolvedisno</label>
<br>
<select name='colour' >
<option value='' selected disabled hidden></option>
<option value='red' class="redoption" > Red </option>
<option value='orange' class="amberoption" > Amber </option>
<option value='green' class="greenoption" > Green </option>
</select>
</div>
<br>
<div id="ifNo2" style="display: none;">
<label>Showifresolvedisno</label>
<br>
<select name='ref3' required>
<option value='Test'>Test</option>
</select>
<br>
<br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">
Take me to the Preview!
</button>
</div>
</form>
Any help would be massively appreciated!

First you don't need to add selected and disabled attributes to your empty default options. When you select an empty option by default, that overrides the required attribute of the select tag because it is already selected with an empty value.
second I would choose class name instead of id for ifYes and ifNo containers.
this way it would be easier to add more Select tags and options without need to add more ids and styling them separately and you can control them simultaneously like this:
const ifYes = document.querySelectorAll(".ifYes");
const ifNo = document.querySelectorAll(".ifNo");
const theForm = document.forms["emailsend"];
theForm.resolved.onchange = () => {
const yes = theForm.resolved.value === "Yes";
ifYes.forEach((div) => {
div.classList.toggle("noDisplay", !yes);
div.querySelector("select").required = yes;
});
ifNo.forEach((div) => {
div.classList.toggle("noDisplay", yes);
div.querySelector("select").required = !yes;
});
};
.noDisplay {
display: none;
}
<form name="emailsend" class="form-check" method="post" action="send.php">
<label>Decision maker selection</label><br />
<select name="resolved" required>
<option value="" hidden></option>
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<br />
<div class="noDisplay ifYes">
<label>Show if resolved is yes</label><br />
<select name="ref2" required>
<option value="" hidden></option>
<option value="Test">Option 1</option>
<option value="Test">Option 2</option>
</select>
</div>
<div class="noDisplay ifNo">
<label>Show if resolved is no</label><br />
<select name="colour" required>
<option value="" hidden></option>
<option value="red">Red</option>
<option value="orange">Amber</option>
</select>
</div>
<br />
<div class="noDisplay ifNo">
<label>Show if resolved is no</label><br />
<select name="ref3" required>
<option value="" hidden></option>
<option value="Test">option 1</option>
<option value="Test">option 2</option>
</select>
<br />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">
Take me to the Preview!
</button>
</div>
</form>

I will do that this way:
It is necessary to dispose of a css noDisplay class, instead of your style="display: none;" in the HTML
const div_ifYes = document.getElementById('ifYes')
, div_ifNo1 = document.getElementById('ifNo')
, div_ifNo2 = document.getElementById('ifNo2')
, theForm = document.forms['emailsend']
, AllRequired = theForm.querySelectorAll('[required]')
;
function setRequired()
{
AllRequired.forEach(el=>
{
el.required = !el.closest('div').classList.contains('noDisplay');
})
}
setRequired() // on start
;
theForm.resolved.onchange = () =>
{
div_ifYes.classList.toggle('noDisplay', !(theForm.resolved.value === 'Yes'))
div_ifNo1.classList.toggle('noDisplay', !(theForm.resolved.value === 'No'))
div_ifNo2.classList.toggle('noDisplay', !(theForm.resolved.value === 'No'))
setRequired()
}
theForm.onsubmit = e => // just for letting the testing here
{
e.preventDefault() // disable submit
}
.noDisplay {
display: none;
}
<form name="emailsend" class="form-check" method="post" action="send.php">
<label>Decision maker selection</label>
<br>
<select name='resolved'>
<option value='' selected disabled hidden></option>
<option value='No' > No </option>
<option value='Yes' > Yes </option>
</select>
<br>
<div id="ifYes" class="noDisplay">
<br>
<label>Showifresolvedisyes</label>
<br>
<select name='ref2' required>
<option value='Test' > Test </option>
</select>
</div>
<div id="ifNo" class="noDisplay">
<label>Showifresolvedisno</label>
<br>
<select name='colour' >
<option value='' selected disabled hidden></option>
<option value='red' class="redoption" > Red </option>
<option value='orange' class="amberoption" > Amber </option>
<option value='green' class="greenoption" > Green </option>
</select>
</div>
<br>
<div id="ifNo2" class="noDisplay">
<label>Showifresolvedisno</label>
<br>
<select name='ref3' required>
<option value='Test' > Test </option>
</select>
<br>
<br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">
Take me to the Preview!
</button>
</div>
</form>

Related

How do i add multiple conditions in an if statement in javascript?

I'm kind of new to JavaScript and all and I'm having trouble with how to add multiple conditions in an if statement. I wanted the if statement to do: "if 'this' and 'this' and 'this' is selected (I made a select tag so it is a drop down selection) then send the user to another page. I've search solutions but they're too complex for me right now as I'm still a beginner in JavaScript. Sorry if it is not explained well this is my first time making a question in this site. Thank You! Here's my code for the html if needed.
<h1>Clothes Picker</h1>
<form action="clothespicker.html" id="clothespicker">
<fieldset>
<label for="place">Where are you going today?</label>
<div>
<select name="place" id="place">
<option value="Someone's House">Someone's House</option>
<option value="Outdoors">Outdoors</option>
<option value="Shopping">Shopping</option>
<option value="Local Shopping">Local Shopping</option>
<option value="Somewhere Special">Somewhere Special</option>
</select>
</div>
<label for="weather">What's the weather?</label>
<div>
<select name="weather" id="weather">
<option value="Sunny" id="Sunny">Sunny</option>
<option value="Cold">Cold</option>
<option value="Rainy">Rainy</option>
<option value="Cloudy">Cloudy</option>
</select>
</div>
<label for="look">How do you want to look?</label>
<div>
<select name="look" id="look">
<option value="Casual" id="Casual">Casual</option>
<option value="Formal">Formal</option>
<option value="I don't know">I don't know</option>
</select>
</div>
<input type="submit" value="Pick My Clothes!" id="button"></div>
</fieldset>
</form>
I made one condition for you take a look. My condition matched when you select "outdoors" from place, "Sunny" from weather and "casual" from look. If you have multiple conditions then you can else if after if condition
<h1>Clothes Picker</h1>
<form action="clothespicker.html" id="clothespicker">
<fieldset>
<label for="place">Where are you going today?</label>
<div>
<select name="place" id="place">
<option value="Someone's House">Someone's House</option>
<option value="Outdoors">Outdoors</option>
<option value="Shopping">Shopping</option>
<option value="Local Shopping">Local Shopping</option>
<option value="Somewhere Special">Somewhere Special</option>
</select>
</div>
<label for="weather">What's the weather?</label>
<div>
<select name="weather" id="weather">
<option value="Sunny" id="Sunny">Sunny</option>
<option value="Cold">Cold</option>
<option value="Rainy">Rainy</option>
<option value="Cloudy">Cloudy</option>
</select>
</div>
<label for="look">How do you want to look?</label>
<div>
<select name="look" id="look">
<option value="Casual" id="Casual">Casual</option>
<option value="Formal">Formal</option>
<option value="I don't know">I don't know</option>
</select>
</div>
<input type="submit" onclick="myFunction()" value="Pick My Clothes!" id="button">
</fieldset>
<p id="demo"></p>
</form>
<script>
function myFunction() {
var place = document.getElementById("place").value;
var weather = document.getElementById("weather").value;
var look = document.getElementById("look").value;
if(place == "Outdoors" && weather == "Sunny" && look == "Casual")
{
//your condition here
document.getElementById("demo").innerHTML = "Condition Matched";
}
}
</script>

In Javascript, how do you select "option" attribute from "select" element in HTML?

In JavaScript, how would I get whatever option the user selects from the menu list? I'm trying to make it so that when the first option "default" is selected, it displays an error message.
How do i do this in Javascript without changing the HTML? Thanks in advance!
<div class="error"></div>
<form class="form">
<div class="form-control">
<label for="menu">Menu List</label>
<select name="menu" id="menu">
<option value="default">Choose an image...</option>
<option value="fries">Fries</option>
<option value="ice-cream">Ice cream</option>
<option value="cake">Cheesecake</option>
</select>
</div>
</form>
Get the value property of the <select> element.
document.querySelector("#submit").addEventListener("click", function() {
let choice = document.getElementById("menu").value;
if (choice == "default") {
alert("Please select an image");
} else {
console.log("Thank you for purchasing " + choice);
}
});
<div class="error"></div>
<form class="form">
<div class="form-control">
<label for="menu">Menu List</label>
<select name="menu" id="menu">
<option value="default">Choose an image...</option>
<option value="fries">Fries</option>
<option value="ice-cream">Ice cream</option>
<option value="cake">Cheesecake</option>
</select>
</div>
<br>
<button type="button" id="submit">Submit</button>
</form>
If select has a blank first value and the select is required, they cannot submit the form
const sel = document.getElementById("menu");
sel.options[0].value=""; // remove the value
sel.setAttribute("required","required");
<div class="error"></div>
<form class="form">
<div class="form-control">
<label for="menu">Menu List</label>
<select name="menu" id="menu">
<option value="default">Choose an image...</option>
<option value="fries">Fries</option>
<option value="ice-cream">Ice cream</option>
<option value="cake">Cheesecake</option>
</select>
</div>
<input type="submit">
</form>

Show only two select boxes

Basically, i want it so every time someone clicks on the button it will show one select box and then they click it again it will show the other one. So my question is how can I make it so on click it will show a select box one at a time?
Select box add function:
function addChooseSub() {
window["maxAppend"] = 3;
maxAppend = maxAppend + 1;
$("select.signUp[name=\"option" + maxAppend +"\"]").show();
console.log("sdasd"+maxAppend)
}
Click Function:
<script>
$('body').on('click', '.addSelect', function() {
addChooseSub()
});
</script>
Box HTML:
<div class="signup box">
Hello, <strong><?php echo $session->getSessionInfo("register", "firstName")." ".$session->getSessionInfo("register", "lastName"); ?></strong> and welcome to <strong>LetsChat</strong>, please choose up to <strong>5 courses</strong> you're currently taking.
<hr>
<form method="POST" action="#" class="chooseCourse">
<select class="signUp" name="option1">
<option value="empty" disabled selected hidden>Course Option 1</option>
<?php $core->pullCourses(); ?>
</select>
<select class="signUp" name="option2">
<option value="empty" disabled selected hidden>Course Option 2</option>
<?php $core->pullCourses(); ?>
</select>
<select class="signUp" name="option3">
<option value="empty" disabled selected hidden>Course Option 3</option>
<?php $core->pullCourses(); ?>
</select>
<select class="signUp" name="option4" style="display: none;">
<option value="empty" disabled selected hidden>Course Option 4</option>
<?php $core->pullCourses(); ?>
</select>
<select class="signUp" name="option5" style="display: none;">
<option value="empty" disabled selected hidden>Course Option 5</option>
<?php $core->pullCourses(); ?>
</select>
<div class="addSelect"> + </div>
<input type="submit" name="signupSubmit" onclick="choosingSubjects()" class="purple btn signup" value="Finish" style="margin-top: 0;">
</form>
</div>
What's happening is your window.maxAppend = 3; at the top of your function is resetting it every time your function is called.
There are a few ways to accomplish what you want, but the easiest will be to just move maxAppend outside of the function. This way, it will not get reset, and its value will be preserved from the last time it was called.
var maxAppend = 3;
function addChooseSub() {
maxAppend++;
if (maxAppend > 5) return;
$("select.signUp[name=\"option" + maxAppend +"\"]").show();
console.log("sdasd"+maxAppend)
}
You have a few more issues than I saw from the start.
You need to move the counter outside the function
There is no hidden attribute on an option.
Like this - assuming you want to initially have the last two SELECTS hidden and show next two SELECTs one by one
var maxAppend = 3;
$(function() {
$(".addSelect").on("click", function(e) {
maxAppend++;
if (maxAppend <= $("select.signUp").length) {
$("select.signUp[name=\"option" + maxAppend + "\"]").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="signup box">
<hr>
<form method="POST" action="#" class="chooseCourse">
<select class="signUp" name="option1">
<option value="empty" disabled selected>Course Option 1</option>
</select>
<br>
<select class="signUp" name="option2">
<option value="empty" disabled selected>Course Option 2</option>
</select>
<br>
<select class="signUp" name="option3">
<option value="empty" disabled selected>Course Option 3</option>
</select>
<br>
<select class="signUp" name="option4" style="display: none;">
<option value="empty" disabled selected>Course Option 4</option>
</select>
<br>
<select class="signUp" name="option5" style="display: none;">
<option value="empty" disabled selected>Course Option 5</option>
</select>
<br>
<div class="addSelect">+</div>
<input type="submit" name="signupSubmit" class="purple btn signup" value="Finish" style="margin-top: 0;" />
</form>
</div>

HTML form with JS does not work properly in PHP

I have a form with JS where I hide and show form's fields after choosing option with radiobuttons.
<?php require_once 'resources/menus/adminMenu.php'; ?>
<div class="col-lg-offset-3 col-lg-6 ">
<div class="well bs-component">
<form class="form-group" method="post">
<fieldset>
<legend>Wyszukaj</legend>
<div class="form-group" style="display: block" id="queryIndex">
<label for="index" class="control-label">Indeks</label>
<input class="form-control" id="index" name="index" type="text">
</div>
<div class="form-group" style="display: none" id="queryName">
<label for="name" class="control-label">Imię</label>
<input class="form-control" id="name" name="name" type="text">
<label for="surname" class="control-label">Nazwisko</label>
<input class="form-control" id="surname" name="surname" type="text">
</div>
<div class="form-group" style="display: none" id="queryFaculty">
<label for="faculty" class="control-label">Wydział</label>
<select class="form-control" id="faculty" name="faculty" required="required">
<option value=""></option>
<option value="Wydział A">Wydział A</option>
<option value="Wydział B">Wydział B</option>
<option value="Wydział C">Wydział C</option>
<option value="Wydział D">Wydział D</option>
<option value="Wydział E">Wydział E</option>
</select>
</div>
<div class="form-group" style="display: none" id="querySubject">
<label for="subject" class="control-label">Kierunek</label>
<select class="form-control" id="subject" name="subject" required="required">
<option value=""></option>
<option value="Kierunek AA">Kierunek AA</option>
<option value="Kierunek AB">Kierunek AB</option>
<option value="Kierunek AC">Kierunek AC</option>
<option value="Kierunek BA">Kierunek BA</option>
<option value="Kierunek BB">Kierunek BB</option>
<option value="Kierunek BC">Kierunek BC</option>
<option value="Kierunek CA">Kierunek CA</option>
<option value="Kierunek CB">Kierunek CB</option>
<option value="Kierunek CC">Kierunek CC</option>
<option value="Kierunek DA">Kierunek DA</option>
<option value="Kierunek DB">Kierunek DB</option>
<option value="Kierunek DC">Kierunek DC</option>
<option value="Kierunek EA">Kierunek EA</option>
<option value="Kierunek EB">Kierunek EB</option>
<option value="Kierunek EC">Kierunek EC</option>
</select>
</div>
<div class="form-group" style="display: none" id="querySystem">
<label for="system" class="control-label">System</label>
<select class="form-control" id="system" name="system" required="required">
<option value=""></option>
<option value="st">Stacjonarne</option>
<option value="nst">Niestacjonarne</option>
</select>
</div>
<div class="form-group" style="display: none" id="queryDegree">
<label for="degree" class="control-label">Stopień</label>
<select class="form-control" id="degree" name="degree" required="required">
<option value=""></option>
<option value="I">1. stopień (inżynierskie/licencjat)</option>
<option value="II">2. stopień (magisterskie)</option>
</select>
</div>
<div class="form-group" style="display: none" id="querySemester">
<label for="semester" class="control-label">Semestr</label>
<select class="form-control" id="semester" name="semester" required="required">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="form-group">
<input type="radio" name="search" value="index" checked="checked"
onClick="changeForm('queryIndex')"> Indeks
<input type="radio" name="search" value="name"
onClick="changeForm('queryName')"> Imię i nazwisko
<input type="radio" name="search" value="faculty"
onClick="changeForm('queryFaculty')"> Wydział
<input type="radio" name="search" value="subject"
onClick="changeForm('querySubject')"> Kierunek
<input type="radio" name="search" value="system"
onClick="changeForm('querySystem')"> System
<input type="radio" name="search" value="degree"
onClick="changeForm('queryDegree')"> Stopień
<input type="radio" name="search" value="semester"
onClick="changeForm('querySemester')"> Semestr
</div>
<script type="text/javascript">
function changeForm(element) {
document.getElementById('queryIndex').style.display = 'none';
document.getElementById('queryName').style.display = 'none';
document.getElementById('queryFaculty').style.display = 'none';
document.getElementById('querySubject').style.display = 'none';
document.getElementById('querySystem').style.display = 'none';
document.getElementById('queryDegree').style.display = 'none';
document.getElementById('querySemester').style.display = 'none';
document.getElementById(element).style.display = 'block';
}
</script>
<div class="form-group col-lg-4">
<div class="control-label">
<button type="submit" class="btn btn-primary" name="submit" value="searchStudent">Szukaj
</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
Also I have PHP file, where I get data from this form.
function studentWindow()
{
$this->setView("AdminPanel", "StudentWindow");
if (isset($_POST['submit']) && $_POST['submit'] == 'searchStudent') {
$query="";
$data=array();
if($_POST['search']=='index'){
$data['index']=sanitizeString($_POST['index']);
$query="st_index LIKE '?%'";
}
elseif($_POST['search']=='name'){
$data['name']=sanitizeString($_POST['name']);
$data['surname']=sanitizeString($_POST['surname']);
$query="name LIKE '?%' AND surname LIKE '?%'";
}
elseif($_POST['search']=='faculty'){
$data['faculty']=$_POST['faculty'];
$query='AS st INNER JOIN subject AS s ON st.id_subject=s.id_subject INNER JOIN faculty AS f ON s.id_faculty=f.id_faculty WHERE f.name=?';
}
elseif($_POST['search']=='subject'){
$data['subject']=$_POST['subject'];
$query='AS st INNER JOIN subject AS s ON st.id_subject=s.id_subject WHERE s.name=?';
}
elseif($_POST['search']=='system'){
$data['system']=$_POST['system'];
$query='system=?';
}
elseif($_POST['search']=='degree'){
$data['degree']=$_POST['degree'];
$query='degree=?';
}
elseif($_POST['search']=='semester'){
$data['semester']=$_POST['semester'];
$query='semester=?';
}
$this->loadModel("AdminPanel");
$model = new AdminPanelModel();
$model->getStudents($query,$data);
}
}
This is a problem. I can't get data from forms and also the button doesn't work. I made other forms like this but without JS. This may be the cause. Do you have any suggestions or solutions?
P.S. Sorry for my English ;)
The problem is using required='required' when the form fields are not required.
The user can submit at any time and it is not evident that you must click each radio button in turn to fill out that portion, if that was the intention.
I ran your code as plain HTML and examined the POST data in the Chrome Dev Tools and it works fine if you fill out all fields with required...
You will get an error in console that says the following:
An invalid form control with name='faculty' is not focusable.
Chrome is trying to focus the field to add error messages, but you set style.display = 'none' so it can't.

How to create different number of input text fields for different options in the drop down menu?

This is what I am trying to achieve -
Select different options from a drop down menu.
Input different number of text fields depending on the option selected.
Like when selecting optionA it should automatically create 2 textfields for some input.
OptionB should create 5 textfields for inputs.
Here is where I am struggling -
Can't get the option id or value of the option selected
Creating variable number of textfields.
HTML Code -
<body>
<p>
<select name="Select Flow" id="Flow" >
<option id="option0" value="https://fusion.paypal.com">Send Money</option>
<option id="option1" value="option1">optionA</option>
<option id="option2" value="option2">OptionB</option>
<option id="option3" value="option3">C</option>
<option id="option4" value="option4">D</option>
<option id="option5">E</option>
<option id="option6">F</option>
<option id="option7">G</option>
<option id="option8" value="option8">H</option>
</select>
</p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" onclick="myfunc()"action="" />
</p>
</body>
JS-
function myfunc()
{
var value="F";
var t = document.getElementById("Flow");
alert((t.options.length).innnerHTML);
for(var i=0; i<t.options.length;i++)
{
if(t.options[i].text == value)
{
t.selectedIndex = i;
alert(t.selectedIndex.innerHTML);
}
}
}
This code can help you
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(name,job)
{
alert(document.getElementById("Flow").value);
write = document.getElementById('textfeilds');
for(i=0;i<document.getElementById("Flow").value;i++)
{
write.innerHTML += '<input type="text">';
}
}
</script>
<p>
<select name="Select Flow" id="Flow" >
<option id="option0" value="4">Send Money</option>
<option id="option1" value="1">optionA</option>
<option id="option2" value="2">OptionB</option>
<option id="option3" value="3">C</option>
<option id="option4" value="4">D</option>
<option id="option5" value="5">E</option>
<option id="option6" value="6">F</option>
<option id="option7" value="7">G</option>
<option id="option8" value="8">H</option>
</select>
</p>
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" onclick="myFunction()"action="" />
</p>
<div id="textfeilds"></div>
</body>
</html>

Categories