Two else-if statements result in errors in javascript - javascript

I have two else-if statements in my code. When I added the other else-if statement the first one resulted in an error. When I took it away, it was working just fine. I have multiple conditions for each else-if statement although I'm pretty sure I didn't set-up the conditions like I'm supposed to. If the user selects the right conditions listed in the statement it will turn an image and its text to display flex. I feel that I'm not using the && and || operators correctly in my conditions and maybe that's why the error is occurring, but I'm not sure. I've tried messing around with the && and || operators in my condition but nothings helping. I keep getting a "can't read property selected of null " error.
document.getElementById("2");
document.getElementById("3");
document.getElementById("4");
function emotion() {
if( document.getElementById("1/1").selected === true && document.getElementById("2/1").selected === true && document.getElementById("3/1").selected === true && document.getElementById("4/2").selected === true ) {
document.querySelector('.happy').style.display = 'flex';
document.querySelector('.htext').style.display = 'flex';
} else if (document.getElementById("1/3").selected === true && document.getElementById("2/2").selected === true || document.getElementById("2/3").selected === true || document.getElementById("3/3").selected === true && document.getElementById("4/1").selected === true || document.getElementById("4/2").selected === true) {
document.querySelector('.okay').style.display = 'flex';
document.querySelector('.otext').style.display = 'flex';
} else if (document.getElementById("1/4").selected === true || document.getElementById("1/5").selected === true && document.getElementById("3/4").selected === true && document.getElementById("4/1").selected === true || document.getElementById("4/2").selected === true ) {
document.querySelector('.sad').style.display = 'flex';
document.querySelector('.text').style.display = 'flex';
}
}
.happy {
position:absolute;
left:520px;
display:none;
}
.htext {
position:relative;
left:285px;
top:250px;
display:none;
}
.okay {
position:absolute;
left:520px;
display:none;
}
.otext {
position:relative;
left:205px;
top:250px;
display:none;
}
.sad {
position:absolute;
left:520px;
display:none;
}
.stext {
position:relative;
left:305px;
top:250px;
display:none;
}
<!DOCTYPE html>
<html>
<head>
<title>Emotion Tester</title>
</head>
<body>
<h1 align = "center">Hey there! How are you feeling today? Answer the questions below to determine your mood! 😄 </h1>
<p>PLEASE REFRESH EVERYTIME YOU PUT NEW INPUT!!</p>
<p>How was your day today?</p>
<select id = "1">
<option id = "1/1">It was amazing!</option>
<option id = "1/2">It was good</option>
<option id = "1/3">Fine</option>
<option id = "1/4">Wasn't good...</option>
<option id = "1/5">Horrible :(</option>
</select>
<p>Are you worried?</p>
<select id = "2">
<option id = "2/1">Not at all!</option>
<option id = "2/2">Yes, very</option>
<option id = "2/3">A little...</option>
</select>
<p>Are you happy with life?</p>
<select id = "3">
<option id = "3/1">My life is great!</option>
<option id = "3/2">It's a good life</option>
<option id = 3/3">I guess</option>
<option id = "3/4">Not at all</option>
</select>
<p>Are you mad at someone?</p>
<select id = "4">
<option id = "4/1">YES!</option>
<option id = "4/2">Nope :)</option>
</select>
<button onclick = "emotion()">SUBMIT</button>
<img src="https://s3.gifyu.com/images/happy-emoji.gif" class = "happy" width = "300px" height = "300px">
<h2 class = "htext">Seems like you're mood is HAPPY! You're happy with life and have a positive attitude</h2>
<img src="https://s3.gifyu.com/images/giphy-12e8027bed3a7ae23.gif" class = "okay" width = "300px" height = "300px">
<h2 class = "otext">It seems that you're day was just OKAY. You might feel upset, tired, or a little stressed.
Maybe you're just confused, like this emoji!.</h2>
<img src="https://s3.gifyu.com/images/sad-emoji9181fba54a527d19.gif" class = "sad" width = "300px" height = "300px">
<h2 class = "stext">Seems like your day wasn't the best. You may be sad or stressed.</h2>
</body>
</html>

