HTML SELECT JS onchange() disable comment box - javascript

This may be an absurdly easy question, but I'm new to JS.
I would like to have a SELECT box allowing a person to indicate where they heard about the event they're registering for. There would be a comment box, disabled by default but if the user selects 'Other' in the SELECT option the comment box would become available.
I am aware of onchange() but I don't know how to trigger a response in the separate form element. Any help?

Probably something like this.
HTML:
<select id="menu">
<option value="0">News</option>
<option value="1">Friends</option>
<option value="2">Other</option>
</select>
<input id="comment" type="textbox" disabled="true"/>
JS:
document.getElementById('menu').addEventListener('change', function() {
if (this.value == 2) {
document.getElementById('comment').disabled = false;
} else {
document.getElementById('comment').disabled = true;
}
});
Here's a fiddle.

Probably something like this.
HTML:
<select id="IDE">
<option value="0">Xcode</option>
<option value="1">Android Studio</option>
<option value="2">Others</option>
</select>
<input id="comment_box" type="textbox" disabled="true"/>
JS:
document.getElementById('IDE').addEventListener('change', function() {
if (this.value == 2) {
document.getElementById('comment_box').disabled = false;
} else {
document.getElementById('comment_box').disabled = true;
}
});
Here's a fiddle.

Related

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;

HTML:JS:BOOTSTRAP ; validate the multiselect dropdown

In my web application we have used the twitter-bootstrap theme. I have to do client side validation for one form in my application. The form includes text fields,checkboxs and multiselect dropdowns. I can validate textfield and checkboxes but i cant validate the dropdown.
<select id="users" name="username[]" class="chzn-select span2" multiple="multiple">
<option value="sdfsd">sdfsdfs</option>
....
</select>
But during runtime the select tag is hide and they generate <li> tags.
I cant use document.getElementByID();
Please provide me the best way to do the validation.
Try this
HTML
<form action="#">
<select id="users" name="username[]" class="chzn-select span2" multiple="multiple">
<option value=""></option>
<option value="sdfsd">sdfsdfs</option>
....
</select>
<input type="submit" id="add_btn">
</form>
Script
$('#add_btn').on('click', function(e) {
if($('#users').val() == null && $('#users_chosen').is(':visible')) {
alert('You must choose division');
}
});
DEMO
OR
$(function(){
$('form').submit(function(){
var options = $('#users > option:selected');
if(options.length == 0){
alert('no value selected');
return false;
}
});
});
DEMO
//You can use Js for this
var ptype=document.getElementById('username').options[document.getElementById('username').selectIndex].value;
if(ptype=""){
document.getElementById('username').style.display='none';
alert('Please select field');
document.getElementById('username').focus();
return false;
}

Button on click w/ selected value of <select> as parameter

I am new to web development and I'm trying to do this:
I have a <select> and I want the value of the selected option to be one of the parameters of a method that is called whenever a button is clicked.
So for example:
<select id="instructorSelector">
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button onclick="sendEmail(($('#instructorSelector').val()),...,...)" type="button">Send Email</button>
The problem with this is that it doesn't seen to detect when I've actually selected someone. I'm using freemarker templates but a general response as to how I should do this would be helpful too.
Also, how could I make it so the button is not clickable (or even visible) until the user actually selects something from the <select> ?
Thanks in advance! Sorry if this is an overly simple question.
You don't need to pass anything, what you need is a proper event handler:
<select id="instructorSelector">
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button id="btn" type="button">Send Email</button>
JS
$(function() {
$('#btn').hide();
$('#instructorSelector').on('change', function() {
$('#btn').show();
});
$('#btn').on('click', function() {
var select_value = $('#instructorSelector').val();
// use the value here
});
});
I would solve it like this:
disable the button in the beginning using the proper disabled-attribute
toggle this attribute if the value of the box changes, depending on something is selected or not
store the selectors in variables, so you don't need to re-query them all the time
HTML
<select id="instructorSelector">
<option value="">Please select</option>
<option value="abrown#gmail.com">Anna Brown</option>
<option value="jdoe#gmail.com">Jane Doe</option>
</select>
<button class="send_email" type="button" disabled="disabled">Send E-mail</button>
JavaScript
// example of a selector using a class name
var button = $('button.send_email');
// example of using a selector using the id of an element
var selector = $('#instructorSelector');
selector.change(function () {
if ('' == selector.val()) {
button.attr('disabled', 'disabled');
} else {
button.removeAttr('disabled');
}
});
button.click(function(event) {
sendEmail(selector.val());
event.preventDefault();
});
Demo
Try before buy
Try to use .chage() from jQuery http://api.jquery.com/change/ to make button visible
$('#instructorSelector').change(function () {
$('#id-of-the-button').show();
});
In this chang function you can also capture values of option $(this).val()
I highly recommend that you read jQuery Event Basics
You will need to understand how you can use selectors along with events to truly leverage the power of jQuery.
I think after reading about events you will see how click and change will greatly benefits the goals you have for your page.
Simplest Way: http://jsfiddle.net/rA4VJ/
<select id="instructorSelector">
<option value='none' selected>Choose Someone</option>
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
</select>
<button id="btn" type="button">Send Email</button>
var btn = document.getElementById("btn");
var elm = document.getElementById("instructorSelector");
elm.onchange = function (e) {
if (elm.value != 'none') {
console.log(elm.value);
btn.removeAttribute('disabled');
} else {
btn.setAttribute('disabled', 'disabled');
}
}
If you are using JavaScript, you can have the property onchange on the select, that can trigger a method that could check the value and make visible the the button. Use an option to indicate that there is no selection, and if that is the one selected, hide the button.
<select id="instructorSelector" onchange="something()">
<option value='selectone'>Select one</option>
<option value='abrown#gmail.com'>Anna Brown</option>
<option value='jdoe#gmail.com'>Jane Doe</option>
...
</select>
<button id="button" style="display:none;" onclick="sendEmail(($('instructorSelector').val()),...,...)" type="button">Send Email</button>
function something(){
if ( $('#instructorSelector').val()!='selectone' ) {
document.getElementById("button").style.display = 'block';
}
else{
document.getElementById("button").style.display = 'none';
}
}

