So I've got multiple forms with selects on a page. For each form I want the submit button to have a class of disabled until an option is selected, at which point the button should lose the disabled class (each form must work independently of the others). I can't seem to get this working using Next or Find. Here's my code:
<-- FORM ONE -->
<form>
<label for="available-countries-#variables.x#">Available Countries</label>
<select id="available-countries-#variables.x#" class="form-control available-countries-selector">
<option value="0">-- Select Country --</option>
<option value="1">Australia</option>
<option value="2">Brazil</option>
</select>
<button type="submit" class="btn btn-default disabled" role="button">Submit</a>
</form>
<-- FORM TWO -->
<form>
<label for="available-countries-#variables.x#">Available Countries</label>
<select id="available-countries-#variables.x#" class="form-control available-countries-selector">
<option value="0">-- Select Country --</option>
<option value="1">Argentina</option>
<option value="2">France</option>
</select>
<button type="submit" class="btn btn-default disabled" role="button">Submit</a>
</form>
-- JS --
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).find('btn-default').removeClass('disabled');
} else {
$(this).find('btn-default').addClass('disabled');
}
});
Any help would be appreciated
You need to look for the button in the current form. Best way to do that is using closest().
var isEnabled = $(this).val() !== '0';
$(this).closest("form").find('btn-default').toggleClass('disabled', !isEnabled);
How I would code it with event bubbling:
$(document).on("change", ".available-countries-selector", function(){
var isDisabled = $(this).val() === "0";
$(this).closest("form").find('btn-default').toggleClass('disabled', isDisabled);
});
ideally you would set document to an element that is closer to the forms.
In the JS context, the this is the <select> element. Since the btn-default is not inside the select, it will not find it with that code.
Instead you can go to the closest form parent and find it from there:
$(this).closest("form").find('btn-default').removeClass('disabled');
The submit button is not within the selector you are using so $(this).find will not work. However, you can use $(this).next() since the submit button is immediately after the select dropdown, like this:
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).next().removeClass('disabled');
} else {
$(this).next().addClass('disabled');
}
});
JSFiddle
You're closing your <button>s with a </a> and your find() is not looking for a classname (because you've excluded the dot) nor can you find a sibling. Use next([selector]) to find the next .btn-default:
$('.available-countries-selector').change(function(){
if($(this).val() !== '0'){
$(this).next('.btn-default').removeClass('disabled');
} else {
$(this).next('.btn-default').addClass('disabled');
}
});
http://jsfiddle.net/mL9h2fof/
UPDATE (thanks #TrueBlueAussie)
You could use .toggleClass to make this even simpler:
$('.available-countries-selector').change(function(){
$(this).next('.btn-default').toggleClass('disabled', $(this).val());
});
http://jsfiddle.net/mL9h2fof/1/
Related
i have a select field, where i have two options in it. If an option is selected i want to add and remove Classe from a div!
On firefox its working fine, not on chrome and safari
Here is the code:
<label for="priv-firma-select">Bestellen als</label><br />
<select id="priv-firma-select" name="firma-privat">
<option id="privat">Privatperson</option>
<option id="firma">Firma</option>
</select>
Here is the jquery for it:
$j(document).ready(function() {
$j("#firma").click(function(){
$j(".input-company").addClass("show");
$j(".leweb_button_firma").addClass("hide");
$j(".leweb_button_privat").removeClass("hide");
});
$j("#privat").click(function(){
$j(".input-company").removeClass("show");
$j(".leweb_button_privat").addClass("hide");
$j(".leweb_button_firma").removeClass("hide");
});
});
The issue is because you're adding click event handlers to option elements. This is not well supported. Instead, add a change event handler to the select and check the chosen value.
Also note that you can use toggle() with a boolean argument to show/hide the elements, instead of adding or removing classes. Try this:
var $j = jQuery.noConflict();
$j("#priv-firma-select").change(function() {
var val = $j(this).val();
$j('.input-company, .leweb_button_privat').toggle(val == 'firma');
$j('.leweb_button_firma').toggle(val != 'firma');
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-company">input-company</div>
<div class="leweb_button_firma">leweb_button_firma</div>
<div class="leweb_button_privat">leweb_button_privat</div>
<br /><br />
<label for="priv-firma-select">Bestellen als</label><br />
<select id="priv-firma-select" name="firma-privat">
<option value="privat">Privatperson</option>
<option value="firma">Firma</option>
</select>
$j(document).ready(function() {
$j("#priv-firma-select").change(function(){
if($(this).val() == "firma"){
$j(".input-company").addClass("show");
$j(".leweb_button_firma").addClass("hide");
$j(".leweb_button_privat").removeClass("hide");
}
else{
$j(".input-company").removeClass("show");
$j(".leweb_button_privat").addClass("hide");
$j(".leweb_button_firma").removeClass("hide");
}
});
});
I have a continue button with the class "options-btn" on a page (it's a multi-step booking process), with two select fields on the page. One of these dropdown select fields needs to have a value selected by the user before they can click the submit button on the page while also disabling the click event?
Each dropdown field has the default select option 0, with the other choice of "1". How can I write a function to basically say "If neither one of these options has a value of 1 selected - alert message "please select an option" and disable the button.
The two ID's associated with these select fields are:
#extra_units_7 & #extra_units_4
This is what I wrote so far, but it's not working:
jQuery(document).ready(function($) {
$(".options-btn").click(function() {
if ( $('#extra_units_7').val() === 0 || $('#extra_units_4').val() === 0 )
alert("Please select an option");
return false;
} else {
$('.options-btn').trigger('click');
}
});
I re-factored your HTML in order to enable you to feedback to the End User without being obtrusive with alert() boxes.
<!-- Use ID to attach to in JS -->
<form id="form_units" action="#" method="post">
<div>
<!-- Labels, because... well, labels. -->
<label for="extra_units_4">extra_units_4</label>
<!-- Use data-attr to identify which elements should be validated and how. This future proofs your code, and it's a good pattern to follow. -->
<select id="extra_units_4" data-validate="notempty">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<!-- Hidden element to provide feedback as it's better UX -->
<div class="fielderror">Please make a selection</div>
</div>
<div>
<label for="extra_units_7">extra_units_7</label>
<select id="extra_units_7" data-validate="notempty">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="fielderror">Please make a selection</div>
</div>
<!-- Included an input[type="text"] for fun, and because future proofing is good -->
<div>
<label for="extra_units_8">extra_units_8</label>
<input type="text" id="extra_units_8" data-validate="notempty" />
<div class="fielderror">Please make a selection</div>
</div>
<!-- There appeared to be no reason not to use an input[type="submit"] in your code. Not doing so adds a tiny amount of complexity - so I slimmed the example down. Re-factor yourself for if <button> is a requirement. -->
<input type="submit" class="options-btn" value="Submit" />
</form>
Now we have a simple JS which will capture all <input>s with data-validate="notempty".
// Make sure you're specific with your selector for your form
$('#form_units').on('submit',function(e) {
// Hide all .fielderror elements within the context of 'this' form.
// This means that the next time we submit error messages are reset
$('.fielderror', this).hide();
// Select for all 'not empty' validations
$('[data-validate="notempty"]').each(function (index, item) {
// Check if it's an input[type="text"] - future proofing your "not empty" requirements. Expand on this idea for "radio" and "checkbox" inputs if and when required.
if ($(item).attr('type') === 'text') {
// Text is empty if the length is less than one char
if ($(item).val().length < 1) {
// We've found one that is invalid so stop the from from sending
e.preventDefault();
// Show the .fielderror text that is associated with the input being validated
$(item).siblings('.fielderror').show();
}
} else {
// Selects are empty if val() is less than 1. Be warned, this is dependant on having numerical values - and assumes that zero means no answer.
if ($(item).val() < 1) {
// We've found one that is invalid so stop the from from sending
e.preventDefault();
// Show the .fielderror text that is associated with the input being validated
$(item).siblings('.fielderror').show();
}
}
})
});
Lastly, add a little CSS to hide the error messages and style them when they become shown.
.fielderror { display: none; color: red;}
jsFiddle of working example with update to HTML structure and text input - https://jsfiddle.net/likestothink/xLLvzps2/9/
jQuery(document).ready(function($) {
$(".options-btn").click(function(){
if ( $('#extra_units_7').val() === 0 && $('#extra_units_4').val() === 0 )
alert("Please select an option");
return false;
}
return true;
});
)}
You should use && instead of ||. You don't need to trigger click event again.
1st: There is an error for }); at the end of your code
2nd: use == instead of ===
3rd: no need to use $('.options-btn').trigger('click');
try this .. if you have submit button without form
jQuery(document).ready(function($) {
$(".options-btn").on('click',function() {
if( $('#extra_units_4').val() == 0 ){
alert("Please select an option in extra_units_4");
//return false;
}else if($('#extra_units_7').val() == 0 ){
alert("Please select an option in extra_units_7");
//$('.options-btn').trigger('click');
}else{
alert('extra_units_4 value = '+$('#extra_units_4').val());
alert('extra_units_7 value = '+$('#extra_units_7').val());
}
});
});
Working Demo
or this .. if you have a submit button for a form (you need to use e.preventDefault(); and window.location.href )
jQuery(document).ready(function($) {
$(".options-btn").on('click',function(e) {
e.preventDefault();
if( $('#extra_units_4').val() == 0 ){
alert("Please select an option in extra_units_4");
//return false;
}else if($('#extra_units_7').val() == 0 ){
alert("Please select an option in extra_units_7");
//$('.options-btn').trigger('click');
}else{
alert('extra_units_4 value = '+$('#extra_units_4').val());
alert('extra_units_7 value = '+$('#extra_units_7').val());
// window.location.href = "type_url_here" // change type_url_here with url you need or with the form action attribute
}
});
});
Working Demo
you want to check id the condition is respected at every change of the select an basically disable / enable the button, the code was pretty much ok but you had to perform the check at the change event. I've extracted the check function in an external one just to help redability (you missed a { indenting too much the code) and i've introduced a class on the select to perform the check better, you can use the ID's if you like.
<select class="input-select" id="extra_units_4">
<option value="0">Volvo</option>
<option value="1">Saab</option>
</select>
<select class="input-select" id="extra_units_7">
<option value="0">Volvo</option>
<option value="1">Saab</option>
</select>
<button class="options-btn" disabled="disabled">Submit</button>
<script>
jQuery(document).ready(function() {
$(".input-select").on( "change", checkSelect);
});
function checkSelect() {
if ( $('#extra_units_7').val() == '0' && $('#extra_units_4').val() == '0' ) {
$(".options-btn").attr("disabled","disabled");
alert("Please select an option");
}
else {
$(".options-btn").removeAttr('disabled'); }
}
</script>
The if contition is an AND because you are checking that both the values are 0 and the check must be performed on string because the select value is not an integer.
Here's an alternative approach, in case you plan to keep adding selects which are mutually exclusive but required (you would need to add the required-select to all of them):
});
jQuery(document).ready(function($) {
var hasSelected = function() {
return $('.required-select option:not([value="0"]):selected').length;
};
$('.required-select').change(function() {
$('.options-btn').prop('disabled', !hasSelected());
});
$('form').submit(function(e) {
if (!hasSelected()) {
alert("Please select an option");
e.preventDefault();
} else {
alert('submitted');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" onsubmit="return false;">
<select id="extra_units_7" class="required-select">
<option value="0">Select an option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="extra_units_4" class="required-select">
<option value="0">Select an option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<hr>
<button type="submit" class="options-btn" disabled="disabled">Submit</button>
</form>
I think it's overkill to validate on submit when the button is disabled, and it's not intuitive to allow submit, alert error and then disable the button. I'd take one of the two approaches in the code above (I prefer specifying in writing that the selects are required and not enabling the submit until they are selected).
Javascript
$(".show").change(function(){
if ($(this).val() == "1") {
$(".text_area").show();
}
else {
$(".text_area").hide();
}
});
I want to use this code for all element with this class but, when i select option with "value 1" that make effect to all elements. Please help. Thank you.
Here is demo Click here
use $(this).next():
$(".show").change(function () {
if ($(this).val() == "1") {
$(this).next(".text_area").show();
} else {
$(this).next(".text_area").hide();
}
});
You have to make use of keyword this. $(this) works within the event of context of your selector.
As you have class name as a selector, so you should note that it returns a collection. It means if you have more than one element then it will refer to all and this refers to the event applied on the current selector in the collection.
If you happen to change the order of the html, for example place text area before the select box, it would not work. So as an alternative for the previous answer, you can wrap your groups into a div:
<div class="container">
<select class="show">
<option value="0">NO</option>
<option value="1">YES</option>
</select>
<textarea class="form-control text_area" type="text" name="text_area" placeholder="Write something" rows="5" cols="50"></textarea>
</div>
and when you are going to display/hide the text areas, you can do:
$(this).closest('.container').find('.text_area').show();
or
$(this).closest('.container').find('.text_area').hide();
Here is a demo: http://jsfiddle.net/n1fjo6qu/13/
I have a small form.
Two select box elements and a submit button.
The select box elements collectively when selections are chosen, fire off an ajax request.
What I want to do is, disable the submit button UNTIL user has made selections from the select drop downs.
They must make a selection from BOTH select drop downs, before the Submit button is enabled.
I dont mind if the submit button is hidden until selections made.
Brief Code:
<form id="ad_form" method="post" action="">
<p>
<select id="ad_type" name="ad_type">
<option value="" selected="selected">Select premium ad type</option>
<option value="<?php echo TYPE_USER;?>">Featured Agent</option>
<option value="<?php echo TYPE_LISTING;?>">Featured Listing</option>
</select>
<label for="ad_type" class="labelStrong">Advertising Type</label>
</p>
<p>
<select id="ad_duration" name="ad_duration">
<option value="" selected="selected">Select premium ad duration</option>
<option value="weekly">Weekly</option>
<option value="fortnightly">Fortnightly</option>
<option value="monthly">Monthy</option>
</select>
<label for="ad_duration" class="labelStrong">Advertising Duration</label>
</p>
<p>
<div id="calender">
</div>
</p>
<p>
<input type="submit" name="submit" value="Submit" id="submitorder" />
</p>
</form>
Here's a demo that seems to do what you want:
http://jsfiddle.net/Yr59d/
That javascript code would go in a $(document).ready() block
$(function() {
$("#submitorder").css("visibility", "hidden");
$("#ad_form select").bind("change", function() {
if ($("#ad_type").val().length > 0 && $("#ad_duration").val().length > 0) {
$("#submitorder").css("visibility", "visible");
} else {
$("#submitorder").css("visibility", "hidden");
}
});
});
If you give all your selects a common class name (like 'required') , you can do something like this:
$('select.required').change(function() {
var total = $('select.required').length;
var selected = $('select.required option:selected').length;
$('#submitorder').attr('disabled', (selected == total));
});
This is not tested code. This documentation might help. This jquery discussion might help too.
Gah, I'll have to agree with Kon on this one - fix-now-worry-about-it-later answers have their place but an elegant solution that is simple at the same time has to be the way to go.
My solution: (with credit from a thread at: JQuery Enable / Disable Submit Button in IE7)
$('select.required').change(function() {
var total = = $('select.required').length;
var selected = $('#ad_form').find("select.required option[value!='':selected").length;
$('#submitorder').prop('disabled', (selected != total));
});
Incidentally, thanks ctcherry for demoing the code on the JSFiddle site - I've not seen that before and will make use of it in the future!
Use listeners on both select buttons for change and check whether the other is also set. If set, enable the submit button.
I have two forms and a selector.
This is my code --
<select>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<form id="pp">
<input type="text">
</form>
<form id="cc">
<input type="text">
</form>
Now if option 1 is selected i want to hide form CC. if 2 hide form PP.
How do i do it with js or jquery? thanks
Try this (using jQuery):
$("select").bind("change", function() {
if ($(this).val() == "1") {
$("#pp").show();
$("#cc").hide();
}
else if ($(this).val() == "2") {
$("#pp").hide();
$("#cc").show();
}
});
Additionally, you could hide both forms using .hide() as shown above before the user selects any option.
bind is attaching an event handler to the "change" event of the select box. This is fired when the user changes what option is selected.
Inside the handler, val is used to determine the value of the currently selected option.
show() and hide() are used on the correct forms, depending on which option was selected.
Working example: http://jsfiddle.net/andrewwhitaker/faqZg/
<script>
function Hide(val)
{
if(val==1)
{
document.getElementById('cc').style.display='none';
document.getElementById('pp').style.display='inline';
}
if(val==2)
{
document.getElementById('pp').style.display='none';
document.getElementById('cc').style.display='inline';
}
}
</script>
<select onchange="Hide(this.value);">
<option value="">Please Select</option>
<option value="1">Pay</option>
<option value="2">Goog</option>
</select>
<div id="pp">
<input type="text">
</div>
<div id="cc">
<input type="text">
</div>