Jquery combobox how to get value - javascript

I'm trying to get the value from combobox-items,
so i can give each a different function...
this is the combobox :
<select id="ComboBox" >
<option value="bios">Bioscopen </option>
<option value="dogs">HondenToiletten</option>
<option value="doctors">Huisartsen</option>
</select>
How can i see what is selected with jQuery and give them each another
function?
Thanks in advance!

var a = $("#ComboBox").val();
alert (a);
then depending of received value run corresponding function
switch(a){
case : "bios" dosomething(); break
case : "doctors" dosomething_else(); break
default: break;
}

Something (rustic) like that, see jsFiddle
If you only want it to be launched when a change event happens, you can remove the $(document).ready(....) part
function bios() {
alert("bios is selected");
}
function dogs() {
alert("dogs coming");
}
function getVal(v) {
switch(v) {
case "bios":
bios();
break;
case "dogs":
dogs();
break;
default:
alert('other');
break;
}
}
$('#ComboBox').change(function(){
getVal($(this).val());
});
$(document).ready(function() {
getVal($('#ComboBox').val());
});

I would handle this by binding on the change element of the select element, and then calling another function in the callback. So maybe something like:
$('#ComboBox').change(function() {
var selectedItem = $(this).val();
if (selectedItem === 'bios'){
// Your code here, maybe another function call etc...
} else if (selectedItem === 'dogs'){
// More code
}
// and so on and so on
});
This isn't a super graceful way to handle this, but I hope it helps.

Related

Prevent Select from changing selected option if condition is not met

