Disable dropdownlist based on the selected value of another - javascript

This may be a stupid question, but I'm still learning so do forgive me if the answer is obvious :)
I have a test page with the following on:
<select name="ddlRoles" ID="ddlRoles" OnChange="DisEnableDDL();">
<option value="-1">Fresh Milk</option>
<option value="2">Old Cheese</option>
<option value="3">Hot Bread</option>
</select>
<select name="ddlCust" ID="ddlCust">
<option value="-1">rawr</option>
<option value="2">root</option>
<option value="3">honk</option>
</select>
If the user selects anything with a value that's not 3 from ddl Roles, it should disable ddlCust. Here's my JS function:
function DisEnableDDL()
{
var ddlR = document.getElementById("ddlRoles")
var ddlC = document.getElementById("ddlCust")
if(ddlR.options[ddlR.selectedIndex].value = "3")
{
ddlC.disabled = false;
}
else
{
ddlC.selectedIndex = 0;
ddlC.disabled = true;
}
}
Doesn't work. What am I missing? have I failed to set my variables properly? Does this just change the variables ddlR and ddlC without changing the elements on the page itself or something?
Following it through in Firebug, it seems to fall into the correct statements, but ddlCust never gets disabled.
Any help would be most appreciated!

== instead of = in your if:
if(ddlR.options[ddlR.selectedIndex].value == "3")
= is for assignment, whereas == is for comparison, in most C-like syntaxes.

You're not comparing properly, you need to use '==':
if(ddlR.options[ddlR.selectedIndex].value == "3")

Related

JQuery show/hide gives weird results