From this jsfiddle: https://jsfiddle.net/7jLnvhd1/
I can't tell what your issue actually is.
I changed <option id = 3/3">I guess</option>
to
<option id = "3/3">I guess</option>
and added $(document).ready() within your JS.

Related

Getting a result after mutliple variables in javascript

I´m pretty new to coding and I´ve been trying to get a website running where there are multiple forms, I want to get different outputs depending on the interaction of the various answers.
As of now I get a change in the console congruent with the selected element, it seems to be working, the variables being:
let a = document.getElementById('CAL');
a.onchange = (ev) =>{
console.log( a.value);} //Gets the CAL value of low,high,medium or naCal
let b = document.getElementById('sev-lev-2');
b.onchange = (ev) =>{
console.log( b.value);} //Gets value of RBL as low, medium or high
let c = document.getElementById('sev-lev-3');
c.onchange = (ev) =>{
console.log( c.value);} //Gets value of tooth loss as low, medium or high
let d = document.getElementById('MPD');
d.onchange = (ev) =>{
console.log( d.value);} //Gets value of maximum pocket depth as low, medium or high
let e = document.getElementById('type-bl');
e.onchange = (ev) =>{
console.log( e.value);} //Gets value of type of bone loss as low or high
let f = document.getElementById('ST3a');
{console.log(f.checked);}
f.onchange = (ev) =>
{console.log(f.checked);} //checks if Furcation is ticked in (true) or not
let g = document.getElementById('ST3b');
{console.log(g.checked);}
g.onchange = (ev) =>
{console.log(g.checked);} //checks if Moderate ridge defects is ticked in (true) or not
let h = document.getElementById('ST4');
{console.log(h.checked);}
h.onchange = (ev) =>
{console.log(h.checked);} //checks if Need complex rehab is ticked in (true) or not
I tried grouping some variables (ab) (ce) (fg), I am missing something to make these work, they always come out as undefined (when connecting a button to as an example console.log (ab), I tried multiple ways but are still stuck with this:
let ab //Gets value for CAL or RBL
if (a === "low"|| b === "low") {ab= "low"}
else if (a === "medium"|| b === "medium") {ab=== "medium"}
else if (a === "hig"|| b === "high") {ab=== "high"}
else {ab=="null"}
let fg;
if (f === "false"&& g === "false"){fg==="false"}
else {fg === "true"} ;
let ce;
if (c === "false"&& e === "false"){ce==="false"}
else {ce === "true"}
The other part of the problem is that when I get results for ab/ce/fg I would like to get the end result from a function,so that I can couple the function to a button click. I structured the function with or without the grouped variables but still could not get to work, the version with grouped variables is:
function debug(){
if (ab == "low" && d == "low" && ce == "low" && fg=="false" && h == "false" ) {console.log;{"I"}}
else if (ab == "low" && d == "medium" && ce == "low" && fg=="false" && h == "false" ) {console.log ("II")}
else if (ab == "medium" && (d == "low"|| d =="medium") && ce == "low" && fg=="false" && h == "false") {console.log ("II")}
else if (ab == "medium" && ((c== "medium" || "high") ||(d=="high")||(e=="high")||(fg=="true"))) {console.log ("III")}
else if (ab == "high" && (c!= "high" || h!="true")) {console.log ("III")}
else if (ab=="high" && d== "high" && e=="high" && fg=="true" && h == "true") {console.log ("IV")}
else {console.log("")}
}
The HTML for the forms is the following:
<div id="staging">
<div id="severity">
<h2>Severity (Site of greater loss)</h2>
<div><label for="CAL">Clinical attachment level:</label>
<select name="CAL" id="CAL" onclick="Severity()">
<option value="">--Interdental CAL--</option>
<option value="low">1-2mm</option>
<option value="medium">3-4mm</option>
<option value="high">>5mm</option>
<option value="naCal" >Not available</option>
</select>
</div>
<div id="RBL" ><label for="rx-bone-loss">Radiographic bone loss (% of root):</label>
<select name="RBL" id="sev-lev-2" onclick="Severity2()">
<option value="">--Select RBL %--</option>
<option value="low"> <15%</option>
<option value="medium">15-33%</option>
<option value="high">>33%</option>
</select>
</div>
<div id="TL"><label for="tooth-loss">Perio caused tooth loss:</label>
<select name="tooth-loss" id="sev-lev-3">
<option value="">--Or planned for extraction--</option>
<option value="low"> None</option>
<option value="medium">≤4</option>
<option value="high">≥5</option>
</select>
</div>
</div>
<div id="Complexity">
<h2>Complexity</h2>
<p><label for="max-probing-depth">Max Probing Depth:</label>
<select name="MPD" id="MPD">
<option value="">--Max PD--</option>
<option value="low"> ≤4mm</option>
<option value="medium">≤5mm</option>
<option value="high">≥6mm</option>
</select>
</p>
<p><label for="type-bl">Type of bone loss:</label>
<select name="type-bl" id="type-bl">
<option value="">--Type--</option>
<option value="low"> Mostly horizontal</option>
<option value="high">Vertical ≥3mm </option>
</select>
</p>
<form> <p><b>Additional Information:</b></p>
<input type="checkbox" id="ST3a" value="ST3a"><label for="Furcation"> Furcation involvement cl II-III</label><br>
<input type="checkbox" id="ST3b" value="ST3b"><label for="Defect"> Moderate ridge defects</label><br>
<input type="checkbox" id="ST4" value="ST4"><label for="Rehab"> Need for complex rehabilitation</label><br>
</form>
</div>
Additional problem:
First of all thanks for the answers, some of it I did understand, a great deal is too complicated for my level...
Now I got the form working on single selections, but when trying to select another value without refreshing the value seems to go to "undefined" and with a second try give an error "Uncaught TypeError: Cannot read properties of undefined (reading 'value')
at a.onchange"
this code shows the error on one variable selection:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Perio Staging and Grading</title>
</head>
<body>
<h2>Severity (Site of greater loss)</h2>
<div><label for="CAL">Clinical attachment level:</label>
<select name="CAL" id="CAL" >
<option value="">--Interdental CAL--</option>
<option value="low">1-2mm</option>
<option value="medium">3-4mm</option>
<option value="high">>5mm</option>
<option value="naCal" >Not available</option>
</select>
</div>
</div>
</div>
<button id="debug">Submit</button>
<div id="result">
</div>
<script>
let a = document.getElementById('CAL');
a.onchange = (ev) =>{
a= (a.value);} //Gets the CAL value of low,high,medium or naCal
</script>
</body>

Show image depending on <option value> in a <select> element

I've been struggling for the last 2 days to create an option when a user clicks the button "submit" after they selected a value from a "select>" element, the website to show an image.
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
I tried something like this in Javascript, but everytime I click the submit button it adds a new image and I really dont want that, I want the image to change everytime a value is chosen.
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const aImg = document.createElement("img");
const cImg = document.createElement("img");
const eImg = document.createElement("img");
const sImg = document.createElement("img");
const eqImg = document.createElement("img");
const eqeImg = document.createElement("img");
aImg.src = "https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027"
cImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720"
eImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461"
sImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6InM1NnM5ZndkYTR4dC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.1N_EW-jPwI1Q33sSuwaIdYxTexUdYAHcWgEFYCPqkrU/image;s=1080x720"
eqImg.src = "https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg"
eqeImg.src = "https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg"
if (value === 'mba') {
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}
}
And 1 more bonus question: how to actually inject a whole div container with 3 flex childrens(a img, paragraph and a small div) when the submit button is clicked?
Try removing all child nodes from the container first:
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
const container = document.querySelector('#container');
removeAllChildNodes(container);
You can remove everything from the container before appending :
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
container.innerHTML = '';
[...]
or you can change src of image without appending new image
document.querySelector('#btn').addEventListener('click', submit);
const images = {
mba:'https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027',
mbc:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720',
mbe:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461',
mbs:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
mbeq:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
default:'https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg'
}
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const img = document.querySelector('#img');
if(images.hasOwnProperty(value)) {
img.setAttribute('src', images[value]);
} else {
img.setAttribute('src', images.default);
}
}
<label for="cars" id="carInput" name="carInput"/>
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
<div class="container">
<img id="img"/>
</div>
I suggest changing about the way you think of the relationship between the HTML and the JS. The former is the presentation layer, the latter is the logic layer. It makes little sense to include presentation information in your business logic, if you can help it. Right now, if you want to make changes to the way this select works (for example, adding new images or changing existing images) you have to change the JS as well as the HTML.
You could change your code to the following:
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let containerImg = document.querySelector('#container-img');
containerImg.hidden = false;
containerImg.src = value;
}
This allows you to add any number of future image options without having to touch the code. This makes some assumptions about the HTML. You would have to change it like this:
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="image1.png">Mercedes-Benz A Class</option>
<option value="image2.png">Mercedes-Benz C Class</option>
</select>
<button id="btn">submit</button>
</label>
<div class="container">
<img hidden src="" id="container-img" />
</div>
Add this div element.
<div id="container"></div>
Change container variable.
let container = document.getElementById('container');
Add innerHTML method before your if statement.
container.innerHTML=""; //<-------------- This will clear your div before appending your new image
if (value === 'mba') { //Note: I have not changed the if statement
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}

