Showing Div Not Working On Select Using Javascript - javascript

I am trying to show the FILE DIV if the user selects the doctor value in the select statement. I know the if statement works because I also print the value in the console which works perfectly fine. I toggle my divs in the same exact manner in my other webpages so I'm not understanding what's going on with this one in particular.
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}
}
.hidden{
display : none;
}
<div>
<select id="accountType" name="type" class="form-control" onchange="viewFile()">
<option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
****************************************EDIT-WORKAROUND**********************
Since my code refused to work, I added a line of code with 'head' being the title and not a real value. Thanks to everyone who contributed. I took out the hidden class altogether but when I add it, it still doesn't work correctly.
function viewDocFile() {
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if (type === 'regular' || type === 'head') {
file.style.display = "none";
console.log(type);
} else {
file.style.display = "block";
console.log(type);
}
}
***************************FINAL-EDIT************************
Kept the original code, but added the CSS inline.
<div class="form-group col-md-6" id="doclicense" style="display:none;">
Works perfectly now.

Here is an example of how this code should be written (even if there are still horrors)
// declare them here and not in a function where they will be redone each time the function is called
const
file_IHM = document.querySelector('#doclicense')
,
type_IHM = document.querySelector('#accountType') // and not with .value ...!
;
type_IHM.onchange = function()
{
file_IHM.style.display = (this.value==='doctor')?"block":"none";
console.log('type_IHM.value', this.value );
}
#doclicense { display : none; }
<div>
<select id="accountType" name="type" class="form-control" > <!-- let the js in the js part -->
<option required>Account Type</option>
<option value="doctor" id="doctor" >Doctor</option>
<option value="regular" id="regular" >Regular Account</option>
</select>
</div>
<div class="file-class" id="doclicense"> <!-- do not use class="hidden... -->
<input type="file" name="license" />
<input type="submit" /> <!-- there is no form anywhere... why don't you use <button> ?? -->
</div>

If that what your code really looks like, did you add your js in a <script></script> tag?
Or do you want to toggle the hide and show of the div?
if so this answer may help
<select id="accountType" name="type" class="form-control" onchange="viewFile()"><option required>Account Type</option>
<option value="doctor" name="doctor" id="doctor">Doctor</option>
<option value="regular" name="regular" id="reg">Regular Account</option>
</select>
</div>
<div class="hidden file" id="doclicense">
<input type="file" name="license" />
<input type="submit"/>
</div>
<script>
function viewFile(){
var file = document.getElementById("doclicense");
var type = document.getElementById('accountType').value;
if(type === 'doctor') {
file.style.display = "block";
console.log(type);
}else{
file.style.display = "none";
console.log(type);
}
}
</script>

Related

Show multiple div elements on select using JavaScript

When I select the first option, I would like it to show the first input or div (already working) but now I need it for the 2nd option too and 3rd option too. I tried else if which didn't work.
function optSelectEstimate(nameSelect)
{
if(nameSelect){
admOptionValue = document.getElementById("optnbestim1").value;
if(admOptionValue == nameSelect.value){
document.getElementById("nbestim1").style.display = "block";
}
else{
document.getElementById("nbestim1").style.display = "none";
}
}
else{
document.getElementById("nbestim1").style.display = "none";
}
}
<form method="post" action="index-2.html">
<!--Form Group-->
<div class="form-group">
<label class="label">Étape #1</label>
<select style="width:250px;" onchange="optSelectEstimate(this);">
<option>Type de Service</option>
<option id="optnbestim1" value="fenetre">Fenêtres (panneau traditionnel)</option>
<option id="optnbestim2" value="gouttiere">Gouttières</option>
<option id="optnbestim3" value="lavagepression">Lavage à pression du revêtement extérieur</option>
</select>
</div>
<!--Form Group-->
<div class="form-group">
<label class="label">Étape #2</label>
<div id="nbestim1" style="display: none;">
<input type="number" name="nbestim1" placeholder="Unités"></div>
<div id="nbestim2" style="display: none;">
<input type="number" name="nbestim2" placeholder="Pied linéaire"></div>
<div id="nbestim3" style="display: none;">
<input type="number" name="nbestim3" placeholder="Pied carré"></div>
</div>
</form>
You can try the "selectedIndex" of your select.
var nbestimId = "nbestim" + (nameSelect.selectedIndex + 1);
document.getElementById(nbestimId).style.display = "block";
Did not test it.
Also you have to hide the other two, i suppose.

