I want if test2 is selected from <option> then disable all element inputs by via id element1. I try with if but dosnt work for me
function myFunction() {
if (document.getElementById("element0").value = "test2") {
document.getElementById("element1").disabled = true;
} else {
document.getElementById("element1").disabled = !0;
}
}
<select name="" id="element0">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
<div id="element1">
<label for="your-name">Name: </label>
<input type="text" name="your-name" id="" />
</div>
Generally, you should have better naming for your fields and elements. Element0 does not accurately describe what it is or does. I chose a simple name here, but please think of a better name yourself.
The function itself can be simplified. You can assign constants for the element references so that you can reuse some code. It is more readable like this and you don't have to search twice for the same element (with .getElementById).
The disabled attribute can be the outcome of the expression, since it correlates.
function myFunction() {
const dropdown = document.getElementById('dropdown');
const name = document.getElementById('name');
name.disabled = dropdown.value === 'test2';
}
<meta name="color-scheme" content="dark light" />
<body onload="myFunction()" oninput="myFunction()" style="zoom: 225%">
<select name="dropdown" id="dropdown">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
<div>
<label for="name">Name: </label>
<input type="text" name="name" id="name" />
</div>
</body>
First, the comparison operator should be "===", not "=". Secondly, you should disable the input element, not the whole div(obviously, you can't do so). So, I added the id in input. Thirdly, !0 also means true so I changed it to false
function myFunction() {
if (document.getElementById("element0").value === "test2") {
document.getElementById("element1").disabled = true;
} else {
document.getElementById("element1").disabled = false;
}
}
<select id="element0" onchange="myFunction()">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
<div>
<label for="your-name">Name: </label>
<input type="text" name="your-name" id="element1" />
</div>
So you have a couple of issues with your code.
First in your if clause you are making an assignment instead of a comparison:
= is only for assignments like: let i = 0 and == or === are used for comparison, being the latter the most used one because is does not make type inference.
Next you are disabling a div and not an input. So here's a rapid overview of my changes to your code:
<select name="myOption" id="element0">
<option value="test1">test1</option>
<option value="test2">test2</option>
</select>
<div id="element1">
<label for="your-name">Name: </label>
<input id="inputElement1" type="text" name="your-name" id="" />
</div>
</body>
function myFunction() {
if (document.getElementById("element0").value === "test2" ) {
document.getElementById("inputElement1").disabled=true;
} else {
document.getElementById("inputElement1").disabled=false;
}
}
Edit: Also changed from !0 to false on the else clause because !0 is true and probably not what you want.
Related
so I want to add some input based on the option value from the drop down that will be selected. For example, the dropdown looks like this:
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
</form>
and if the selected value is number 1 or teacher, it will display new input like this below it:
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
if you guys know how to make it, maybe you can help me with this please, either using php or js because I've been stuck with this problem for a long time.
There are many different ways to achieve what you want depends on what framwwork you are using.
For
vanilla JS: onchange to control css OR append html.
jQuery: $("#class").hide() / .show();
Angular: ngIf
vueJs: v-if / v-show
etc...
In JS you can do that by adding change event listener to the <select></select> element;
and each time the selected <option></option> changes you should make all inputs hidden then make the ones you want visible.
Example:
const select = document.getElementById('job');
select.addEventListener('change', function() {
// returns the selected option's value
const selectedOption = select.value;
// makes all inputs hidden each time the selected option changes.
document.querySelectorAll('input').forEach(input => input.style.display = "none");
// for 1st parameter, pass the option value.
// for 2nd parameter, pass an array of ids of the inputs you want to make them visible.
const setInputs = (state, id) => {
if (selectedOption === state) {
(id.sup ? id = [id] : id);
id.forEach(i => {
try {
document.getElementById(i).style.display = 'block';
} catch (error) {
console.error(`#${i} doesn't exists!`)
}
});
}
}
/* if the selected option's value is 1(Teacher),
The "student" and "class" inputs will be visible. */
setInputs('1', ['student', 'class']);
/* if the selected option's value is 2(Principal),
The "id" and "principal" inputs will be visible. */
setInputs('2', ['id', 'principal']);
/* if the selected option's value is 3(Staff),
The "name" input will be visible. */
/* if you want to show just one input,
don't need to pass an array as 2nd parameter
just pass a string */
setInputs('3', 'name');
});
/* Makes all inputs hidden by default */
input {
display: none;
}
<form action="#" method="post">
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" placeholder="Student">
<input type="Text" name="class" id="class" placeholder="class">
<input type="number" name="id" id="id" placeholder="ID">
<input type="number" name="principal" id="principal" placeholder="Principal">
<input type="Text" name="name" id="name" placeholder="Name">
</form>
before that, set the style of input is hide, then You can try onchange on select, Which is get the value of select. then proceed to show the hide input.
const job = document.getElementById("job");
let add = document.getElementsByClassName("addEx");
job.addEventListener("change",function() {
if (this.value == 1) {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'block';
}
}
else {
for (let i = 0; i < add.length; i++) {
add[i].style.display = 'none';
}
}
});
.addEx {
display:none;
}
<form action="#" method="post">
<select name="job" id="job" >
<option value="">position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<input type="number" name="student" id="student" class="addEx">
<input type="Text" name="class" id="class" class="addEx">
</form>
You can use like this:
jQuery(document).ready(function() {
$('#job').change(function() {
let job = $('#job').val();
if (job == '1') {
$('#sampleBox').show();
} else {
$('#sampleBox').hide();
}
});
});
#sampleBox {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="job" id="job">
<option selected hidden disabled>Position</option>
<option value="1">Teacher</option>
<option value="2">Principal</option>
<option value="3">Staff</option>
</select>
<div id="sampleBox">
<input type="number" name="student" id="student">
<input type="Text" name="class" id="class">
</div>
I have a form with a select, input and a function that locks my input when an option is selected.
I added a warning that inputs are locked when someone selects an option. I would like to add a function to remove this warning when someone chooses an option with value="".
It's removing my warning but for example when I choose option text 1 then text 2 my warning displays twice and then when I choose a selection with first option it removes warning but only first.
How to change it so that the warning displays only once, and not more times, and removes it after select with option first.
$(function() {
$('#stato').change(function() {
var value = $(this).val(); //Pobranie wartości z tego selecta
if (value == "") {
$('#data_consegna').prop('disabled', false);
$("#error").remove();
} else {
$('#data_consegna').prop('disabled', true);
$('#data_consegna').after('<div id="error" style="color:red;">Input locked</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
</div>
my warning displays twice
You don't check if it's already there or remove it.
removes only first
IDs must be unique, so $("#error").remove(); will only remove the first one. Use classes instead of IDs to remove multiple elements. If you only add once, this would not be an issue; just explaining why it removes only the first.
As noted in the other answer, the best solution is to simply .show()/.hide(), so I won't repeat that here.
To update your code, you can always remove the error, then add it back if needed - this isn't the most efficient as noted above.
Updated snippet:
$(function() {
$('#stato').change(function() {
var value = $(this).val(); //Pobranie wartości z tego selecta
// always remove any existing error
$("#error").remove();
if (value == "") {
$('#data_consegna').prop('disabled', false);
} else {
$('#data_consegna').prop('disabled', true);
$('#data_consegna').after('<div id="error" style="color:red;">Input locked</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
</div>
Also note, as it's using an ID, it can only be used for a single error message.
The simple way to achieve what you require is to have the notification div always contained in the DOM, but hidden, and then hide/show it depending on the state of the select, like this:
jQuery(function($) {
$('#stato').change(function() {
var value = $(this).val();
if (value == "") {
$('#data_consegna').prop('disabled', false);
$("#error").hide();
} else {
$('#data_consegna').prop('disabled', true);
$('#error').show();
}
});
});
#error {
color: red;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div class="col-4">
<label>Enabled </label>
<select name="stato" id="stato" class="form-control">
<option value="">Choose</option>
<option value="Text1">Text1</option>
<option value="Text2">Text2</option>
<option value="Text3">Text3</option>
<option value="Text4">Text4</option>
</select>
</div>
<div class="col-4">
<label>Disabled when choose option in select</label>
<input id="data_consegna" type="text" class="form-control" name="data_consegna" placeholder="Data Consegna" />
<div id="error">Input locked</div>
</div>
I'm trying to make a field mandatory if the option of a select is selected.
Here's the code to be clear :) :
<div class="value">
<h2>Are you happy ?</h2>
<select name="happiness" required>
<option value="1">Good</option>
<option value="0">To improve</option>
</select>
<br>
<textarea name="Comment4Happiness" placeholder="comment"></textarea>
</div>
So the textarea have to be mandatory if the option "To improve" is selected.
We can also fill the text area with a comment if we want. But that's not mandatory!
I already know that I have to use Javascript, but I do not know this domain...
You have to add id's to your form elements and then use them in your JavaScript to get their value and a submit button to call the function.
<div class="value">
<h2>Are you happy ?</h2>
<select id="mySelect" name="happiness" required>
<option value="1">Good</option>
<option value="0">To improve</option>
</select>
<br>
<textarea id="myTextArea" name="Comment4Happiness" placeholder="comment"></textarea>
<button type="button" onclick="myFunction()">Submit</button>
</div>
Now add a script tag to the bottom of your html
<script>
function myFunction() {
let selectValue = document.getElementById("mySelect").value;
let textAreaValue = document.getElementById("myTextArea").value;
if (selectValue === "0") {
if (textAreaValue === "") {
alert("Text Area should not be empty");
}
}
}
</script>
Press on submit button and you will see mandatory for select option To improve.
function checkHappiness(happiness) {
if(happiness.value === "0") {
document.getElementById("comment").required = true;
} else {
document.getElementById("comment").required = false;
}
}
<div class="value">
<form action="/action_page.php">
<h2>Are you happy now ?</h2>
<select name="happiness" onchange="checkHappiness(this)" required>
<option value="1">Good</option>
<option value="0" selected>To improve</option>
</select>
<br>
<textarea name="Comment4Happiness" value="value1" placeholder="comment" id="comment" ></textarea>
<input type="submit">
</div>
Try like this,
I added a id to the textarea. and added a function when the select box onChange.
function checkHappiness(happiness) {
if(happiness.value === "0") {
document.getElementById("comment").required = true;
} else {
document.getElementById("comment").required = false;
}
}
<div class="value">
<h2>Are you happy ?</h2>
<select name="happiness" onchange="checkHappiness(this)" required>
<option value="1">Good</option>
<option value="0">To improve</option>
</select>
<br>
<textarea name="Comment4Happiness" placeholder="comment" id="comment"></textarea>
</div>
Basically, I want to make a site with a button that repeatedly asks user for input. However, one of the inputs that the site asks for involves a select field and depending on the select field, have a corresponding text field appear or dissapear(values none). My javascript utilizes a for loop as the user can repeatedly press the button to add more and more select fields( and corresponding text field).
Here is jsfiddle
Below is the example code of what I'm trying to do.
HTML
<div><select class="DISPLAYTYPE" id="QBox" data-fieldtype="P">
<option value = "text">TextBox</option>
<option value = "check">CheckBox</option>
<option value = "radio">Radio</option>
</select></div>
<input type="number" min="1" value="LENGTH" class="quantumBox" id="P">
JAVASCRIPT
var textBoxList = document.getElementsByClassName("DISPLAYTYPE");
for (var i=0; i<textBoxList.length;i++){
textBoxList[i].addEventListener('change', function(){
var subParam = textBoxList[i].options[textBoxList.selectedIndex].value;
if(subParam ="text"){
//make ONLY corresponding input box appear
}else{
//make ONLY corresponding input box dissapear
}
})
};
EDIT: This is the Structure
[table id="rootPlacement"]
//insert here
[/table]
[button/] <--This will make a duplicate of invisible html and place it under invisible root
//The invisible html stuff we want to duplicate into //insert here
Given your feedback about the HTML structure in the comments, you can use the following to achieve what you are trying to. Just look into
You are trying to get the selected value inside the change event for the drop-down by using var subParam = textBoxList[i].options[textBoxList.selectedIndex].value; rather than using textBoxList[i] you can use this so that i becomes var subParam = this.options[this.selectedIndex].value.
For showing hiding the inputs you can use the function findRoot() which takes the target element object i.e ``selectand finds a parent with the class namedrootPlacement` and returns the node and then you can iterate it's children to show the selected node and hide the rest.
See a demo below
var textBoxList = document.querySelectorAll(".DISPLAYTYPE");
for (var i = 0; i < textBoxList.length; i++) {
textBoxList[i].addEventListener('change', function() {
var selectedType = this.options[this.selectedIndex].value;
let rootPlacement = findRoot(this, 'rootPlacement');
let children = rootPlacement.children;
for (var c = 0; c < children.length; c++) {
let element = children[c];
let elementType = element.type;
let isInputElement = typeof elementType !== 'undefined';
if (isInputElement) {
if (elementType == selectedType) {
element.style.display = 'inline';
} else {
element.style.display = 'none';
}
}
}
});
};
function findRoot(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
input {
display: none;
}
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox1" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="" class="quantumBox" id="P1">
<input type="checkbox" value="" class="quantumBox" id="q1">
<input type="radio" value="" class="quantumBox" id="r1">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox2" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P2">
<input type="checkbox" value="" class="quantumBox" id="q2">
<input type="radio" value="LENGTH" class="quantumBox" id="r2">
</div>
<div class="rootPlacement">
<div>
<select class="DISPLAYTYPE" id="QBox3" data-fieldtype="P">
<option value="text">TextBox</option>
<option value="checkbox">CheckBox</option>
<option value="radio">Radio</option>
</select>
</div>
<input type="text" value="LENGTH" class="quantumBox" id="P3">
<input type="checkbox" value="" class="quantumBox" id="q3">
<input type="radio" value="LENGTH" class="quantumBox" id="r3">
</div>
I am trying to create what I hope is a somewhat simple donation form. There are two options to choose from:
A drop down with a text field to enter an amount
A text field to write in an other designation along with a text field to enter an amount
I've been looking through a lot of different examples of code, but I'm not entirely sure how to search the technical name for what I need. I need to have an alert appear when nothing is entered as well as an alert when only one part of 1 or one part of 2 is entered. I know this is something I need JS for, but have zero experience with it.
I found several pages that were a little helpful with validation and alert messages for multiple fields, but I think I need to have an either/or type of alert (if that makes sense). EITHER you choose from the drop down and enter an amount OR you enter something in the "Other" text field and enter an amount.
You can see my code below. I included some JS I found and tried to modify that seemed to be closest to what I'm looking for, but with my limited knowledge of the language I know it's not correct (try not to judge me). I can get an alert message that works sometimes and not for everyone. And sometimes the alert still appears when it's filled out correctly.
I feel like my brain is fried at this point, so any help you can provide is greatly appreciated. Javascript is definitely going to the top of my "Must Learn" list after this. Thank you!
<script>
function validateForm() {
var x = document.forms["form1"]["FUND1"].value;
var x = document.forms["form1"]["FUND2"].value;
var x = document.forms["form1"]["GIFT_AMOUNT1"].value;
var x = document.forms["form1"]["GIFT_AMOUNT2"].value;
if (form1.FUND1.value == '' && form1.FUND2.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
if (form1.GIFT_AMOUNT1.value == '' && form1.GIFT_AMOUNT1.value == '') {
alert("Please select a donation designation and an amount.");
return false;
}
}
</script>
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="0.00"/>
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation"/>
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="0.00"/>
</div>
<div style="clear:both; float:left;">
<p><input type="submit" value="Continue" class="continue_button" onclick="validateAndSend()"></p>
</div>
What you are doing is ok.
To improve what you are doing you can try this:
I'm paring FUND and GIFT_AMOUNT because I guess is what you are trying to do, now the alert will show when both 1s or 2s are empty.
function validateForm() {
var form1 = document.forms['form1']
if (form1.FUND1.value === '' || form1.GIFT_AMOUNT1.value === '') {
alert("please select a donation designation and an amount 1.");
return false;
}
if (form1.FUND2.value === '' || form1.GIFT_AMOUNT2.value === '') {
alert("please select a donation designation and an amount 2.");
return false;
}
return true;
}
In your form you need to initialize your GIFT_AMOUNT inputs with value="" otherwise if you compare '0.00' with '' always will be false.
<form name="form1" method="POST" action="input.php" id="form1" onsubmit="return validateForm()" >
<div class="giving_dropdown body_copy">
<h3>Giving Opportunities</h3>
<select name="FUND1" class="drop_down" >
<option value="" selected class="body_copy"></option>
<option value="Option1" class="body_copy">Option1</option>
<option value="Option2" class="body_copy">Option2</option>
<option value="Option3" class="body_copy">Option3</option>
<option value="Option4" class="body_copy">Option4</option>
<option value="Option5" class="body_copy">Option5</option>
<option value="Option6" class="body_copy">Option6</option>
<option value="Option7" class="body_copy">Option7</option>
<option value="Option8" class="body_copy">Option8</option>
<option value="Option9" class="body_copy">Option9</option>
<option value="Option10" class="body_copy">Option10</option>
<option value="Option11" class="body_copy">Option11</option>
</select>
<input class="inputotherfund" name="GIFT_AMOUNT1" type="text" size="10" id="GIFT_AMOUNT1" value="" />
</div>
<div class="other_designation">
<h3>Other</h3>
<input name="FUND2" type="text" size="50" id="FUND2" class="inputotherfund" placeholder="Indicate where to direct donation" />
<input class="inputotherfund" name="GIFT_AMOUNT2" type="text" size="10" id="GIFT_AMOUNT2" value="" />
</div>
<div style="clear:both; float:left;">
<p>
<input type="submit" value="Continue" class="continue_button" />
</p>
</div>
</form>
There is no need to call a function in your onclick property because you are calling the submit function already to improve this behavior you can do something like this:
function submitForm() {
if (validateForm()) {
// do some stuff
}
}
and change the onsubmit property from your form
<form ... onsubmit="submitForm()">
If you are starting with javascript will be a good idea to learn how to use the console in order to debug your scripts. This article is a good point to start and as a last tip check this out.