Get selected option from HTML into JavaScript and using If statements to create numeric variables

I am trying to use my select in HTML, bring in the values, then depending on the value, assign a different value to a variable. It's for an order form that will eventually give an updated price list based on what options the customer selects.
The logic goes as follows:
select an option
the option's value is assigned to a variable
based on the value, a numeric value is then assigned to that variable using a conditional statement
At this point I can get it to return the initial value, but once I invoke the conditional statement, it won't return anything.
I'm not receiving any errors, so I am just a little bit confused.
function fn1() {
let cpu = document.getElementById("cpuOption").value;
return cpu;
cpuPrice = 0;
if (cpu == cpu_1) {
cpuPrice = 200;
} else if (cpu == cpu_2) {
cpuPrice = 300;
} else {
cpuPrice = 400;
}
document.getElementById("test").innerHTML = cpuPrice;
}
<form>
<label for="cpuOption">Desired CPU Configuration</label>
<br>
<select id="cpuOption" onchange="fn1()">
<option value="none" selected>select</option>
<option value="cpu_1">cpu-1</option>
<option value="cpu_2">cpu-2</option>
<option value="cpu_3">cpu-3</option>
</select>
</form>
<h2>Check it out!</h2>
<button onclick="fn1()">Click me</button>
<div id="test"></div>
The first error, as #clod9353 mentioned, is that you return early inside your fn1() function. Code after a return won't get executed.
The second error is that you compare the select value to non-existing variables. Variables like cpu_1 and cpu_2 don't exist and you should compare the value to strings like "cpu_2".
The code below should work as expected:
function fn1() {
let cpu = document.getElementById("cpuOption").value;
let cpuPrice = 0;
if (cpu === 'cpu_1') {
cpuPrice = 200;
} else if (cpu === 'cpu_2') {
cpuPrice = 300;
} else {
cpuPrice = 400;
}
document.getElementById("test").innerHTML = cpuPrice;
}
<form>
<label for="cpuOption">Desired CPU Configuration</label>
<select id="cpuOption" onchange="fn1()">
<option value="none" selected>select</option>
<option value="cpu_1">cpu-1</option>
<option value="cpu_2">cpu-2</option>
<option value="cpu_3">cpu-3</option>
</select>
</form>
<h2>Check it out!</h2>
<button onclick="fn1()">Click me</button>
<div id="test"></div>
I think this might help. Tell me if it does. This code has some unnecessary pieces of code.
<body>
<form>
<label for="cpuOption">Desired CPU Configuration</label>
<br>
<select id="cpuOption">
<option value="none" selected>select</option>
<option id = "cpu_1"value="cpu_1">cpu-1</option>
<option id ="cpu_2" value="cpu_2">cpu-2</option>
<option id ="cpu_3"value="cpu_3">cpu-3</option>
</select>
<br><br>
</form>
<button onclick="fn1()">Click me</button>
<script>
function fn1() {
let cpu = document.getElementById("cpuOption").value;
var cpu_1 = document.getElementById("cpu_1").value
var cpu_2 = document.getElementById("cpu_2").value
;
cpuPrice = 0;
if (cpu == cpu_1) {
cpuPrice = 200;
}
else if (cpu == cpu_2) {
cpuPrice = 300;
}
else if (cpu == cpu ) {
cpuPrice = 0;
}
else {
cpuPrice = 400;
}
document.getElementById("test").innerHTML = cpuPrice;
}
</script>
<h2>Check it out!</h2>
<div id="test"></div>
</body>