Activate textbox on change of an item in Drop down in HTML

I am trying to do the following:
I have drop down menu with four options in it. When I choose Shipped a text box should enabled. So I tried the following:
<div class="col-md-3">
<select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" <?php if ($dispatch_status == "Uploaded") echo "selected='selected'";?> >Uploaded</option>
<option value="Processing" <?php if ($dispatch_status == "Processing") echo "selected='selected'";?> >Processing</option>
<option value="Dispatched" <?php if ($dispatch_status == "Dispatched") echo "selected='selected'";?> >Dispatched</option>
<option value="Shipped" <?php if ($dispatch_status == "Shipped") echo "selected='selected'";?> >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
Java script:
<head>
<script type="text/javascript">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});
</script>
</head>
Doesn't seem to trigger? I don't see log on console too. What could be wrong here?
Update:
I have pasted the html code here:
https://justpaste.it/6zxwu
Update
Since you've now shared your other code I think I know what you want. You have multiple modals, each with a select list and shipping_notes textbox which should be enabled when the selection is Shipped for that particular modal. I've modified your HTML to get this working.
I've updated your HTML a bit. You have multiple elements with the same ID. HTML IDs should be unique. If you want to target multiple elements it's safer to use class (or data-) attributes. I've added class="order-status" to each select and class="shipping_notes_txt" to each textbox. I've used element.querySelector() and document.querySelectorAll() to select DOM elements.
The snippet below mimics two modals. When the select is updated, it only enables/disabled the textbox within the same form element.
// wait for the DOM to load
document.addEventListener('DOMContentLoaded', function() {
// get all select elements with class=order-status
var selects = document.querySelectorAll('.order-status');
// iterate over all select elements
for (var i = 0; i < selects.length; i++) {
// current element
var element = selects[i];
// add event listener to element
element.addEventListener('change', function()
{
console.log(this.value);
// get the form closest to this element
var form = this.closest('form');
// find the shipping notes textbox inside form and disable/enable
if (this.value == 'Shipped') {
form.querySelector('.shipping_notes_txt').disabled = false;
} else {
form.querySelector('.shipping_notes_txt').disabled = true;
}
});
// default value if status == Shipped: enable textbox
if (element.value == "Shipped")
{
var form = element.closest('form');
form.querySelector('.shipping_notes_txt').disabled = false;
}
}
});
.modal1 {
display:inline-block;
vertical-align:top;
padding: .5em;
padding-bottom:5em;
border: 1px solid black;
}
<div class="modal1">
<h3>First Modal</h3>
<div id="edit1" class="modal fade" role="dialog">
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus1" name= "ostatus">
<option value="Uploaded" selected='selected' >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped">Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes1" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
<div class="modal1">
<h3>Second Modal</h3>
<div id="edit20" class="modal fade" role="dialog" >
<form action="order.php" autocomplete="off" method="post">
<div class="col-md-2 ml-3 pt-1">
<label for="role" class="mr-3">Status</label>
</div>
<select class="form-control order-status" id="ostatus20" name= "ostatus">
<option value="Uploaded" >Uploaded</option>
<option value="Processing">Processing</option>
<option value="Dispatched">Dispatched</option>
<option value="Shipped" selected='selected' >Shipped</option>
</select>
<input type="text" class="form-control shipping_notes_txt" name="shipping_notes" disabled="true" id="shipping_notes20" aria-describedby="emailHelp" placeholder="Enter Shipping details">
</form>
</div>
</div>
Add onchange to your <select>
<select class="form-control" id="ostatus" name= "ostatus" onchange = "statuschange()">
And change the JavaScript to :
<script type="text/javascript">
function statuschange(){
var drpDownValue = document.getElementById('ostatus').value;
if (drpDownValue == 'Shipped')
{
document.getElementById('shipping_notes').disabled = false;
}
else
{
document.getElementById('shipping_notes').disabled = true;
}
}
</script>
assuming everything on the server side this works HTML comes first
<div class="col-md-3"> <select class="form-control" id="ostatus" name= "ostatus">
<option value="Uploaded" selected="selected" >Uploaded</option>
<option value="Processing" >Processing</option>
<option value="Dispatched" >Dispatched</option>
<option value="Shipped" >Shipped</option>
</select>
</div>
</div>
<input type="text" class="form-control" name="shipping_notes" disabled="true" id="shipping_notes" aria-describedby="" placeholder="Enter Shipping details">
document.getElementById('ostatus').addEventListener('change', function()
{
console.log(this.value);
if (this.value == 'Shipped') {
document.getElementById('shipping_notes').disabled = false;
} else {
document.getElementById('shipping_notes').disabled = true;
}
});

