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.
Related
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;
I have a form that starts with a select. Based on the choice of that first select (which report is chosen) I need to change the action path of which .cfm the form submits to. Will someone please assist me in how I should do this? I am open to any proper way whether is HTML, ColdFusion or jQuery (Javascript).
So starts with a select:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
If #checklistreports is chosen the form should be
<form name="generatereport" method="post" action="_checklists_queries.cfm">
But if #locationreports is chosen the form should be
<form name="generatereport" method="post" action="_location_queries.cfm">
Any help with this would be greatly appreciated.
I was trying to do in IF statement in CF but it has me stuck unfortunately with no results.
You can use a .change handler to change the action attribute of the form.
$("#reporttype").change(function() {
if ($(this).val() == "checklistreports") {
$("form[name=generatereport]").attr("action", "_checklists_queries.cfm");
} else {
$("form[name=generaterport]").attr("action", "_location_queries.cfm");
}
});
I would recommend to just indicate the action values of the form in the values of the options.
$('#reporttype').change(function(){
form_action = $(this).val();
$('form').attr('action', form_action);
$('span').text(form_action);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="_checklists_queries.cfm" >Checklist Stats</option>
<option value="_location_queries.cfm" >Location Stats</option>
</select>
<form name="generatereport" method="POST" action="#">
<p>This forms action value is <span>#</span></p>
</form>
You could always do it all with ColdFusion. It's so much simpler. Here is one approach.
formPage
<form action = "action.cfm" method="post">
<select name="pageToInclude">
<option value="locationQueries.cfm">Location</option>
rest of form.
action.cfm
<cfinclude template = "#form.pageToInclude#">
You already have an accepted answer, but I would like to propose a slightly cleaner solution to the answer you selected, as well as an alternative:
Option #1 (Inline and Clean):
// Cache the selector for better reuse.
var form = $("form[name=generatereport]");
$("#reporttype").change(function() {
var action = $(this).val() === 'checklistreports' ? '_checklists_queries.cfm' : '_location_queries.cfm';
form.attr('action', action);
});
The above option is just a more compact version of the answer you selected, but utilizes selector caching, which is good for performance.
Option #2 ('Global' Config Options):
// Cache the selector
var form = $('form[name=generatereport]');
// Now you can define the variable states for your app.
var config = {
checklistreports: {
action: '_checklists_queries.cfm'
},
locationreports: {
action: '_location_queries.cfm'
}
};
// Updating is trivial
$('#reporttype').change(function() {
var selected = $(this).val();
form.attr('action', config[selected].action);
});
This option is interesting because it lets you define all the different "states" for your components in one place, which is nice for readability and maintenance, and it makes the actual updating of components as simple as looking up the values it should have.
If the forms contains differents elements, you could hide the forms with css and with an onchange handler on the select unhide the right form.
html:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="checklistreports" >Checklist Stats</option>
<option value="locationreports" >Location Stats</option>
</select>
<form method="post" action="_location_queries.cfm" id="locationreports" style="display: none;">
<input type="text" name="location" placeholder="location">
</form>
<form method="post" action="_checklists_queries.cfm" id="checklistreports" style="display: none;">
<input type="text" name="location" placeholder="checklist">
</form>
js:
var locationReport = document.getElementById("locationreports");
var checklistReport = document.getElementById("checklistreports");
function onChangeForm(e) {
if (e.target.value === "locationreports") {
locationReport.style.display = "block";
checklistReport.style.display = 'none';
} else {
checklistReport.style.display = "block";
locationReport.style.display = "none";
}
}
document.getElementById("reporttype").onchange = onChangeForm;
jsfiddle example
I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);
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.
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';
}
}