onChange function stops after one click, what code do I need to write so that it continues indefinitely? (Javascript)

change = function(event) {
let new_url;
if (event.target.value == "views") {
new_url = "images/desert.jpg";
} else if (event.target.value == "beaches") {
new_url = "images/beach-calm.jpg";
} else if (event.target.value == "party") {
new_url = "images/plane-wing.jpg";
}
let image_two = document.getElementById("image-two");
if (new_url && image_two.src.indexOf("images/second-main-image.png") != -1) {
image_two.src = new_url;
}
}
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)">
<option id="default" value="default"> </option>
<option id="views" value="views">stunning views</option>
<option id="beaches" value="beaches">glorious white beaches</option>
<option id="party" value="party">places to party</option>
</select>
I have a dropdown menu and when a different option is clicked I want an image on the page to change with it. I have managed to make it do this however only does it once and stops after that. I've added the code so far below.
Do I need to make it a while loop and if so how would I structure it? Thanks for any help
Your second function definition is replacing the first one, so you only update the image when you select beaches.
You need one function that checks for both options.
It only works one time because you only change the image when it contains images/second-main-image.png. After you've selected something from the menu, that's no longer true. You should remove that check.
And if you want to go back to the default when the user selects the default option, add a case for that.
change = function(event) {
let new_url;
if (event.target.value == "views") {
new_url = "images/desert.jpg";
} else if (event.target.value == "beaches") {
new_url = "images/beach-calm.jpg";
} else {
new_url = ("images/second-main-image.png");
}
let image_two = document.getElementById("image-two");
image_two.src = new_url;
}
<select id="select-one" class="suggestion-dropbox" name="likes" onchange="change(event)">
<option id="default" value="default"> </option>
<option id="views" value="views">stunning views</option>
<option id="beaches" value="beaches">glorious white beaches</option>
<option id="party" value="party">places to party</option>
</select>
<img id="image-two" src="images/second-main-image.png">