Validation form with JavaScript

I'm trying to create a form validation, in pure JavaScript.
I have two elements to validate, a select option and a checkbox, but I can't manage to make the select-option to work.
This is the first time I try this, please be patient:
var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');
function checkName(event) {
if (elSelectGender.valueOf() == null) { // If name not entered
elNameHint.innerHTML = 'You must insert your name.'; // Show message
event.preventDefault(); // Don't submit form
}
}
function checkGender(event) {
if (elSelectGender.valueOf() == 'Select an option:') { // If gender not selected
elGenderHint.innerHTML = 'You must select a gender.'; // Show message
event.preventDefault(); // Don't submit form
}
}
function checkTerms(event) {
if (!elTerms.checked) { // If check-box ticked
elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
event.preventDefault(); // Don't submit form
}
}
//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label for="firstName" class="input"> Name: </label>
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
<div id="nameHint" class="warning"></div>
</div>
<div>
<label for="gender" class="selectbox"> Gender: </label>
<select id="gender">
<option value="Select an option:">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<div id="genderHint" class="warning"></div>
</div>
<div>
<input type="checkbox" id="terms" />
<label for="terms" class="checkbox"> Check to agree to terms & conditions</label>
<div id="termsHint" class="warning"></div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>
</html>
I expect to have a warning message and validation for all three elements. If one of the three elements is not validated, it shouldn't go to the next page.
It only works for the checkbox for some reason, the other two elements are ignored.
I'd wrap the selects and inputs into label and use CSS to display the .warning error messages.
Than I'd use Array.prototype.some() to check for any of my elements does not passes a check to than use ev.preventDefault() and display the warnings:
const EL = sel => document.querySelector(sel),
warning = (el, err) => [err, el.closest('label').classList.toggle('is-error', err)][0],
noValue = el => warning(el, !el.value.trim()),
noCheck = el => warning(el, !el.checked),
checkFormRegistration = ev => {
const isSomeInvalid = [
noValue(EL('#firstName')),
noValue(EL('#gender')),
noCheck(EL('#terms'))
].some(b => b);
if (isSomeInvalid) ev.preventDefault();
};
EL('#registrationForm').addEventListener('submit', checkFormRegistration);
label.is-error > *{
outline: 1px solid red;
outline-offset: -1px;
}
label + .warning {
display: none;
color: red;
}
label.is-error + .warning {
display: block;
}
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label> Name:
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text">
</label>
<div class="warning">Please, enter a name</div>
</div>
<div>
<label> Gender:
<select id="gender">
<option value="">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
</label>
<div class="warning">Please, select a gender</div>
</div>
<div>
<label>
<input type="checkbox" id="terms">
Check to agree to terms & conditions
</label>
<div class="warning">You must agree to the terms</div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday">
</form>
I changed valueOf() to value equal to empty (when form is initialized, the field is empty, it is not null).
Make sure that your HTML elements are correct, I saw it was wrong before, now it seems to have been corrected.
I added an else statement to handle the errors in the case where the user corrects the validation errors.
Still, this is quite a simplification of validation, it takes a lot more work (things like min-length, max-length you might want to consider them too, as well as sanitization, trimming as mentioned by some commenters, which I will leave it to you).
var registrationForm, elSelectGender, elGenderHint, elTerms, elTermsHint; // Declare variables
registrationForm = document.getElementById('registrationForm'); // Store elements
elSelectGender = document.getElementById('gender');
elGenderHint = document.getElementById('genderHint');
elTerms = document.getElementById('terms');
elTermsHint = document.getElementById('termsHint');
elName = document.getElementById('firstName');
elNameHint = document.getElementById('nameHint');
function checkName(event) {
if (elName.value == '') { // If name not entered
elNameHint.innerHTML = 'You must insert your name.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elNameHint.innerHTML = '';
}
}
function checkGender(event) {
if (elSelectGender.value == 'Select an option:') { // If gender not selected
elGenderHint.innerHTML = 'You must select a gender.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elGenderHint.innerHTML = '';
}
}
function checkTerms(event) {
if (!elTerms.checked) { // If check-box ticked
elTermsHint.innerHTML = 'You must agree to the terms.'; // Show message
event.preventDefault(); // Don't submit form
} else {
elTermsHint.innerHTML = '';
}
}
//Create event listeners: submit calls checkTerms(), change calls packageHint()
registrationForm.addEventListener('submit', checkName, false);
registrationForm.addEventListener('submit', checkGender, false);
registrationForm.addEventListener('submit', checkTerms, false);
<!DOCTYPE HTML>
<html>
<form id="registrationForm" name="registrationForm" method="post" action="example.html">
<div>
<label for="firstName" class="input"> Name: </label>
<input name="firstName" class="form-control" id="firstName" placeholder="First Name" type="text" />
<div id="nameHint" class="warning"></div>
</div>
<div>
<label for="gender" class="selectbox"> Gender: </label>
<select id="gender">
<option value="Select an option:">Select an option:</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<div id="genderHint" class="warning"></div>
</div>
<div>
<input type="checkbox" id="terms" />
<label for="terms" class="checkbox"> Check to agree to terms & conditions</label>
<div id="termsHint" class="warning"></div>
</div>
<input class="btn btn-primary" id="submitButton" type="submit" value="Sign up for G Holiday" />
</form>
</html>

