Calling onclick from options in a dropdown - javascript

I have created a dropdown and added a onclick="function name" to each of the options but however on selecting those options from the dropdown I am unable to get any response
This is the code that i have tried using:
<span onclick="myfunc('demo')">Sports</span>
<select name="sports">
<option value="none"></option>
<option value="cricket" onclick="myfunc('cricket')">Cricket</option>
<option value="football" onclick="myfunc('football')">Football</option>
<option value="volleyball" onclick="myfunc('volleyball')">Volleyball</option>
<option value="basketball" onclick="myfunc('basketball')">Basketball</option>
<option value="ttenis" onclick="myfunc('ttennis')">Table Tennis</option>
<option value="athletics" onclick="myfunc('atletics')">Athletics</option>
</select>
function myfunc(ft){
console.log(ft);
}
My only response is when I click the span i.e.Sports, and I get 'demo displayed in the output.

You may use change event to handle your each item. Please follow below code as your need
<select id="ddlSportsItems" name="sports">
<option value="0">None</option>
<option value="1">Cricket</option>
<option value="2">Football</option>
<option value="3">Volleyball</option>
<option value="4">Basketball</option>
<option value="5">Table Tennis</option>
<option value="6">Athletics</option>
</select>
$('#ddlSportsItems').change(function()
{
var selectedValue = parseInt(jQuery(this).val());
switch(selectedValue){
case 1:
Cricket();
break;
case 2:
Football();
break;
//etc...
default:
alert("catch default");
break;
}
});
function Cricket(){
alert("do your require stuff");
}
function Football(){
alert("do your require stuff");
}

Solution in javascript:
<select name="sports" onchange="myFunc(this)">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>
<script>
function myFunc(select){
console.log(select.value);
}
</script>

Correct way to write this would be :
function myfunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
console.log(selectedValue);
if (selectedValue === 'cricket') {
alert("Cricket");
//Write your code for cricket
}
else if (selectedValue === 'football') {
alert("Football");
}
else if (selectedValue === 'volleyball') {
alert("Volleyball");
}
else if (selectedValue === 'basketball') {
alert("BasketBall")
}
else if (selectedValue === 'ttenis') {
alert("Table Tennis");
}
else if (selectedValue === 'athletics') {
alert("Athletics");
}
}
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>