Im having some weird issues with javascript I can't really resolve.
I have three html input boxes with a small js file to show or hide the second and third one depending on what is picked in the first box. I'm using these functions:
$('#maintype').on('change', function() {
if (this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
The problem im running to is that the second dropdown is not shown when I highlight "fries". The third input box is never shown. I've tried all sorts of solutions, but I just can't figure out why.
I put my code on github
Anyone that can give me some insight on where I am going wrong? Is there maybe another, simpler way to get this done?
You have two issues:
The problem im running to is that the second dropdown is not shown when I highlight "fries"
Your check for fries is wrong, you have:
if ( this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
but the check should be for '6' since that is the value you assigned to it in your #maintype select.
The other issue:
The third input box is never shown.
You assigned the different IDs (eg. #fries, #icecream, etc.) to the <div> and not to the <select>.
You should also not have several elements with the same id or name (ie. #selectlist) in your case this will be solved when you fix the second issue.
There is no handler for <option value="6">fries</option> , i mean there is no if ( this.value == '6') type line in your javascript code. I added below lines in your js file and it worked.
$('#maintype').on('change', function() {
if ( this.value == '6')
//.....................^.......
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
});
Demo : https://jsfiddle.net/gd548j0g/
In your #maintype select, fries has a value of '6'. But in your change handler, you are looking for a value of 1. In fact, there is no value in the select that has a value of 1. Hence, the fries select box is never shown. Either change your handler to look for the id of 6:
$('#maintype').on('change', function() {
if ( this.value == '6') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
Or change your option value for fries to 1:
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="1">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
Working example: https://jsfiddle.net/mspinks/vnofjobu/2/
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="6">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
$('#maintype').on('change', function() {
if ( this.value == 6)
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
be careful with the values that you assign to the options
your value of fries is 6, not 1
I have checked your code in Git, you can achieve your output with below code in your showhide.js file.
$(document).ready(function(){
$('#maintype').on('change', function() {
$('input[type="text"]').hide(); //Hides all input with type Text, better if we do this using class
var id = '#' + this.value;
$(id).show(); //Show input with id which you have returned with this.value
});
});

JS: Change select option value on being selected with prompt?

I've looked around and I don't see this being asked before.
I have a select box, like so:
<select onchange="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
</select>
I want to add another option...
<option value="custom">Option 4</option>
...that when chosen (clicked) an alert box will popup asking the user to type in a number (in the case 30 or 90 weren't viable options, as in the values of the option's) to replace the value of the option.
<script>
function change() {
if(value == "custom") {
value = prompt("Please enter a new number:", "60");
}
}
</script>
I wanted to know what the best way to do this is with plain old javascript - I'll use jQuery if I have to.
Any ideas? An example would be great as well.
Take a look at this code. I think this is what you're trying to do:
HTML
<select id="optionvals" onclick="change()">
<option value="" selected>Option 1</option>
<option value="30">Option 2</option>
<option value="90">Option 3</option>
<option value="custom">Option 4</option>
</select>
JS
function change() {
var oItem = document.getElementById('optionvals');
var value = oItem.options[oItem.selectedIndex].value;
if(value == "custom") {
alert("you've clicked b");
value = prompt("Please enter a new number:", "60");
oItem.options[oItem.selectedIndex].value = value;
console.log(oItem.options[oItem.selectedIndex].value)
}
}
What this does is prompt you on the change only if the selected value in the options is custom. Then after you choose a custom value, it will rewrite the value of that the custom option element to the value you just entered in the prompt. I logged the new value after assigning it to show you that it is working.
Here is a fiddle: https://jsfiddle.net/ng7xvy05/
Your onchange event is the appropriate way to handle this. This is mostly a matter of user interface (UX) design though. To do this in the prompt fashion you ought to use parseFloat:
change() {
var value = prompt('You\'ve chosen Other. Please enter a value', '60');
if(value) {
value = parseFloat(value);
// apply it to your model
} else {
// apply NULL to your model
}
}
From a UXD point of view I would use a typeahead input. It would autosearch known answers but also allow the user to input their own. This is not standard html so you would need to write this yourself or use jquery. But from a user interface design point of view, prompts suck.

separating an event to perform actions in other functions depending on the result of the event

Thank you for taking the time to read this. I'm learning about OOP, Module, and Constructor Function and the stuff is too advance for me so I am stuck trying to write the below code.
Im trying to separate events so I could perform functions addTwoNums() and addThreeNums() depending on the value of what is returned from GetAmount I know the speek method is not set up for that. can you do something to set something like to fix it. Im so lost.
$(document).ready(function(){
$emitter = $({})
console.log($emitter);
$("#amountItems").on('change', function(){
var amountchosen = $("#amountItems option:selected").val();
$emitter.trigger("amountUpdate", amountchosen);
});
var GetAmount = (function(){
this.mode = "";
$emitter.on("amountUpdate", function(e, val){
if(val == 2){
alert(2)
this.mode = 'addTWoNumbers'
}else if(val == 3){
alert(3)
this.mode = 'addThreeNumbers'
}else if(val== 4){
alert(4)
this.mode = 'addFourNumbers'
}
})
return {
speek : function(){
console.log(this.mode);
}
}
})();
// I think these methods should be apart of a module
function addTwoNums(){
GetAmount.speek(); //I guess i could instantiate an object
//here like (if (twonumbers = new GetAmount())) it should return addTWoNumbers
//so now i could do operation pertaining to 2 numbers
//do some function when 2 is chosen
}
function addThreeNums(){
//do some function when 3 is chosen
}
});
Also I got that part $emitter = $({}) from another source but I would like a clearfiacation on how it works. because where making $emitter an empty
jquery obj that mean we could use it for some type of place holder to trigger events. its like were making up an object just to perform actions on it but it doesnt contain anything.
I know these concepts are from pub/sub type of pattern.I think I'm trying to make a pub/sub.
HTML:
<div class="select labelOuter">
<!-- <p>How many Items would you like to add</p> -->
<select name="" id="amountItems" data-chosen ="0">
<option selected default disabled value="">Amount of items</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>

How to disable <select> based on other <select> on Select2.js

i'm having a little trouble with disabling a "select" input.
I need to disable "cidade" whenever nothing is selected on "estado".
here's my code:
<select id="estado" class="select_customized">
<option></option>
<option value="sp">São Paulo</option>
<option value="mg">Minas Gerais</option>
<option value="rj">Rio de Janeiro</option>
</select>
<select id="cidade" class="select_customized">
<option></option>
<option value="sao-paulo">São Paulo</option>
<option value="minas-gerais">Minas Gerais</option>
<option value="rio-de-janeiro">Rio de Janeiro</option>
</select>
And here's the script i'm using:
$("#cidade").select2("enable", false);
$("#estado").on('change',function(){
var is_empty = $('#estado').is(":empty");
if(is_empty){
$("#cidade").select2("enable", false);
}
else {
$("#cidade").select2("enable", true);
}
});
this kinda works, but whenever i choose something on the "estado" input, and clear it again, "cidade" does not disable again... any suggestions?
You probably want to use the select2 call to check if the selection box is empty, instead of going into the original #estado box you created (since that is hidden by select2).
Your call:
var is_empty = $('#estado').is(":empty");
then can be changed to something like:
var is_empty = $('#estado').select2("val") == "";
and that did the job for me. Note that the actual comparison above will differ a bit depending on for example if you are using a multi-valued selection box.
I think is that you need actually. You just need to set the .on('change') to make it works, like this fiddle.
UPDATE: easier than I thought.
http://jsfiddle.net/fczo7tLq/2/
$("#cidade").prop('disabled', 'disabled');
$("#estado").on('change', function() {
var that = $("#estado option:selected").val();
if (that !== "empty") {
$("#cidade").prop('disabled', false);
} else {
$("#cidade").prop('disabled', 'disabled');
}
});

HTML/JS: Validating value in <selected>-list

I'm really new to this and working on a JavaScript code and I want to see if a dropdownlist has any choosen value. How do i do that?
I tried:
var selectObj = form.document.getElementById('myListId');
var selectInd = selectObj.selectedInd;
and tried:
if(selectInd == "")
to check if it was empty.
What do I need to change to make it work?
Thanks in advance!
A drop-down, by design, always has a value selected. If you just want to leave an empty value first to not choose something for the user, you can simply check if it's value is empty.
document.getElementById("validate").onclick = function() {
if (document.getElementById("foo").value == "")
alert("invalid");
else
alert("valid");
};
Live example
According to comments, this might not work in older versions of IE. Be sure to test it there if you need to support those browsers.
HTML
<select id="myListId">
<option value="">- Select an option-</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Javascript
function checkvalue(){
var selectObj = form.document.getElementById('myListId');
if (selectObj.value != "") {/* DO something */}
}
Now you can execute this function on change of the select box, or when you submit the form, it is up to you.
Try to read this example.
You are trying compare a number (selectObj.selectedIndex) with a string (""), you should write something like this:
var selectObj = document.getElementById('myListId'),
selectInd = selectObj.selectedIndex,
selectedVal = selectObj.options[selectInd].value;
if(selectedVal== "") {
/* do your stuff*/
}
Only to notice: This only would work (detect a value equal to "") with an html like this:
<select id="myListId">
<option value="" selected="selected">Empty value</option>
<option value="1">Non empty value</option>
</select>
Or when the user has been selected the option "Empty value".
EDIT:
Try with this demo. This demo also works in IE7.

Categories

Resources