Browser issue :Branching Select Drop Down Not Supporting in IE 7 or 8

I have a Branching Drop down that is not working in the IE version 7 and 8 but working in all the other browsers .
Here is a js Fiddle link for live demo : http://jsfiddle.net/r64w7/
MY code :
HTML :
<div>
<label >Select a step</label>
<select id="selectCreateNew">
<option value="input">
Input
</option>
<option value="radio">
Radio
</option>
</select>
</div>
<div id="section1" style="display:none;">
<label >Input</label>
<input name="" type="text"/>
</div>
<div id="section2" style="display:none;">
<label >Radio</label>
<input name="" type="radio" value=""/>
</div>
javascripts
var sections ={
'input': 'section1',
'radio': 'section2',
};
selection = function(select) {
for(i in sections)
document.getElementById(sections[i]).style.display = "none";
document.getElementById(sections[select.value]).style.display = "block";
}
document.getElementById('selectCreateNew').addEventListener('change', function() {
selection(this);
try{for(var lastpass_iter=0; lastpass_iter < document.forms.length; lastpass_iter++)
{ var lastpass_f = document.forms[lastpass_iter];
if(typeof(lastpass_f.lpsubmitorig2)=="undefined")
{ lastpass_f.lpsubmitorig2 = lastpass_f.submit; lastpass_f.submit = function()
{ var form=this; var customEvent = document.createEvent("Event");
customEvent.initEvent("lpCustomEvent", true, true);
var d = document.getElementById("hiddenlpsubmitdiv");
for(var i = 0; i < document.forms.length; i++)
{ if(document.forms[i]==form){ d.innerText=i; } }
d.dispatchEvent(customEvent);
form.lpsubmitorig2(); } } }}catch(e){}
});
I am really poor in java scripts and jQuery . I got this from from my other post . I am not figuring out what is he issue for his not working in the IE 7 and 8 . Is there any way to make work this in IE 7 or 8 . If will be great if can be made support with IE 7 .
Thanks
I know the question isn't tagged jQuery, but it was mentioned in the question, so I feel a jQuery-based answer is appropriate because this is actually very easy using jQuery.
Here's your HTML code. I've modified it slightly - note the changed values of the options and the extra wrapper <div> around the sections:
<div>
<label >Select a step</label>
<select id="selectCreateNew">
<option value="section1">
Input
</option>
<option value="section2">
Radio
</option>
</select>
</div>
<div id='sections'>
<div id="section1" style="display:none;">
<label >Input</label>
<input name="" type="text"/>
</div>
<div id="section2" style="display:none;">
<label >Radio</label>
<input name="" type="radio" value=""/>
</div>
</div>
..and some jQuery code to do the magic:
$('#selectCreateNew').change(function() {
var showme = $(this).val();
$('#sections>div').each(function(i,e) {
$(e).toggle(e.id === showme);
});
});
Yeah, it's as short as that. :-)
Here it is as a jsFiddle

