Second Select disabled if Option 1 in first Select - javascript

I have two select boxes. I need the entire second select box to be disabled until the user selects any option other than the first option in the first select box.
This is my logic but I can't quite execute it.
if
.first-select = option-1
then
.second-select .attr('disabled').
else
.second-select .removeAttr('disabled')

You could use the selectedIndex property:
var
firstSelect = document.querySelector('.first-select'),
secondSelect = document.querySelector('.second-select')
;
function changeHandler() {
secondSelect.disabled = firstSelect.selectedIndex === 0;
}
firstSelect.addEventListener('change', changeHandler);
changeHandler(); // execute the handler once on DOM ready
Or if you are using jQuery:
$('.first-select').on('change', function() {
$('.second-select').prop('disabled', this.selectedIndex === 0);
}).change(); // trigger the event once on DOM ready

You have to do something like this
$("#first_select").on("change",function(){
if(this.selectedIndex != 0){
$("#second_select").removeAttr("disabled");
// or you can do this $("#second_select").prop("disabled",false);
});

Related

How to trigger a change event only after all multiselect selections have been made

I have a multiselect dropdown element with check boxes and a change function for that element in my javascript file. But the change function is triggered every time a check box is clicked. I would like the change function to be triggered only after the user exits the select dropdown or hits 'enter' so it only runs once if a user checks five boxes instead of running five times (immediately after each new box is checked). How can I do this? Here is my current code:
html element:
<select id="vo_select_mobile_brands" multiple="multiple">
<option>Select a country</option>
</select>
javascript dynamic addition of checkbox options:
$el = $('#vo_select_mobile_brands');
$el.empty()
$.each(_vo_mobile_brand_ids_list, function(idx, mobile_brand_id) {
$el.append($("<option></option>")
.attr("value", mobile_brand_id).text(mobile_brand_id));
});
$el.multiselect('destroy')
$el.multiselect({
includeSelectAllOption: true
});
$el.multiselect()
javascript change function:
$('#vo_select_mobile_brands').change(function() {
_vo_selected_mobile_brands = [];
selected_objects = $("#vo_select_mobile_brands option:selected")
for(var i = 0; i < selected_objects.length; i++){
//do something with the selected items
}
});
You can execute your js function on a button click with button click event like
$('#ButtonID').click(function() {
_vo_selected_mobile_brands = [];
selected_objects = $("#vo_select_mobile_brands option:selected")
for(var i = 0; i < selected_objects.length; i++){
//do something with the selected items
}
});
So it will get fired only when user want to submit after selecting multiple values from dropdown.
OR
If you still need to execute it on change event of dropdown when 5 items are selected then you can get count of the selected values and fire the function if selected items are equal to 5
$('#vo_select_mobile_brands').change(function() {
var count = $("#vo_select_mobile_brands :selected").length;
if(count==5)
alert(count);
});
See fiddle : https://jsfiddle.net/4zabsa9e/7/
Maybe you are looking for a delay, so that if several changes are made within a short time, your code only executes after the last one:
var timer = null;
$('#vo_select_mobile_brands').change(function() {
clearTimeout(timer); // cancel and restart timer
timer = setTimeout(function () {
_vo_selected_mobile_brands = [];
selected_objects = $("#vo_select_mobile_brands option:selected")
for(var i = 0; i < selected_objects.length; i++){
//do something with the selected items
}
}, 1000); // after one second of idle time
});
So only trigger when the select looses focus/blur perhaps?:
$("#vo_select_mobile_brands").on('focusout blur',function(){
//will return an array of the values for the selected options
var myselectedvalues = $(this).val();
});
The focusout event is sent to an element when it, or any element
inside of it, loses focus. This is distinct from the blur event in
that it supports detecting the loss of focus from parent elements (in
other words, it supports event bubbling).
IF you manually change values via script, you can trigger the event:
$("#vo_select_mobile_brands").trigger("focusout");

Select All Checkboxes while keeping track of manual selects jquery

I've been using a simple select all script for checkboxes for a while now that looks something like this:
<span id="select">Select All</span>
with
$('#select').click(function(event) {
var $that = $(this);
$('.checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
It's fairly simple. It attaches to an onclick, loops through all the inputs with the class .checkbox and checks or unchecks them accordingly. However what I'd like to do now is make it a bit more user friendly adding the following functionality to it.
1) When the user click the link labeled "Select All" it should select all check boxes as normal, but then change the text to "Deselect All". Similarly, when the user clicks "Deselect All" the text would go back to "Select All".
2) If the users manually select all check boxes I'd like check for this scenario and update the text from Select All to Deselect All as well.
Your code is checking whether a <span> is :checked, which as far as I know is not possible. Perhaps I'm wrong, but in this answer I'll use a different approach to keeping track of that, a data attribute.
// initialize 'checked' property
$('#select').data('checked', false);
// make link control all checkboxes
$('#select').click(function(event) {
var $that = $(this);
var isChecked = ! $that.data('checked');
$that.data('checked', isChecked).html(isChecked ? 'Deselect All' : 'Select All');
$('.checkbox').prop('checked', isChecked);
});
// make checkboxes update link
$('.checkbox').change(function(event) {
var numChecked = $('.checkbox:checked').length;
if (numChecked === 0) {
$('#select').data('checked', false).html('Select All');
} else if (numChecked === $('.checkbox').length) {
$('#select').data('checked', true).html('Deselect All');
}
});
Not jquery, but here's what I'd do
var cb=document.getElementsByClassName('cb'); //get all the checkboxes
var selectAll=document.getElementById('selectAll'); //get select all button
function selectAllState(inputEle,selectAllEle){ //class to manage the states of the checkboxes
var state=1; //1 if button says select all, 0 otherwise;
var num=inputEle.length;
function allChecked(){ //see if all are checked
var x=0;
for(var i=0;i<num;i++){
if(inputEle[i].checked==true){
x+=1;
}
}
return x;
}
function handler(){ //if all checked or all unchecked, change select all button text
var y=allChecked()
if( y==num && state){
selectAllEle.innerHTML='Deselect All';
state=0;
} else if(y==0 && !state){
selectAllEle.innerHTML='Select All';
state=1;
}
}
for(var i=0;i<num;i++){
inputEle[i].addEventListener('change',handler); //listen for changes in checks
}
function checkAll(){ //function checks or unchecks all boxes
for(var i=0;i<num;i++){
inputEle[i].checked=state;
}
handler();
}
selectAll.addEventListener('click',checkAll); //listen for button click
}
var myState=new selectAllState(cb,selectAll); //instance the selectAllState class
This creates a javascript class to manage the states of all your checkboxes. It takes two arguments, the first being the array of checkboxes (which is what you get if you use getElementsByClassName), and the second being the select all button. The internal methods could be exposed using the this keyword if you want to be able to, for example, have a different part of the application select or deselect all the checkboxes.
Try breaking it down in several functions: Let's call the span toggle, as it can select and de-select all.
<span id="toggle">Select All</span>
And we'll have a function to select and de-select all of the values. No need to iterate through the list as prop sets the value for all elements
function SetAll(value){
$(".checkbox").prop("checked", value);
}
Then for the toggle button:
$("#toggle").click(function(){
if($(this).text() == "Select All"){
SetAll(true);
$(this).text("De-select All");
} else {
SetAll(false);
$(this).text("Select All");
}
});
Finally we need an onchange event for each checkbox:
$(".checkbox").change(function(){
var allCheckboxes = $(".checkbox");
var allChecked = $.grep(allCheckboxes, function(n,i){
return $(n).is(":checked");
}); //grep returns all elements in array that match criteria
var allUnchecked = $.grep(allCheckboxes, function(n,i){
return $(n)is(":checked");
},true); //invert=true returns all elements in array that do not match
// check the lengths of the arrays
if (allChecked.length == allCheckboxes.length)
$("#toggle").text("De-select All");
if (allUnchecked.length == allCheckboxes.length)
$("#toggle").text("Select All");
}):

addEventListener, "change" and option selection

I'm trying to have dynamic select list populate itself, from a single selection to start:
<select id="activitySelector">
<option value="addNew">Add New Item</option>
</select>
and then JavaScript code we have:
addEventListener("select", addActivityItem, false);
The problem is that various events don't fire when you have one item: not "change" because, the text is no different when you select that item; not "select" (as I have here), for a roughly similar reason, because I'm not really selecting anything because there's only one item. What is the event that should be fired here? It seems silly to list a blank item in my option list to fire the event, so I hope there is another solution. Or is that the best solution?
You need a click listener which calls addActivityItem if less than 2 options exist:
var activities = document.getElementById("activitySelector");
activities.addEventListener("click", function() {
var options = activities.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
addActivityItem();
}
});
activities.addEventListener("change", function() {
if(activities.value == "addNew")
{
addActivityItem();
}
});
function addActivityItem() {
// ... Code to add item here
}
A live demo is here on JSfiddle.
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus.
What you need to do is use change.
"Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
Another way to make your code understandable is :
let selector = document.getElementById("Selector");
let result = document.getElementById("result");
// when client clicked on select element
selector.addEventListener("click", () => {
// if default value is changed
selector.addEventListener("change", () => {
// if value switched by client
switch (selector.value) {
case "add":
//do somthing with , "add" value
result.innerHTML = selector.value;
break; // then take break
case "remove":
//do somthing with , "remove" value
result.innerHTML = selector.value;
break; // then take break
}
});
});
#Selector{
margin: 1rem 0;
}
<label for"Selector">chose an option:</label>
<select id="Selector" name="Selector" >
<option value="add">Add new item</option>
<option value="remove">Remove existing item</option>
</select>
<div id="result">option selected : "The default value is first option"</div>

