Make textbox required if a certain value is selected in dropdown box - javascript

On a form, I have the following required drop down box:
<select id="SelectBox" name="SelectBox" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
I also have the following textbox:
<input type="text" name="textbox" id="textbox">
I am trying to make the textbox required only if val4 is selected from the dropdown box using the required attribute (red border around textbox). I have done this with a radio button group, but need to do the same with this dropdown box.
Any help would be greatly appreciated. Thanks.

This should work to make text input attribute required and add some red border if you select the val4 option from the select box only.
var select = document.getElementById("SelectBox");
var textBoxElement = document.getElementById("textbox");
select.onchange = function(){
var selectedString = select.options[select.selectedIndex].value;
if(selectedString == 'val4'){
textBoxElement.required = true;
textBoxElement.style.border="1px solid red";
}else{
textBoxElement.required = false;
textBoxElement.style.border="";
}
}
See working fiddle : https://jsfiddle.net/nwk1tkb7/5/

One approach I'd suggest is the following:
// use of a named function, to be called via Elememt.addEventListener:
function elementRequiredIf(event) {
// 'this' will be the <select> element in this example, however
// the 'this' is automatically passed from Element.addEventListener
// (as is the 'event' object, though we don't use that here):
var changed = this,
// here we find the conditionally-required element, using
// the id of the element stored in the custom data-* attribute
// of the <select> element, here we retrieve that attribute-
// value from the dataset object, stored as a property of the
// Element:
requiredElement = document.getElementById(changed.dataset.required_elem_id),
// as above, we use the same approach to retrieve the
// value that makes the other element required:
ifRequiredValueIs = changed.dataset.required_if_value;
// here we set the required property of the element to
// true (if the <select> value is equal to the required
// value, or false if they are unequal:
requiredElement.required = changed.value === ifRequiredValueIs;
}
// here we find the <select> element via its id,
// and bind an event-listener for the 'change' event,
// which, upon a change event being fired, calls the
// named function (note the deliberate, required, lack
// of parentheses following the function name):
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
function elementRequiredIf() {
var changed = this,
requiredElement = document.getElementById(changed.dataset.required_elem_id),
ifRequiredValueIs = changed.dataset.required_if_value;
requiredElement.required = changed.value === ifRequiredValueIs;
}
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
input:required {
box-shadow: 0 0 0.5em #f00;
}
<form>
<select id="SelectBox" name="SelectBox" data-required_elem_id="textbox" data-required_if_value="val4" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
<input type="text" name="textbox" id="textbox">
<button type="submit">Submit</button>
</form>
JS Fiddle demo.
References:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.

Related

Determine the Selected Index number of a drop down menu?

I'm trying to make sure that the user is not selecting the default of a drop down method by determining the index number selected. It seems to be only returning false even though I believe the code is correct... So far I have the code listed below but its not working, any ideas?
<p id="Gender">
<label for="Gender">Gender: </label>
<select required>
<option disabled selected value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</p>
function validate1() {
valCheck3 = true;
var dropD1 = document.getElementById("Gender");
var resultSelect = dropDown1(dropD1);
var image3 = getImage(Boolean(resultSelect), "gender");
var labelGender = getNotification3(Boolean(resultSelect), "gender");
document.getElementById("Gender").appendChild(image3);
document.getElementById("Gender").appendChild(labelGender);
}
function dropDown1(select){
if(select.selectedIndex > 0){
return true;
}
valCheck3 = false;
return false;
}
EDIT: I added the HTML I used the setting to make the answer required, the problem is I need to have a button that checks whether the answer has been selected to insert an image next to the box. So in this case I figured I could determine the selected index number of the drop down so that I could determin
You can add the required attribute to the select element, then add some value attribute to each option except for the first one (use value without the value itself i.e. value="1")
Then you can just use select.checkValidity(), which returns true or false.
I'm trying to make sure that the user is not selecting the default of a drop down
You can just add disabled attribute to the <option> and also make it default. If the user opens the dropdown, the default option can not be clicked anymore and the user has to choose an onther option.
Example:
<form action="">
<select required>
<option disabled selected value>Default option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="submit">
</form>