Enable / Disable submit button on a dropkick enabled form?

I have a form styled with jQuery's Dropkick however I'm unable enable / disable a submit button once the forms get the style. The JS validation works as expected without Dropkick.
The HTML:
<form method="get" id="dropkickform" action="">
<select id="min" class="list">
<option selected="selected" value="">Selection 1</option>
<option value="1">100</option>
<option value="2">200</option>
</select>
<select id="max" class="list">
<option selected="selected" value="">Selection 2</option>
<option value="1">500</option>
<option value="2">600</option>
</select>
<input type="submit" value="Submit"/>
</form>
The JS:
$('.list').dropkick();
$(document).ready(function () {
$form = $('#dropkickform');
$form.find(':input[type="submit"]').prop('disabled', true);
$form.find(':input').change(function () {
var disable = false;
$form.find(':input').not('[type="submit"]').each(function (i, el) {
if ($.trim(el.value) === '') {
disable = true;
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/L3FCV/
From what I can see once you apply dropkick it will not update the selects behind the scenes so your validation will not work because of that (the selects have the initial option selected all the time, have a look in firebug/chrome web inspector to see it).
I've been able to get close with http://jsfiddle.net/Qguh5/ but it does break sometimes.
I used:
$('.list').dropkick({
change: function(value, label){
var disable = true;
$('.dk_option_current > a').each(function(){
if($(this).data('dk-dropdown-value')){
disable = false;
} else {
disable = true;
}
});
$form.find(':input[type="submit"]').prop('disabled',disable);
}
});
The change event is mentioned on the dropkick page.
I suggest you give http://uniformjs.com a try if you want custom looking forms. It might not be as pretty as dropkick but it is a lot easier to use in your scenario.

On select javascript not working with pull down?

I am new to javascript.
I have a function I modifed that when a user selects "Yes" from a pull down menu it creates 3 text boxes in a div area.
Here is my form pull down code:
<select name="dosage" id="dosage" onchange="function dosage(sel)">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<div id="dosagearea"></div>
This is the javascript I modified which originally created a message box to the user when they selected something.
function dosage(sel)
{
if(sel.options.selectedIndex == 0)
{
return false;
}
else if(sel.options.selectedIndex == 'Yes')
{
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='dosage_emitted';
document.getElementById('dosagearea').appendChild(x);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='dosage_absorbed';
document.getElementById('dosagearea').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='dosage_period';
document.getElementById('dosagearea').appendChild(x)
}
}
I checked with firebug and no JS errors being returned, I think my function is not being called the right way.
Thanks
The value of the onchange property is basically the name of a function or some JavaScript. If you want to call your function with the select element as a parameter, you need to do
<select name="dosage" id="dosage" onchange="dosage(this)">
Note that this isn't the recommended way to do things as it couples your HTML with your JS. Instead, try adding the event directly in JS, like so
window.onload = function() {
document.getElementById("dosage").onchange = dosage;
function dosasage(event) {
var sel = event.currentTarget;
}
}
try the following: onchange="dosage(this)"
it's better to have the fields already in html with display:none either on the inputs or the placeholder. and toggle to display:block when yes is selected. Also, you need to change the event listener to onchange="dosage(this)"
or make it like this
<select name="dosage" id="dosage" onchange="document.getElementById('dosagearea').style.display = this.options.selectedIndex ? 'block' : 'none'">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<div id="dosagearea" style="display:none">
<input type="text" name="dosage_emitted" />
<input type="text" name="dosage_absorbed" />
<input type="text" name="dosage_period" />
</div>
here it is in action http://jsfiddle.net/t4cy7/

Categories

Resources