change dropdown list to its original state - javascript

i have two dropdownlists in my view. by changing the value on the first one i can change the value on the second one. in the first run it works fine using scrip below.
but when i change the first dropdownlist to something else it will not work. i believe if i can change the second dropdownlist value and text and .... rest to its original state it will be ok.
here is my code :
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
#foreach (var item in Model)
{
<option value="#item.DepartmentTitle">#item.DepartmentTitle</option>
}
</select>
</td>
</tr>
<tr>
<td>grade</td>
<td>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>
and here is my script :
$('#ddlDepartment')
.change(function() {
debugger;
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
});
}
});
i get the erro here:
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}

You have to move getGrade() function outside. getGrade() function bind a change event handler for second select EVERYTIME you changed the first select.
Final Solution
$('#ddlgrade').change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $(this).val();
if(ddlDepartment){
$.ajax('/AdminPages/showStudents/' + ddlDepartment + '/' + grade)
.done(function(data) {
$('#lstStudents').html(data);
});
}
else{
alert("Please select department first!");
}
});
Please take a look how works your code:
$('#ddlDepartment')
.change(function() {
var ddlDepartment = $('#ddlDepartment').val();
var grade = $('#ddlgrade').val();
alert(ddlDepartment);
getGrade();
function getGrade() {
$('#ddlgrade')
.change(function() {
grade = $('#ddlgrade').val();
alert(grade);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlDepartment">
<option selected disabled>اselect department</option>
<option val="1">acb</option>
<option val="1">acfdb</option>
</select>
<select id="ddlgrade">
<option selected disabled="disabled">Select Grade</option>
<option id="id_bachelor" value="bachelor">bachelor</option>
<option id="id_Masters" value="Master">Masters</option>
<option id="Doctorate" value="Doctorate">Doctorate</option>
</select>

Related

display current alert when change select value

I have a select (dropdown) and an input. When I enter a number at input, select value change with that number:
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>
I want when change select value, display an alert:
document.getElementById('input').addEventListener('input', function (event){
let de = new Event('change');
document.getElementById('select').dispatchEvent(de);
document.getElementById('select').value = document.getElementById('input').value;
})
document.getElementById('select').addEventListener('change', function (event){
alert(document.getElementById('select').text + ' was selected.')
})
Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
How can I fix this problem?
I think this will help you.
//First Way
document.addEventListener('DOMContentLoaded', event => {
const target_input = document.querySelector('#input'),
target_select = document.querySelector('#select');
if (target_input != null) {
target_input.addEventListener('input', event => {
const { target } = event;
for (const node of [...target_select.childNodes]) {
if (node.nodeType == 1) {
if (node.value == target.value) {
node.selected = true;
alert(`${node.textContent} is selected`)
break;
}
}
}
})
}
});
// Second way
const {input, select} = {input: document.getElementById('input'), select: document.getElementById('select')};
input.addEventListener('input', function (event){
const selector = select.querySelector(`option[value="${input.value}"]`);
if (selector == null) {
alert('Does not exist!');
return '';
}
selector.selected = true;
select.dispatchEvent(new Event('change'));
})
select.addEventListener('change', function (event){
alert(select.value + ' was selected.')
})
<input id="input" type="text" name="selectChanger">
<select id="select">
<option value="" selected></option>
<option value="0">floor 0</option>
<option value="1">floor 1</option>
<option value="2">floor 2</option>
</select>
Now when input number 0 , display was selected, and then input number 1 display floor 0 was selected but must display floor 1 was selected.
Slightly confused, but-
Steps for detecting dropdown value change:
Get the element
Add an event listener for change
Detect the selected value
Code:
elem = document.getElementById("select")
elem.addEventListener("change", function(e) {
alert(elem.options[elem.selectedIndex].innerText + " was selected")
})

I want dropdown reset to original when second time ajax result come

On change of type and category, department should be changed.
It works for one time, but when I change category and type a second time without refresh, it does not works.
I don't want to refresh page for second time or much more time.
<select id="CATEGORY_ID">
<option value="21">desc</option>
<option value="22">short</option>
<option value="23">medium</option>
<option value="24">long</option>
</select>
<select class="bx-user-field-enum" name="UF_TYPE">
<option value="1">comp</option>
<option value="2">query</option>
<option value="3">fault</option>
</select>
<select name=UF_DEPT>
<option value="21">Volvo</option>
<option value="22">Saab</option>
<option value="23">Mercedes</option>
<option value="24">Audi</option>
</select>
JS here:
$('#CATEGORY_ID,[name=UF_TYPE]').on('change', function() {
var id = $('#CATEGORY_ID').val();
var select = $('.bx-user-field-enum').val();
if(id !=null && select !=null){
$.ajax({
type: "POST",
//dataType: 'json',
url:"ajax_dept.php",
data: {
select: select, id: id
},
success: function(msg) {
removeOptions(msg);
}
});
}
});
function removeOptions(msg) {
var cars = document.getElementsByName("UF_DEPT")[0];
var val = JSON.parse(msg);
for(var i=0; i<=cars.length; i++) {
var isFound = false;
for(var j=0;j<=i; j++) {
if(val[j] == cars[i].value) {
isFound=true;
//cars[i].style.color="red";
cars[i].style.display="block";
break;
}
}
if(!isFound) {
cars[i].style.display="none";
}
$('[name=UF_DEPT]').val(val[0]);
}
}
That is a logic issue.
I'm pretty sure that you want to remove the <options> from the cars (3rd dropdown) if they're not in the array received via ajax.
You use the <select> value, in the comparison, instead of each <option> value.
You double for loop just can lead to some errors.
The break will end the looping on first match, instead of removing them all.
I don't get what you try to acheive with the if(id !=null && select !=null){ comparison, which is always TRUE.
So I fixed your code using only one for loop and .indexOf() to check if the option value is in array.
I made some replacements in your code and commented them.
But I completely removed you double loop.
Here is a CodePen with all console logs showing.
console.clear();
$('#CATEGORY_ID, #UF_TYPE').on('change', function() {
var id = $('#CATEGORY_ID').val();
var select = $('#UF_TYPE').val();
//console.log(id+" "+select);
if(id !=null && select !=null){ // This condition is always TRUE
/*
$.ajax({
type: "POST",
//dataType: 'json',
url:"ajax_dept.php",
data: {
select: select, id: id
},
success: function(msg) {
removeOptions(msg);
}
});
*/
//Simulating Ajax response.
console.log("Ajax request!")
removeOptions('["21","23","24"]'); // I guess you receive your array as a string.
}
});
function removeOptions(msg) {
//var cars = document.getElementsByName("UF_DEPT")[0]; // You have the <select> tag here.
var cars = $("#UF_DEPT option"); // You have all <option> here.
//console.log(cars.length);
//console.log(msg);
var val = JSON.parse(msg); // Parse the string to get an array.
//console.log(val);
for(i=0; i<cars.length; i++) {
//console.log(i);
//console.log( cars.eq(i).attr("value") );
if( val.indexOf(cars.eq(i).attr("value")) == -1){
console.log("Hide "+cars.eq(i).val()+" - "+cars.eq(i).text()+" is not in the array.");
cars.eq(i).hide();
}else{
console.log("Show "+cars.eq(i).val()+" - "+cars.eq(i).text()+" is in the array.");
cars.eq(i).show();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="CATEGORY_ID">
<option value="21">desc</option>
<option value="22">short</option>
<option value="23">medium</option>
<option value="24">long</option>
</select>
<select id="UF_TYPE" class="bx-user-field-enum" name="UF_TYPE">
<option value="1">comp</option>
<option value="2">query</option>
<option value="3">fault</option>
</select>
<select id="UF_DEPT" name=UF_DEPT>
<option value="21">Volvo</option>
<option value="22">Saab</option>
<option value="23">Mercedes</option>
<option value="24">Audi</option>
</select>
I have modified your code and separated the function bound to the change events of the CATEGORY_ID and UF_TYPE dropdowns. Moreover, I have created a separate function to handle updation of department dropdown options. Below id the modified code:
HTML:
<select id="CATEGORY_ID">
<option value="21">desc</option>
<option value="22">short</option>
<option value="23">medium</option>
<option value="24">long</option>
</select>
<!-- Note: I have added Id to this select element -->
<select id="UF_TYPE" class="bx-user-field-enum" name="UF_TYPE">
<option value="1">comp</option>
<option value="2">query</option>
<option value="3">fault</option>
</select>
<select name=UF_DEPT>
<option value="21">Volvo</option>
<option value="22">Saab</option>
<option value="23">Mercedes</option>
<option value="24">Audi</option>
</select>
JS:
//A specialized function to update the department options
function update_department_options()
{
var id = $('#CATEGORY_ID').val();
var select = $('#UF_TYPE').val();
if(id !=null && select !=null) {
$.ajax({
type: "POST",
//dataType: 'json',
url:"ajax_dept.php",
data: {
select: select, id: id
},
success: function(msg) {
removeOptions(msg);
}
});
}
}
$('#UF_TYPE').on('change', function() {
update_department_options();
});
$('#CATEGORY_ID').on('change', function() {
update_department_options();
});
function removeOptions(msg) {
var cars = document.getElementsByName("UF_DEPT")[0];
var val = JSON.parse(msg);
for(var i=0; i<=cars.length; i++) {
var isFound = false;
for(var j=0;j<=i; j++) {
if(val[j] == cars[i].value) {
isFound=true;
//cars[i].style.color="red";
cars[i].style.display="block";
break;
}
}
if(!isFound) {
cars[i].style.display="none";
}
$('[name=UF_DEPT]').val(val[0]);
}
}

select option value jquery

i have a bit of problem to deal with the option value in jquery. which i have 2 kind of select and one of theme contain an array. some how i dont know how to compared them.
example:
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
script:
$(function(){
var $article = $('#article > option').each(function(){
//var $v = $(this).val();
//console.log($v);
return $(this).val();
});
$('#categorie').on('change', function(){
var $e = $(this).val();
console.log($e);
if($e == $article){
// here should be the value from the article was choosed from category
}else{
console.log('there are no entries')
}
});
})
but i dont know how to compare theme properly. and it should be if #category [1,2] selected then the #article 1 and 2 only shown in option and the other should be hidden. any kind of idea or suggestion thank you very much. best regard.
You can use something like that. It works for me.
Here is html.
<select id="category">
<option value="[1,2]"> category fruit</option>
<option value="[3,4]"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
And here is jquery.
$(document).ready(function(){
function checkData(value){
var $e = value;
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
}
$('#category').change(function(){
checkData($(this).val());
});
checkData($('#category').val());
});
I think that may help you.
Thanks
First of all there is a typo categorie. It should be category
Try this
var opts = [];
$('#article > option').each(function(){
opts.push($(this).val());
});
console.log(opts)
$('#category').on('change', function(){
var $e = $(this).val();
var present = false;
$(opts).each(function(i,v){
if($e[1]==v){
present= true;
console.log($e[1])
}
});
if(!present){
console.log('there are no entries')
}
});
Demo
You need to get the select value [1,2], then use JSON.parse to make that and array. Then you can search it.
var $article = [];
$(function() {
$article = $('#article > option').map(function() {
return parseInt(this.value);
}).get();
console.log($article);
$('#category').on('change', function() {
var $e = JSON.parse(this.value);
console.log($e);
valid = false;
$.each($e, function(i, val){
valid = valid || $.inArray(val, $article) != -1;
});
if (valid)
alert('Exists' + $e.join())
else
console.log('there are no entries')
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="category">
<option value="[1,2]">category fruit</option>
<option value="[3,4]">category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
try this:
if($e.indexOf($article)!=-1){
}else{
console.log('there are no entries')
}
Try this option, working example jsfiddle
$('#categorie').on('change', function(){
var $e = $(this).val();
$('#article > option').each(function(index, item) {
if ($e.indexOf($(item).val()) === -1) {
$(item).hide();
} else {
$(item).show();
}
});
});
The value inside first select element is not an array, it just a string, remove bracket and leave only number with comma separated like following :
HTML
<select id="category">
<option value="1,2"> category fruit</option>
<option value="3,4"> category vegies</option>
</select>
<select id="article">
<option value="">chose</option>
<option value="1">banana</option>
<option value="2">mango</option>
<option value="3">letus</option>
<option value="4">spinach</option>
</select>
Js
(first option)
// use this
$('#category').change(function(){
var cat = $( this ).val().split(',');
$('#article option').hide()
$.each(cat,function(i,e){
$('#article option[value="'+e+'"]').show()
})
});
(second option)
//or use this : filter out only matched element
var cacheElem = $('#article option').detach();
$('#category').change(function(){
$('#article option').remove();
var cat = $( this ).val().split(',');
var h = cacheElem.filter(function(){
return $.inArray(this.value, cat) !== -1 && this
});
$('#article').append(h)
});
DEMO
I'm not sure of your flexibility to change the category option value attribute but I took the liberty to take another approach to your issue.
I created an object with a list of possible items to display.
The select id="category" options value is the name of the list of items I want to display.
When the category changes I update the article select with only the list of items I want to show.
<select id="category">
<option value="fruits"> category fruit</option>
<option value="vegies"> category vegies</option>
</select>
<select id="article">
<option value="1">banana</option>
<option value="2">mango</option>
</select>
as for the JavaScript
$(function(){
var items = {
fruits: ["banana", "mango"],
vegies: ["letus", "spinash"]
};
var current = items[0];
var updateOptions = function(cat_in) {
current = cat_in;
output = "";
for(var i = 0; i<items[cat_in].length; i++) {
output += '<option value="'+i+'">'+items[cat_in][i]+'</option>';
}
return output;
};
$('#category').on('change', function(){
var $e = $(this).val();
if($e == current) return;
var options = updateOptions($e);
$("#article").empty().append(options);
});
});
Here is a live example: https://jsfiddle.net/marioandrade/mkt16n1g/1/
Seems pretty simple:
$('#category').on('change', function() {
var currentCategory = $(this).val();
// reset and show/hide group items
$('#article').val("").find('option').each(function(index) {
$(this).toggle(!(currentCategory.indexOf($(this).val()) === -1));
});
}).triggerHandler('change');

How to keep drop down menu variable by function

i have a function with 3 cases depending on the date. Now i want to display it in a drop down menu.
function get_data_date(i) {
var string;
if (i == 0) {
if(d.getUTCHours() < 3 ) {
.
.
.
.
.
string=d_date.getUTCFullYear()+""+addZero1(d_date.getUTCMonth()+1)+""+d_date.getUTCDate()+"_"+addZero1(d_date.getUTCHours());
return string;
}
I do not know how to call the function in an Option tag. Please note that the function is not complete displayed.
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>
Don't use eval, as it offers too many opportunities for Bad Things.
Instead, inspect the selected option and invoke the appropriate function. With the markup as you've presented it, it would look something like this
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
var id = e.options[e.selectedIndex].id;
// Invoke `get_data_date` with appropriate argument, based on
// the selected option. NOTE: This is not a good solution--see below for
// a better one
if (id === 'run1') {
get_data_date(0);
} else if (id === 'run2') {
get_data_date(1);
} else if (id === 'run3') {
get_data_date(2);
}
}
var selectControl = document.querySelector('select[name="run"]');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select name="run" size="1">
<option id="run1" > get_data_date(0)</option>
<option id="run2" > get_data_date(1) </option>
<option id="run3" > get_data_date(2)</option>
</select>
</form>
However, if you have control of your markup, you should consider refactoring to put the value you care about in the value attribute of your options. Then, you can directly access that value and pass it as an argument to your function.
// Ignore this, it's just here for an example
var doLog = (function() {
var logOutput = document.createElement('pre');
document.body.appendChild(logOutput);
return function doLog(msg) {
var t = document.createTextNode(msg + "\n");
logOutput.appendChild(t);
};
})();
function get_data_date(i) {
doLog('You selected ' + i);
}
function selectChangeHandler(ev) {
var e = ev.target;
// TODO: Error handling
var val = e.options[e.selectedIndex].value;
get_data_date(val);
}
var selectControl = document.getElementById('date-run-select');
selectControl.addEventListener('change', selectChangeHandler);
<form action="select.htm">
<select id="date-run-select" name="run" size="1">
<option id="run1" value="0"> get_data_date(0)</option>
<option id="run2" value="1"> get_data_date(1) </option>
<option id="run3" value="2"> get_data_date(2)</option>
</select>
</form>

Not allow duplicates in different HTML selects with the same content with javascript or JQuery

I have different selects with the same content and i want control that the user don't put the same value in two or more selects, i make this code, but i think there are some options better than this, I put here the code for share and at the same time ask if exist some better options. because i search some solution like this and i can't found.
$(function () {
function restrict_multiple(selector) {
// Here sets the current value in your alt
$(selector).each(function () {
$(this).attr("alt", $(this).val());
})
// trigger when the select change
$(selector).change(function () {
// Remove the hidden from the <option>
$(selector + " option").removeClass("hidden");
// I use thr alt attr, like an aid to maintain the actual selected value
$(this).attr("alt", $(this).val())
// Create an array with the selected options
var selected = new Array();
// Every selected option is assigned into this array
$(selector + " option:selected").each(function () {
selected.push(this.value);
})
// Apply the hidden the other select options
for (k in selected) {
if( selected[k] != "" ){
$(selector + "[alt!=" + selected[k] + "] option[value=" + selected[k] + "]").addClass("hidden")
}
}
})
// trigger to keep updated all selects
$(selector).each(function () { $(this).trigger("change"); })
}
//calling the function again sending the class
restrict_multiple(".excluyent-select");
})
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="participantes_1" id="participantes_1" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
<select name="participantes_2" id="participantes_2" class="excluyent-select" >
<option value="">Seleccionar</option>
<option value="1">111111111111111111</option>
<option value="2">222222222222222222</option>
<option value="3">333333333333333333</option>
<option value="4">444444444444444444</option>
<option value="5">555555555555555555</option>
<option value="6">666666666666666666</option>
<option value="7">777777777777777777</option>
<option value="8">888888888888888888</option>
<option value="9">999999999999999999</option>
</select><br />
Here i put the link to some example running: http://jsfiddle.net/hevercking/xdmd87se/
I changed the js code to do it this way:
$(function () {
function restrict_multiple(selector) {
$(selector).each(function () {$(this).attr("alt", $(this).val());});
$(selector).on('change', function () {
var ind = $(this).index();
var val = $(this).val();
var alt = $(this).attr('alt');
$(selector).each(function () {
$(this).find("option[value="+alt+"]").removeClass("hidden");
if($(this).index() != ind && val != "") {
$(this).find("option[value="+val+"]").addClass("hidden");
}
});
$(this).attr('alt', val);
});
}
restrict_multiple(".excluyent-select");
})
Let me know if it works correctly: http://jsfiddle.net/48zmLm7x/5/
Great! i like more your option, but the two options i discover have one problem and i don't know how to solve, if i generate the selects with one for.
for ( var i=0; i < 2; i++ ) {
$('<p><select name="grup_'+i+'" id="grup_'+i+'" class="excluyent-select")"><option value="">Seleccionar</option><option value="1">111111111111111111</option><option value="2">222222222222222222</option><option value="3">333333333333333333</option><option value="4">444444444444444444</option><option value="5">555555555555555555</option><option value="6">666666666666666666</option><option value="7">777777777777777777</option><option value="8">888888888888888888</option><option value="9">999999999999999999</option></select></p>').appendTo('#selecs');
}
$(function () {
function restrict_multiple(selector) {
$(selector).each(function () {$(this).attr("alt", $(this).val());});
$(selector).on('change', function () {
var ind = $(this).index();
var val = $(this).val();
var alt = $(this).attr('alt');
$(selector).each(function () {
$(this).find("option[value="+alt+"]").removeClass("hidden");
if($(this).index() != ind && val != "") {
$(this).find("option[value="+val+"]").addClass("hidden");
}
});
$(this).attr('alt', val);
});
}
restrict_multiple(".excluyent-select");
})
.hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="selecs">
</div>
in this case don't run http://jsfiddle.net/hevercking/t3qg45v3/
I try make with onChange but only start to remove when i change one select the second time and if i change don't apear again until remove all options in the other select, i put here the example: http://jsfiddle.net/hevercking/e4scbtre/3/

Categories