Form validations with js

I'm trying to do validations with js, i have an input and a select, each one has an alert under it, those alerts appear when the input's value is less than 12, and when the user leaves the select empty, and there is a disabled button at the end of the form, it gets enabled if the value of the input == 12 or the select is not null, i tried something for the input only but i can't figure out how to put the select condition in the same function, here is my code:
$('#requiredInput').keyup(function () {
if ( document.getElementById("requiredInput").value.length == 12)
{
document.getElementById("requiredAlert").style.display = 'none';
document.getElementById("disabledButton").disabled = false;
} else if ( document.getElementById("requiredInput").value.length != 12 ) {
document.getElementById("requiredAlert").style.display = 'block';
document.getElementById("disabledButton").disabled = true;
}
});
p{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="requiredInput">
<p id="requiredAlert">Please fill out this field</p>
<select id="requiredSelect">
<option>Hi</option>
</select>
<p id="requiredSelectAlert">Please select</p>
<button disabled id="disabledButton">Submit</button>
If you need to have the select with a null value selected by default, you have to add one more option in the top. You can add <option selected disabled>Select Something</option>. The disabled attribute will make it unselectable by the user after they click another option.
Then we need to add values to the options. Add an empty value in the default option we added before so it becomes <option selected disabled value="">Select Something</option>. Then, when the field change event fires, you can check the value of the select field and make the magic happen. I have updated your snippet bellow and added the above advice.
$('#requiredInput').keyup(function () {
if ( document.getElementById("requiredInput").value.length == 12)
{
document.getElementById("requiredAlert").style.display = 'none';
document.getElementById("disabledButton").disabled = false;
} else if ( document.getElementById("requiredInput").value.length != 12 ) {
document.getElementById("requiredAlert").style.display = 'block';
document.getElementById("disabledButton").disabled = true;
}
});
$('#requiredSelect').change(function () {
if ( document.getElementById("requiredSelect").value != "")
{
document.getElementById("requiredSelectAlert").style.display = 'none';
document.getElementById("disabledButton").disabled = false;
} else if ( document.getElementById("requiredSelect").value === "" ) {
document.getElementById("requiredSelectAlert").style.display = 'block';
document.getElementById("disabledButton").disabled = true;
}
});
p{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="requiredInput">
<p id="requiredAlert">Please fill out this field</p>
<select id="requiredSelect">
<option value="" disabled selected>Select something</option>
<option value="hi">Hi</option>
</select>
<p id="requiredSelectAlert">Please select</p>
<button disabled id="disabledButton">Submit</button>
This is my version of you request. Using jquery to find the :selected element and get the text into the option tag. Also in each option you can set an value and get the .val() and will works.
$('#requiredInput').keyup(function () {
if ( document.getElementById("requiredInput").value.length == 12 && $('#requiredSelect').find(":selected").text() != "default")
{
document.getElementById("requiredAlert").style.display = 'none';
document.getElementById("disabledButton").disabled = false;
} else if ( document.getElementById("requiredInput").value.length != 12 && $('#requiredSelect').find(":selected").text() == "default") {
document.getElementById("requiredAlert").style.display = 'block';
document.getElementById("disabledButton").disabled = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="requiredInput">
<p id="requiredAlert">Please fill out this field</p>
<select id="requiredSelect">
<option>default</option>
<option>hi</option>
</select>
<p id="requiredSelectAlert">Please select</p>
<button disabled id="disabledButton">Submit</button>
You could add to the condition... Something like:
$('#requiredInput').keyup(function () {
if (document.getElementById("requiredInput").value.length == 12 || document.getElementByid("requiredSelect").value != "Hi")
{
document.getElementById("requiredAlert").style.display = 'none';
document.getElementById("disabledButton").disabled = false;
} else if (document.getElementById("requiredInput").value.length != 12 && document.getElementByid("requiredSelect").value == "Hi") {
document.getElementById("requiredAlert").style.display = 'block';
document.getElementById("disabledButton").disabled = true;
}
});
and add to your htm:
<select id="requiredSelect">
<option value='Hi'>Hi</option>
<option value='op1'>option 1</option>
<option value='opN'>option N</option>
</select>
On the other hand, you are using jQuery so you could change you code to:
$('#requiredInput').keyup(function () {
if ($("#requiredInput").val().length == 12 || $("#requiredSelect").val() != "Hi")
{
$("#requiredAlert").css("display" : "none");
$("#disabledButton")prop("disabled", false);
} else if ($("#requiredInput").val().length != 12 && $("#requiredSelect").val() == "Hi") {
$("#requiredAlert")css("display" : 'block');
$("#disabledButton")prop("disabled", true);
}
});

Categories