Loop through select from fields and validate

Im trying to loop through multiple text and select boxes in a form and validate they have been answered.
I have used the following code to loop through the text boxes but can work out how to do something similar on the select boxes.
<form name="Form1"></form>
<label>Question 1</lable>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>';
</form>
<script>
(function (){
$('#Go').on('click', function(e){
e.preventDefault();
genericValidationText('form[name="Form1"]');
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationText (formName) {
document.forms.noValidate = true;
var notValid;
// PERFORM GENERIC CHECKS
// INPUT form fields
$(formName + ' *').filter(':input').each(function(){
var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
performValidation(formElement);
});
function performValidation(formElement){
if ($(formElement).hasClass('required')) {
notValid = false;
if (!($.trim($(formElement).val()))){
notValid = true;
};
if (notValid === true) {
showErrorMessage(formElement);
};
};
}
}
function genericValidationSelect (formName) {
?????
}
</script>
You can validate <select> elements in much that same way as <input /> elements, by examining the result of the select element's .val().
Something to keep in mind is that the <select> will have a value by default (that corresponds to the <option> that is initially visible to the user in the browser). This will in effect cause validation on the <select> to pass (even when a selection option hasn't been explicitly picked by the user).
To address this, consider adding a default <option> to the <select> like this:
<option selected disabled>Please select something</option>
Adding this option means that validation on the <select> will fail until the user has actually engaged with the <select> by picking a valid option (after which, validation on the select will pass):
(function() {
/* Consider using submit on form, rather than a click event
listener on the Go button */
$('form[name="Form1"]').submit(function(e) {
e.preventDefault();
/* Exclude call to genericValidationText() for
this snippet to simplify it
genericValidationText('form[name="Form1"]');
*/
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationSelect(formName) {
let notValid = false;
/* Iterate each select in the form */
$('select', formName).each(function() {
/* Check value in similar way. If null value,
then consider the select invalid */
var selectedOption = $(this).val();
if (selectedOption === null) {
notValid = true;
}
});
if(notValid) {
alert('Please select an option');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
<!-- Fixed : typo -->
<label>Question 1</label>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<!-- Added default "no value option" to demonstrate validation -->
<option selected disabled>Please select something</option>
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>
</form>
Hope this helps!
The following should work:
const changeEventHandler = e => {
const value = e.target.options[e.target.selectedIndex].value;
console.log(value); //Validate value...
}
const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;

How can I put the selected option of a <select> from a dynamically generated form into an input field

I have a form, where you can dynamically add steps by clicking a button. Each step contains different input fields. One step has a ,which is filled with some options like this.
<select id="zutatenListe" name="zutatenListe" onchange="updateZutaten()">
<option value="0">Tomate</option>
<option value="1">Brot</option>
</select>
It is possible that there are multiple of it, all with the same id and name.
Next to the select, there is always an input field like this:
<input id="selectedZutat" type="text" value="" name="wiegen_zutat[]">
What I want to make is that when you change the selected option, your selected option will be shown only in the input element next to the changed select. It works for the first one, but for all other selects, it doesn't. My code is this:
function updateZutaten(){
var eingabe;
eingabe = $("#zutatenListe option:selected").text();
$( "#selectedZutat").val(eingabe);
}
My guess is that it only works for the first select element, because the other select elements have the same id. Has anyone an idea how to take care of this problem?
Please don't get confused by the German names, but I'm from Germany.
Thank you everyone :)
Identifiers must be unique and as you are using jquery bind event using it.
Add a common class to target the <select> element, this will help you select them using Class Selector (".class") and bind event using it, then you can use .next() target the next <input> element.
Here in exmple I have added zutatenListe class to <select> element.
$(function() {
$(document).on('change', '.zutatenListe', function() {
var text = $(this).find("option:selected").text();
$(this).next(".selectedZutat").val(text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select class="zutatenListe" name="zutatenListe">
<option value="0">Tomate</option>
<option value="1">Brot</option>
</select>
<input class="selectedZutat" type="text" value="" name="wiegen_zutat[]">
</div>
<div>
<select class="zutatenListe" name="zutatenListe">
<option value="0">Tomate</option>
<option value="1">Brot</option>
</select>
<input class="selectedZutat" type="text" value="" name="wiegen_zutat[]">
</div>
Maybe work on the change() event?
$("#zutatenListe").change( function () {
var eingabe;
eingabe = $("#zutatenListe option:selected").text();
$( "#selectedZutat").val(eingabe);
})
So it will always set the selected option when the change event fires?
Use unique ID attributes for each set of input and selects. HTML and Jquery require this.
HTML4 Spec
HTML5 Spec
Here's a way to do it in JavaScript.
function updateZutaten(element) {
var option = element.options[element.selectedIndex];
var parent = element.parentElement;
var textBox = parent.getElementsByTagName("input")[0];
textBox.value = option.text;
}
.formItems {
list-style-type:none;
padding:0;
margin:0;
}
.formItems li {
border-bottom:1px solid #EEE;
padding: 10px 0;
}
<form id="myForm">
<ul class='formItems'>
<li>
<select id="zutatenListe"
name="zutatenListe"
onchange="updateZutaten(this)">
<option value="">--Choose--</option>
<option value="0">Tomate</option>
<option value="1">Brot</option>
</select>
<input id="selectedZutat"
type="text" value=""
name="wiegen_zutat[]"
/>
</li>
<li>
<select id="zutatenListe"
name="zutatenListe"
onchange="updateZutaten(this)">
<option value="">--Choose--</option>
<option value="0">Tomate</option>
<option value="1">Brot</option>
</select>
<input id="selectedZutat"
type="text" value=""
name="wiegen_zutat[]"
/>
</li>
</ul>
</form>

How to set value of select box in page before show in jquery mobile?

How to set value of select box in page before show in jquery mobile. i have given normally as
document.getElementById('RA_IF_inpVisible').value = visible;
In page it is given as follows
<div data-role="fieldcontain">
<label for="name">Visibility:</label>
<select name="RA_IF_inpVisible" id="RA_IF_inpVisible">
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</fieldset>
If the variable is "1" also it is showing only "0" as default value.
You need to use .val() to set value and then refresh selectmenu to apply changes.
$(document).on("pagecontainerbeforeshow", function (e, data) {
if ( data.toPage[0].id == "PageID" ) {
$("#RA_IF_inpVisible", data.toPage).val(1).selectmenu("refresh");
}
});
Demo
If i got it right, this should help you:
var e = document.getElementById('RA_IF_inpVisible');
//Value is the Value of your Page, so you need to set it in some way ;)
var value = 1;
var i=0;
for (i;i<e.options.length; i++){
if(e.options[i].value==value){
e.options[i].selected = true;
}
}
e.style.visibility = "visible";
<div data-role="fieldcontain">
<label for="name">Visibility:</label>
<select name="RA_IF_inpVisible" id="RA_IF_inpVisible">
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
This Javascript should circle through all elements and compare your value which should be set to the values of the options. If they match, the options will be selected.
Afterwards your select will be visible.

Programmatically select dropdown option

Is it possible to fire option click programmatically with pure Javascript?
HTML:
<select id="racetype" class="select-menu" name="race-type">
<option value="value" class="select-option js-select-option racetype-all" data-filter-value=".js-find-race-item">Race Types</option>
<option value="value" class="select-option js-select-option racetype-sprint" data-filter-value=".js-type-sprint">Sprint</option>
<option value="value" class="select-option js-select-option racetype-super" data-filter-value=".js-type-super">Super</option>
<option value="value" class="select-option js-select-option racetype-beast" data-filter-value=".js-type-beast">Beast</option>
</select>
Click to select the second option (Sprint)
JAVASCRIPT:
function SOsprint() {
var select = document.getElementById("racetype");
select.selectedIndex = 1;
return false;
}
You don't need [0]. getElementById() returns just a single element and not a NodeList
Do this:
var select = document.getElementById("racetype");
There is no need to use [0] as document.getElementById returns a reference to the element by its ID not an array.
Use
var select = document.getElementById("racetype");
instead of
var select = document.getElementById("racetype")[0];

Categories

Resources