After dynamical adding options to select box, trigger doesn't work

I have select box with with id test. I have trigger on it like:
$("#test").on('change', function() { alert('test'); })
And that works for the first time, but after I add some options to select box dynamically like:
var option = $("<option>")
.attr('value', this.value)
.attr('class', this.class)
.html(this.text);
// if id corresponds to selected id then select it
if (parseInt(this.value) == selected_id) {
option.attr('selected', 'selected');
}
// append to select
$("#test").append(option);
trigger doesn't work. What to do?
Try this:
var option = "<option value='"+this.value+"' class='"+this.class+"'>"+this.text+"</option>";
$("#test").append(option);
Instead of doing:
var option = $("<option>")
.attr('value', this.value)
.attr('class', this.class)
.html(this.text);
And then appending it.
Could you post the entire script? Or at least a more complete example?
This should do it:
$(document).on('change', '#test', function() { alert('test'); });
With the following:
var trigger = false;
if (parseInt(this.value) == selected_id) {
option.attr('selected', 'selected');
trigger = true;
}
// append to select
$("#test").append(option);
!trigger || $('#test').change();
NOTE: By just adding a selected attribute to a new option, the select element won't trigger. You have to explicitly trigger it using .change() or .trigger('change') when applicable. When a user manually selects a value, both the value is set and the change event is triggered at the same time (if the new value is not equal to the previous value).

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Categories

Resources