You can try this.
function myfunc() {
alert($("#selectBox").val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span>Sports:</span>
<select id="selectBox" name="sports" onchange="myfunc();">
<option value="none"></option>
<option value="cricket">Cricket</option>
<option value="football">Football</option>
<option value="volleyball">Volleyball</option>
<option value="basketball">Basketball</option>
<option value="ttenis">Table Tennis</option>
<option value="athletics">Athletics</option>
</select>

Related

How to disable multiple options in a select based on another select in JavaScript / Jquery

I am using Select2 Jquery plugin. I have to 2 selects tableHeader and tableBody where I can select multiple tags on each.
What I am trying to do is :
If I select an option or more in first select it/they will be disabled in the second select and vice versa, the same if I unselect an option from one select it will be enabled in other select.
What I did is :
I created an array selections where I am storing the selected options from first select then I am looping through the options of second select and check if the value exists in the array then disable it.
The logic should be correct I guess. Just couldn't find out why my options are not disabled. Any suggestions please ?
here is my code with explanation.
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') { return data; }
if (typeof data.text === 'undefined') { return null; }
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData; }
return null; }
$(".select2").select2({
matcher: matchCustom
});
//if you select or unselect option trigger this
$('#tableHeader').change(function() {
var selections = [];
// if you select an option then add the value in array
$('#tableHeader').on('select2:select', function (e) {
$('#tableHeader option:selected').each(function(){
if($(this).val())
selections.push($(this).val()); });
});
// if you unselect an option then remove from array
$('#tableHeader').on('select2:unselect', function (e) {
var unselected = e.params.data.id;
selections.splice( $.inArray(unselected, selections), 1 );
});
console.log(selections);
// loop through other select option and check if value exists in array then disable it
$('#tableBody option').each(function() {
if(jQuery.inArray($(this).val(), selections) !== -1) {
console.log($(this).val());
$('#tableBody option[value="'+ $(this).val() + '"]').prop('disabled',true); }
});
});
// do the same if you start with second select
$('#tableBody').change(function() {
var selections = [];
$('#tableBody').on('select2:select', function (e) {
$('#tableBody option:selected').each(function(){
if($(this).val())
selections.push($(this).val()); });
});
$('#tableBody').on('select2:unselect', function (e) {
var unselected = e.params.data.id;
selections.splice( $.inArray(unselected, selections), 1 );
});
console.log(selections);
$('#tableHeader option').each(function() {
if(jQuery.inArray($(this).val(), selections) !== -1) {
console.log($(this).val());
$('#tableHeader option[value="'+ $(this).val() + '"]').prop('disabled',true); }
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
Your logic while it's in the idea right, I think you're just complicating things for yourself. Just get on each change the values of each select, loop through the other select and disable one by one the ones that have the same value.
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData;
}
return null;
}
$(".select2").select2({
matcher: matchCustom
});
$('#tableHeader').change(function() {
var tableHeader = $(this).val();
var tableBody = $("#tableBody")[0];
$.each(tableBody.options, function(i, item) {
if (tableHeader.includes(item.value)) {
$(item).prop("disabled", true);
} else {
$(item).prop("disabled", false);
}
});
});
$('#tableBody').change(function() {
var tableBody = $(this).val();
var tableHeader = $("#tableHeader")[0];
$.each(tableHeader.options, function(i, item) {
if (tableBody.includes(item.value)) {
$(item).prop("disabled", true);
} else {
$(item).prop("disabled", false);
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
Just enable and disable on change event of each other, see below snipet
$(document).ready(function() {
// this function to search and show matched input
function matchCustom(params, data) {
if ($.trim(params.term) === '') { return data; }
if (typeof data.text === 'undefined') { return null; }
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += '';
return modifiedData; }
return null; }
$(".select2").select2({
matcher: matchCustom
});
var disableTableBody = function(value){
$('#tableBody option[value="'+ value +'"]').prop('disabled',true);
};
var enableTableBody = function(value){
$('#tableBody option[value="'+ value +'"]').prop('disabled',false);
};
var disableTableHeader = function(value){
$('#tableHeader option[value="'+ value +'"]').prop('disabled',true);
};
var enableTableHeader = function(value){
$('#tableHeader option[value="'+ value +'"]').prop('disabled',false);
};
$("#tableHeader").change(function(){
disableTableBody($(this).val());
});
$('#tableHeader').on("select2:unselecting", function(e){
enableTableBody($(this).val());
});
$("#tableBody").change(function(){
disableTableHeader($(this).val());
});
$('#tableBody').on("select2:unselecting", function(e){
enableTableHeader($(this).val());
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>
</select>

How to check if changes on multiple select boxes happened

I have 2 select dropdown boxes. I need to do many iterations if options were selected.
My select boxes:
<select id="time_period">
<option value="day" selected>Day</option>
option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
option value="bing">Bing</option>
</select>
I want to check if an option from just #time period was selected or an option from #site or even if options from both were selected.
Is there a way to do that?
Using onchange method
(function() {
var time_period, site;
document.getElementById("time_period").onchange = function() {
time_period = document.getElementById("time_period").value;
console.log(time_period);
checkBothSelected();
};
document.getElementById("site").onchange = function() {
site = document.getElementById("site").value;
console.log(site);
checkBothSelected();
};
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
})();
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
Using onChange property
var time_period, site;
function onSelection(e) {
if (e.id == 'time_period') {
time_period = e.value;
} else if (e.id == 'site') {
site = e.value;
}
console.log(e.value);
checkBothSelected();
}
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
<select id="time_period" onChange="onSelection(this)">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site" onChange="onSelection(this)">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
Using addEventListener
(function() {
var time_period, site;
document.getElementById('time_period').addEventListener('change', function() {
time_period = this.value;
console.log(time_period);
checkBothSelected();
});
document.getElementById('site').addEventListener('change', function() {
site = this.value;
console.log(site);
checkBothSelected();
});
function checkBothSelected() {
if (site && time_period) {
console.log('Both Selected!');
}
}
})()
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
You can get a function and check for the selected value from each of the select box
function getSelectedRadio() {
let getTimePeriod = $('#time_period').val();
let site = $('#site').val();
// when both are selected
if (getTimePeriod && site) {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="time_period">
<option value="day" selected>Day</option>
<option value="month">Month</option>
</select>
<select id="site">
<option value="google" selected>Google</option>
<option value="bing">Bing</option>
</select>
<button type='btn' onclick='getSelectedRadio()'>Click</button>

javascript - get selected value from select list

i got a form with a select form elements for month.
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
How do i use javascript to get compare the selected value. for example if i select Feb, the javascript will pop up "you selected feb"
var monthSelect = document.getElementById("month")
var opt = monthSelect.options[monthSelect.selectedIndex]
if(opt.text == "Feb")
{
alert("Feb selected")
return false
}
JSFiddle: https://jsfiddle.net/ebrnh047/
Your html:
<select id="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Try:
var month = document.getElementById("month");
month.onchange = function() {
if (month.value == "Feb") {
alert("Feb selected");
}
}
This is a way to do it with JavaScript only:
First, your HTML:
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option value="Mar">Mar</option>
<option value="Apr">Apr</option>
<option value="May">May</option>
<option value="Jun">Jun</option>
<option value="Jul">Jul</option>
<option value="Aug">Aug</option>
<option value="Sep">Sep</option>
<option value="Oct">Oct</option>
<option value="Nov">Nov</option>
<option value="Dec">Dec</option>
</select>
Then, your script:
var monthSelect = document.getElementById("month");
monthSelect.onchange = function(){
var thisValue = this.value;
alert(thisValue);
};
This is the fiddle: https://jsfiddle.net/16sn90tp/
Make sure you execute this code on document ready event( window.onload )
var monthSelect = document.getElementById("month")
monthSelect.onchange = function() {
var opt = monthSelect.options[monthSelect.selectedIndex]
if (opt.text == "Feb") {
alert("Feb selected")
}
}
<select id="month" name="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
<option>Mar
<option>Apr
<option>May
<option>Jun
<option>Jul
<option>Aug
<option>Sept
<option>Oct
<option>Nov
<option>Dec
</select>
Jan Feb
function myFunction() {
var monthSelect = document.getElementById("month").value;
if (monthSelect == "Feb") {
alert("Feb selected");
return false;
}
}
<select id="month" name="month" onchange="myFunction()">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
Hi add at first a class called "month" to all of your option tags and one class "monthList" to the select like for example this:
<select class="monthList">
<option class="month">Jan</option>
<option class="month">Feb</option>
<option class="month">Mar</option>
...
</select>
After this you need a little bit of JQuery:
$(".monthList .month").click(function(){
var selectedMonth = $(this).text();
var showText = "you selected " + selectedMonth;
alert(showText);
});
Try this, it should work.

dropdown values hide show

I have 2 dropdowns, here is the fiddle,
https://jsfiddle.net/oqsf7gjq/1/
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
When user selects "Yes" from "ddlOption" dropdown, then I want to show only 2 values (Saab and Audi) for dropdown "ddlCar" and when user selects "No", then I want to see all values for "ddlCar" dropdown.
Please suggest me any possibilities with Jquery code. Thanks!
jsFiddle example
$("#ddlOption").change(function() {
$("#ddlCar").val("").find("[value=1], [value=3]").toggle( this.value==="2" );
});
$("#ddlOption").change(function() {
$("#ddlCar").val("").find("[value=1], [value=3]").toggle( this.value==="2" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Toggle the desired option elements by checking Boolean the first select's value (this.value==="2")
Also, reset to .val("") in order to make sure the second select value is properly cleared from possible previous changes.
$('#ddlOption').change(function(){
var txt = $(this).val();
alert(txt);
if(txt==1){
$('#ddlCar option[value="1"]').hide();
$('#ddlCar option[value="3"]').hide();
}
else{
$('#ddlCar option[value="1"]').show();
$('#ddlCar option[value="3"]').show();
}
});
Fiddle
http://jsfiddle.net/ue4Cm/38/
Tested in Edge, Chrome, Firefox and Internet Explorer 11
Note that hiding and showing the options doesn't work in Edge or IE. The elements need to be really removed.
$(function() {
var $ddlCar = $("#ddlCar");
var $ddlCarOptions = $ddlCar.children("option");
$("#ddlOption").change(function() {
if ($(this).val() === "1") {
$ddlCarOptions.filter(".toggleable").attr("selected", false).remove();
} else {
$ddlCar.empty().append($ddlCarOptions);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/>
<br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option class="toggleable" value="1">Volvo</option>
<option value="2">Saab</option>
<option class="toggleable" value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Check updated fiddle
In your markup, you need to add classes to the dropdown values first
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2" class="yes">Saab</option>
<option value="3">Mercedes</option>
<option value="4" class="yes">Audi</option>
</select>
In your jquery code now
$(function() {
$("#ddlOption").change(function() {
var selectedValue = $(this).val();
if (selectedValue == 1)
{
$("#ddlCar option").hide();
$("#ddlCar option.yes").show();
}
else
{
$("#ddlCar option").show();
}
});
});
please check the code below I have made few changes to your code
<script type="text/javascript">
function populateList() {
if($("option:selected",$("#ddlOption")).val()=="1")
{
$(".val1").hide();
$(".val2").show();
}
else if($("option:selected",$("#ddlOption")).val()=="2")
{
$(".val1").show();
$(".val2").hide();
}
else
{
$(".val1").show();
$(".val2").show();
}
}
</script>
<select id="ddlOption" onchange="populateList();">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/><br/>
<select id="ddlCar">
<option value="">- Please select a name -</option>
<option value="1" class="val2">Volvo</option>
<option value="2" class="val1">Saab</option>
<option value="3" class="val2">Mercedes</option>
<option value="4" class="val1">Audi</option>
</select>
let me know if you have any doubts
You can write code as below which is also works for larger object value(300 or whatever size) and it is dynamic.
Here optionOne, optionTwo are object which is bind when Yes/No value selected
Updated Js fiddle link
$(function() {
var optionOne=[{text:"Saab",value:"2"},{text:"Audi",value:"4"}];
var optionTwo=[{text:"Volvo",value:"1"},{text:"Saab",value:"2"},{text:"Mercedes",value:"3"},{text:"Audi",value:"4"}];
$("#ddlOption").change(function() {
var selectedValue=$(this).val();
$('#ddlCar').html('');
var mySelect = $('#ddlCar').append($('<option></option>').val("").html("- Please select a name -"));
if(selectedValue==='1'){
$.each(optionOne, function(index, item) {
mySelect.append($('<option></option>').val(item.value).html(item.text));
});
}else if(selectedValue==='2'){
$.each(optionTwo, function(index, item) {
mySelect.append($('<option></option>').val(item.value).html(item.text));
});
}else{
//To Do if no selection
}
});
});
Try this: https://jsfiddle.net/oqsf7gjq/17/ not the cleanest solution but it will work cross browsing.
$(function() {
var carArray = [];
$('#ddlCar option').each(function() {
carArray.push($(this));
});
$("#ddlOption").change(function() {
if ($('#ddlOption').val() == 1) {
$('#ddlCar option').each(function() {
if ($(this).val() != 2 && $(this).val() != 4) {
$(this).remove();
}
})
} else {
$('#ddlCar option').each(function() {
$(this).remove();
})
for (var i in carArray) {
$('#ddlCar').append(carArray[i])
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlOption">
<option value="">- Select an option -</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>
<br/>
<br/>
<select id="ddlCar">
<option value="0">- Please select a name -</option>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>

Populate HTML select Tag with first input

Filling every inputs of a working hours form can be quite tedious.
Is there a way to populate every inputs from a form with the first entered value?
In the case of this Fiddle https://jsfiddle.net/az8ujh1e/1/, a first input on any of the opend date would populate the other ones (that could still be modified one by one)
and a first input on the closed dates would do the same on all the closing dates.
Code:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="col-sm-6">Opend</div>
<div class="col-sm-6">Closed</div>
<form role="form" action="#" method="POST">
<div class="col-sm-6" id="timeopen1">
<select name="timeopen1" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed1">
<select name="timeclosed1" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen2">
<select name="timeopen2" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed2">
<select name="timeclosed2" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen3">
<select name="timeopen3" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed3">
<select name="timeclosed3" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeopen4">
<select name="timeopen4" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6" id="timeclosed4">
<select name="timeclosed4" class='selectpicker' >
<option value="00:00">00:00</option>
<option value="01:00">01:00</option>
<option value="02:00">02:00</option>
<option value="03:00">03:00</option>
<option value="04:00">04:00</option>
<option value="04:00">05:00</option>
<option value="04:00">06:00</option>
</select>
</div>
<div class="col-sm-6"><br>
<button type="submit" class="btn btn-default" name="submit_time" >Submit</button>
</div>
</form>
I think the other answers are missing the point that he values should only be set automatically if the other values have not yet been set.
Add "timeopen" and "timeclosed" classes to your selectors like this:
<select name="timeopen1" class='selectpicker timeopen'>
Then the following script will change the other three values only if they are still set to "00:00".
$(function() {
$(".timeclosed, .timeopen").change(function() {
if ($(this).hasClass("timeopen")) {
autoSet(".timeopen", this);
} else {
autoSet(".timeclosed", this);
}
});
function autoSet(classSelector, t) {
if ($(classSelector + " option[value='00:00']:selected").length == 3) {
$(classSelector).val($(t).val());
}
}
});
This may cause a problem if three of them need to be set to "00:00", as it will then change the fourth one to "00:00" as well. So instead of checking the values, you may want to use global variables so that the autoSet only runs once for .timeopen and once for .timeclosed.
$(function() {
var autoSetTimeopen = true;
var autoSetTimeclosed = true;
$(".timeclosed, .timeopen").change(function() {
if ($(this).hasClass("timeopen") && autoSetTimeopen) {
autoSet(".timeopen", this);
autoSetTimeopen = false;
} else if ($(this).hasClass("timeclosed") && autoSetTimeclosed) {
autoSet(".timeclosed", this);
autoSetTimeclosed = false;
}
});
function autoSet(classSelector, t) {
if ($(classSelector + " option[value='00:00']:selected").length == 3) {
$(classSelector).val($(t).val());
}
}
});
If I correctly understood you want to display the value you selected in one field in all other fields from the same type. If so you just need to add a class "open" or "closed" to your select inputs and then proceed like this :
$('select').on('change', function() {
var value = $(this).val();
var className = 'open';
if( $(this).hasClass('closed') ) {
className = 'closed';
}
$('select.' + className).val(value);
});
Here is your Fiddle updated:
https://jsfiddle.net/az8ujh1e/2/
Here is a code which would do what you want, but it is not fully optimized right now. What I would do is, add ids to the select tags, so you can easily work with them with javascript or jquery.
$('#timeopen1 select').change(function(){
var opt = $(this).val()
for(i = 2; i<=4; i++){
$('#timeopen'+i.toString()+' select').val(opt);
}
});
$('#timeclosed1 select').change(function(){
var opt = $(this).val()
for(i = 2; i<=4; i++){
$('#timeclosed'+i.toString()+' select').val(opt);
}
});
EDIT:
Just as someone mentioned in another answer, add classes timeopen and timeclosed to your select elements, so we can easily work with them. Here is the updated code, to set all elements just the first time.
$('.selectpicker').one('change',function(event){
var opt = $(this).val()
if($(this).hasClass('timeopen'))
{
$('.timeopen').each(function(){
$(this).val(opt);
$(this).off('change');
});
}
else
{
$('.timeclosed').each(function(){
$(this).val(opt);
$(this).off('change');
});
}
});
https://jsfiddle.net/az8ujh1e/13/

Categories

Resources