I have a select box. Currently, this select box make an ajax call on change.
Now, I want to make call only when a condition is met.
So, here is my code:
$('#buildingSelect').on('change', function(){
var result = checkDirtyStatus();
//this checkDirtyStatus alert message if there is some changes on the form.
//if cancel return false, if confirm return true.
if(result === false) {
return;
}
//make ajax call
});
This prevents from making ajax call, however, this change the selected option of the select i.e, if option1 is selected at the begining and if I try to select next option then it will change the selected option to option2 then only check the status.
On searching on the internet, I got the option of focusin.
$('#buildingSelect').on('focusin', function(){
// console.log("Saving value " + $(this).val());
var result = checkDirtyStatus();
if(result === false) {
return;
}
}).on('change', function(){
g_building_id = $(this).val();
getAmenitiesDetails(g_building_id);
});
However, using this focusin options makes the alert box to appear everytime no matter either I click cancel or ok. This might be because, it call focusin again whenevr I click Ok or Cancel.
What would be the best option to check this status, and if result is false, I don't want to change the selected option as well.
Update
Answer from marked as duplicate not preventing from changing the selected option. Its making ajax call on click i.e. before checking condition.
CodePen Link
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus === true){
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
Finally, by mixing the link from Rory and idea of organizing code from some. I have find a solution for my problem. So, if anyone got stuck on the similar problem here is my solution.
$(function(){
var lastSel;
$('#buildingSelect').on('focusin', function(){
lastSel = $("#buildingSelect option:selected");
}).on('change', function(){
if(!checkDirtyStatus()) {
lastSel.prop("selected", true);
return;
}else{
//made ajax call
//$.ajax({})
}
});
});
function checkDirtyStatus(){
let dirtyStatus = getDirtyStatus();
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
return true;
}
Let us look at your function:
function checkDirtyStatus(){
dirtyStatus = true; // I assume this is only for testing
if(dirtyStatus === true){ // This can be simplified.
if (confirm("Changes you made may not be saved.")) {
return true;
}else{
return false;
}
}
}
confirm returns a Boolean that is either true or false, so you can simplify your function like this:
function checkDirtyStatus(){
dirtyStatus = true;
if(dirtyStatus){
return confirm("Changes you made may not be saved.");
}
// Notice that you do not return anything here. That means that
// the function will return undefined.
}
Your other function can be simplified like this:
$('#buildingSelect').on('change', function(){
if(!checkDirtyStatus()){
// Here you probably want to set the value of the select-element to the
// last valid state. I don't know if you have saved it somewhere.
return;
}
//make ajax call
});
I played with your codepen and you have some errors in your selectors. As I get confused by your explanation I will try to explain what you could update and how to use it in your code and I hope this is what you need to solve your problem.
First I would change your js to this:
var lastSel = $("#buildingSelect").val();
$("#buildingSelect").on("change", function(){
if ($(this).val()==="2") {
$(this).val(lastSel);
return false;
}
});
The proper way to get the value of a select box in jquery is with the .val(). In your case you selected the entire selected option element.
I store this value in the lastSel variable. Then in the change function the new value of the select list is $(this).val(). I check against this value and if it equals 2 I revert it to the value stored in the lastSel variable with this $(this).val(lastSel).
Keep in mind that the value of a select list is always a string, if you want to check against a number you must first cast it to a numeric value e.g. by using parseInt.
If you want to use the checkDirtyStatus for the check then you should only call this function in the change and pass as parameters the lastSel and the newSel like this:
$("#buildingSelect").on("change", function(){
checkDirtyStatus(lastSel, $(this).val());
});
Then you can transfer the logic from the change function into the checkDirtyStatus function and do your checks there. In this case if you wish to revert the select value instead of $(this).val(lastSel) you will do a $("#buildingSelect").val(lastSel).
I hope this helps.

How to run another event based on click event in jQuery?

I'd like to run a change event when user click a button.
$('#b1').on('click', function(){
$('#select_item').trigger('change');
});
$('#select_item').on('change', function(){
var jbyr = $(this).find('option:selected').val();
if(jbyr == 1){
alert('Option 1');
}
else if(jbyr == 2){
alert('Option 2');
}
else{
alert('Option 3');
}
});
What I am looking for is when I click button, the combobox change its option from previously 1 to 2 for example and fire the select_item change script so the alert('Option 2') is displayed.
addition:
#b1 is a button, not submitting anything. It just force changes the combobox option to option 2. When the combobox change by the button click, the combobox change event should fired. So, user not touch the combobox
This seems to be a simple case of do it the hard way. There is no reason, since you own both pieces of subscription code, to trigger any events what so ever. So don't do that, just encapsulate the change code into a new function. Also I highly recommend reading Decoupling Your HTML, CSS, and JavaScript - Philip Walton # Google Engineer.
$(document).ready(function() {
$('.js-alert').on('click', function() {
onSelectedChanged($('.js-select'));
});
$('.js-select').on('change', function() {
onSelectedChanged($(this));
});
function onSelectedChanged($element){
var jbyr = $element.find('option:selected').val();
if (jbyr == 1) {
alert('Option 1');
} else if (jbyr == 2) {
alert('Option 2');
} else {
alert('Option 3');
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="click me" class="js-alert" />
<select class="js-select">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
I'm uncertain about the coding need of triggering a change event on click...
"Cascading events" sure is not the idea of the year.
What I can say from here is you to define a function to call either on click or change of the elements you like.
So just create a named function:
myFunction(){
//Do whatever...
}
Then call myFunction() in the event handler you like:
$(element).on("click",myFunction);
or:
$(element).on("change",myFunction);
You need to set the the value of the combobox like this.
$('#b1').on('click', function () {
$('#select_item').val(2);
$('#select_item').trigger('change');
});
$('#select_item').on('change', function () {
var jbyr = $(this).find('option:selected').val();
if (jbyr == 1) {
alert('Option 1');
} else if (jbyr == 2) {
alert('Option 2');
} else {
alert('Option 3');
}
});

Change event triggering too early on select box

Here is a simplified version of my problem:
The HTML:
<select id="mySelect">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
The jQuery:
$('#mySelect').change( function() {
// do stuff
} );
The problem is that when I move my mouse cursor over the options, do stuff happens as I hover over one of the options, before I actually select the new option. How do I avoid this behaviour so that .change() is triggered only when I have finished choosing a new option in the select?
Edit 1: Further information
Apparently this code would not cause behaviour described. In the actual code the select boxes are being updated as further data is loaded via .get() and processed.
Edit 2: Actual function that updates a select box
This function is the one in my code that updates one of the select boxes after more data has loaded. The global variable padm_courses is an array of course objects, that have a code and name property used to populate the course filter select box.
function loadCourseFilter() {
var selected = '';
var sel = $('<select>').attr('id','padmCourseFilter');
$(padm_courses).each(function() {
sel.append($("<option>").attr('value',this.code).text(this.name));
});
if($('#padmCourseFilter').length) {
selected = $('#padmCourseFilter').val();
$('#padmCourseFilter').replaceWith(sel);
if(selected != '') $('#padmCourseFilter option[value="'+escape(selected)+'"]').prop('selected', true);
} else {
sel.appendTo('#padm_hub_filters');
}
$('#padmCourseFilter').change( function() {
processMCRsByCourse($('#padmCourseFilter').val());
var tables = $('.sv-datatable').DataTable();
tables.rows('.duplicate').remove().draw();
filterTheBlockFilter();
} );
}
Try changing your change event
$(document).on('change', '#mySelect', function() {
// do stuff
});
Okay, I found a solution. It seems that when triggered, the function loadCourseFilter was recreating the selectbox from scratch each time and overwriting the old one. This caused weird behaviour when hovering over one of the options.
A revised version of the function adds only new options, and does not update the filter if nothing was actually added...
function loadCourseFilter() {
var sel, output;
if($('#padmCourseFilter').length) {
var count = 0;
sel = $('padmCourseFilter');
output = [];
$(padm_courses).each(function() {
if($('#padmCourseFilter option[value="'+this.code+'"]').length == 0) {
count++;
output.push('<option value="'+this.code+'">'+this.name+'</option>');
}
});
if(count > 0) {
sel.append(output.join(''));
sortDropDownListByText('padmCourseFilter');
}
} else {
sel = $('<select>').attr('id','padmCourseFilter');
$(padm_courses).each(function() {
sel.append($("<option>").attr('value',this.code).text(this.name));
});
sel.appendTo('#padm_hub_filters');
}
$('#padmCourseFilter').change( function() {
processMCRsByCourse($('#padmCourseFilter').val());
var tables = $('.sv-datatable').DataTable();
tables.rows('.duplicate').remove().draw();
filterTheBlockFilter();
} );
}

Why is the value returned the first in my select no mather what i choose?

it is late and this is probably a very simple fix, i have seen several posts her on stackoverflow covering this, but i cant seem to get this to work right now.
To the case, i have a select with 7 options. All options have a number from 1 to 7 in their value fiels.
html
<select id="thecase" name="thecase">
<option value="1">Velg hva saken gjelder:</option>
<option value="2">Transportskade</option>
<option value="3">Stengt bestilling</option>
<option value="4">Finansiering</option>
<option value="5">Ros & ris</option>
<option value="6">Bedrift</option>
<option value="7">Annet</option>
</select>
javaScript
var hiddenOpt = jQuery("#option_other");
var target = jQuery('#thecase');
var caseVal = target.val();
hiddenOpt.hide();
target.change(function(){
alert (caseVal);
if (target == 'annet') {
hiddenOpt.show();
};
});
When i try this bit of code it returns value 1 no mather what.
Here is a fiddle: http://jsfiddle.net/Danbannan/QM2U8/
Could someone explain to me what i am missing? Thanks in advance.
put var caseVal = target.val(); inside change function. The first time the select value is 1 and that is saved in caseVal, But you need to get the value when the select value changes, henceyou need to get the target.val() inside the change function. you can also use $(this).val()
http://jsfiddle.net/QM2U8/2/
var caseVal = target.val();
You're getting the value right away, but never changing it in the .change() function
It should be
target.change(function(){
caseVal = this.value;
if (target == 'annet') {
alert (caseVal);
hiddenOpt.show();
};
});
var caseVal = target.val();
This is defined only at the onload event. Hence it is static. So you have to make it dynamic by initializing in change event.
Try this out:- http://jsfiddle.net/adiioo7/QM2U8/3/
var hiddenOpt = jQuery("#option_other");
var target = jQuery('#thecase');
hiddenOpt.hide();
target.change(function () {
var caseVal = target.val();
alert(caseVal);
if (target == 'annet') {
hiddenOpt.show();
};
});
Your caseVal is get value before event.
So you need to change like this:
target.change(function(){
caseVal = $(this).val();
alert (caseVal);
});
Actually by looking at my code.
The right answer to this is:
target.change(function(){
caseVal = this.value;
/*Not the target, the caseVal*/
if (caseVal == '7') {
alert (caseVal);
hiddenOpt.show();
};
});
Simple Fix:
var hiddenOpt = jQuery("#option_other");
var target = jQuery('#thecase');
hiddenOpt.hide();
target.change(function(){
var caseVal = target.val();
alert (caseVal);
if (target == 'annet') {
hiddenOpt.show();
};
});
Your variable caseVal was residing outside the target.change function, so it was getting, and always getting the inital value. Put it inside to update.. voila

how to write an if else statement in javascript

can anyone help me with this if else statement....
Coding
<script>
$("#id_add_select").change(function(){
if($("#id_add_select" == "2")){
handler(1)
} else {
handler(2)
}
});
function handler(situation){
var situation = situation;
switch (situation)
case 1:
display: (".name")
display: (".address")
case 2:
disable: (".age")
disable: (".email")
}
</script>
html coding
<html>
------
<select name="add_select" id="id_add_select">
<option value="1">working</option>
<option value="2">not working</option>
<option value="3">retired</option>
</select>
-------
my situation is if i select 2"not working" then it will display case 1. else will display case 2. basic one but i just can't figure it out. thanks a million.
This is not right:
if($("#id_add_select" == "2")){
You probably want to do something like:
if($(this).val() == 2) {
You can do more optimizations with your code, but this should be in the right direction:
$("#id_add_select").change(function(){
if($(this).val() == 2){
handler(1)
} else {
handler(2)
}
});
Alternative solution
IMO, using a map object with functions is cleaner than using switch statements in your case. So I would probably do something like:
var actions = {
1: function() {
// first choice logic
},
2: function() {
// second choice logic
}
};
$("#id_add_select").change(function() {
actions[this.value]();
});
Demo: http://jsfiddle.net/PurjS/
if($("#id_add_select" == "2")){ => if($("#id_add_select").val() == "2"){
First of all you aren't getting any value:
<script>
$("#id_add_select").change(function(){
if($("#id_add_select").val()==2){
handler(1);
} else {
handler(2);
}
});
</script>
Don't forget to put the break statement after every case in the switch loop.
Figuring out why certain things can't work
$("#id_add_select" == "2")
Apparently, you intended to check whether the selected element's value was 2. However, without needing to know how jQuery works, it's clear that this cannot work.
For this, you simply need to dissect the statement into its essential parts.
We have a function call $() which we perform by passing one argument: "#id_add_select" == "2".
We notice, that the argument to the function is completely independent of the actual call, which is true for all function calls. What this means is, that the result of the comparison will be passed. Because both operands of the comparison are literals, we can evaluate the expression ourselves and replace it by a constant: "#id_add_select" == "2" is obviously not equal, thus the result will be false.
We conclude, that it is the same as writing: $(false). From here, it should be obvious that this code can't check whether some arbitrary element has the value 2.
In addition to the other answer, be aware of
How Switch/Case works
Be aware, that JavaScript's switch/case statement has fall-through behavior.
This means, that once a case clause is executed because it's value matches the input x, it will execute all code below it until it hits a break; statement to exit the switch/case construct.
In the below example, executing printTo5Or8(1) will not have it terminate after console.log(1), instead, it will "fall through" to console.log(2); until the break; statement!
function printTo5Or8(x) {
switch(x){
case 1:
console.log(1);
case 2:
console.log(2);
case 3:
console.log(3);
case 4:
console.log(4);
case 5:
console.log(5);
break;
case 6:
console.log(6);
case 7:
console.log(7);
case 8:
console.log(8);
}
}
printTo5Or8(1); // Prints 1 2 3 4 5
printTo5Or8(3); // Prints 3 4 5
printTo5Or8(6); // Prints 6 7 8
printTo5Or8(7); // Prints 7 8
Invalid Syntax
The switch/case statement requires a block: { statements; } to follow after switch(expression)! You don't have any.
display: (".name")
display: (".address")
You probably meant display(".name");. At the moment, you have labels that do nothing.
Redundant code
function handler(situation){
var situation = situation; // <-- Remove
The formal parameter list (situation) already declares a local variable situation. It is not necessary to declare it.
Conclusion
I suggest you devote some energy to learning JavaScript as a language. Knowing how JavaScript works will help you to reason about your code and rule "impossible" code that couldn't ever work. Without a good grasp on how programming languages or in this case JavaScript works, programming will feel like mixing together some magic incantations that just happen to do sometimes what you want, but go awry more often than not.
Programming is an exact science, not guessing and luck.
i think this code is more clean:
<script>
$("#id_add_select").change(function(){
if( $(this).val() == "2"))
handler(1)
else
handler(2)
});
function handler(situation){
switch (situation){
case 1:
display: (".name");
display: (".address");
break;
case 2:
disable: (".age");
disable: (".email");
break;
}
}
</script>
a piece of optimized love:
$("#id_add_select").change(handler);
var handler = function () {
switch (this.value) {
case 1:
display(".name");
display(".address");
break;
default:
disable(".age");
disable(".email");
break;
}
};
or this way:
$("#id_add_select").change(function () {
switch (this.value) {
case 1:
display(".name");
display(".address");
break;
default:
disable(".age");
disable(".email");
break;
}
});
or this way:
$("#id_add_select").change(function () {
if (this.value === "1") {
display(".name");
display(".address");
} else {
disable(".age");
disable(".email");
}
});
also dont forget that you need a display and a disable method (but i guess you already have made them because your code looks like you have)
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
$("#id_add_select").change(function(){
if($(this).val() == "2")
handler(1)
else
handler(2)
});
});
function handler(situation)
{
switch (situation){
case 1:
alert(situation);
break;
case 2:
alert(situation);
break;
}
}
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<select name="add_select" id="id_add_select">
<option value="1">working</option>
<option value="2">not working</option>
<option value="3">retired</option>
</select>
</body>
</html>

Categories