change input size depending on option selected

I've seen similar questions posted and tried to change them to meet my needs but I don't know enough about javascript to do it. All I want to do is limit a form input to 2 characters if they select "state" as their search option. This is what I have:
function changeValue(){
var option=document.getElementById('searchtype').id;
if (option == ("A") || ("B") ){
document.getElementById('field').size="40";
}
else if(option=="C"){
document.getElementById('field').size="2";
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue();">
<option id="A" value="name">Hospital Name<br /></option>
<option id="B" value="city">City</option>
<option id="C" value="state">State</option>
</select>
<br /><br />
Search:<br />
<input id="field" name="searchterm" type="text" size="0">
Am I doing something wrong or is there a better way to do this?
I used Jack's code below and added a field.size attribute so my input matched the max allowed characters: (thanks Jack)
script type="text/javascript">
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
field.size = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2);
field.maxLength = 2;
field.size = 2;
}
}
</script>
<h1>Hospital Search</h1>
<form action="results.php" method="post">
Search By:<br />
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
<option id="name" value="name">Hospital Name<br /></option>
<option id="city" value="city">City</option>
<option id="state" value="state">State</option>
</select><br />
Search:<br />
<input id="field" name="field" type="text" size="40">
</input>
After deciding a dropdown with a list of states would be better, I changed it to this:
<form action="results.php" method="post">
Hospital Name:<br />
<input name="searchterm_name" type="text" size="40">
<br />
<input type="submit" name="submit" value="Search">
</form><br />
<form action="results.php" method="get">
City Name:<br />
<input name="searchterm_city" type="text" size="40"><br />
<select name="select_state">
<option value="">None
<option value="AL" Selected>Alabama
<option value="AK">Alaska
<option value="AZ">Arizona
</SELECT>
<input type="submit" name="submit" value="Search">
</form>
ED: Using form method "post" caused the browser to throw a warning every time I hit the back button to get to the results page. I changed to "get" since the information is not sensitive and now it goes back w/o warning.
Set the maxlength property:
document.getElementById('field').maxlength = 2;
I realize now that the rest of the code is not likely to work:
function changeValue(dropdown) {
var option = dropdown.options[dropdown.selectedIndex].value,
field = document.getElementById('field');
if (option == 'name' || option == 'city') {
field.maxLength = 40;
} else if (option == 'state') {
field.value = field.value.substr(0, 2); // before reducing the maxlength, make sure it contains at most two characters; you could also reset the value altogether
field.maxLength = 2;
}
}​
Then in your HTML:
<select id="searchtype" name="searchtype" onchange="changeValue(this);">
try this
function changeValue() {
var option2 = document.getElementById('searchtype').options[document.getElementById('searchtype').selectedIndex].id;
if (option2 == ("A") || option2 == ("B")) {
document.getElementById('field').size = "40";
}
else if (option2 == "C") {
document.getElementById('field').size = "2";
}
}​
Try this.
document.getElementById('field').setAttribute('size', "10");

Categories