My problem is that i have 2 dropdowns and I want to change second dropdown by the value of first. For example: if user chooses "Apple" on the first dropdown second dropdown should instantly get "iPhone" and "iPad" options. If client changes his mind and selects "Microsoft" "iPhone" and "iPad" values should be deleted and instead of them there should appear "Windows" and "Office". How can I make it work? Thanks.
HTML:
<select name="brand" id="brand" onChange="populateSecond(this.value);">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
jQuery:
$(document).ready(function() {
$("#brand").change(function(populateSecond(id)) {
if(id == 1){
$('select[id=model]').append('<option value="a">iPhone</option>');
$('select[id=model]').append('<option value="a">iPad</option>');
}if(id == 2){
$('select[id=model]').append('<option value="b">Windows</option>');
$('select[id=model]').append('<option value="b">Office</option>');
}
});
});
Problem: http://jsfiddle.net/w6E88/6/
Remove the onChange from the html and do it like this!You are already using Jquery onchange no need to give onChange to your HTML also if you need the selected value from the first dropdown you could simply use this.value to get it and make the necessary changes to your Second DropDown List.
HTML
<select name="brand" id="brand">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
JQUERY
$(document).ready(function() {
$("#brand").change(function() {
var id=this.value;
if(id == 1){
$('#model').html("");
$('#model').append('<option value="a">iPhone</option>');
$('#model').append('<option value="a">iPad</option>');
}else if(id == 2){
$('#model').html("");
$('#model').append('<option value="b">Windows</option>');
$('#model').append('<option value="b">Office</option>');
}
else{
$('#model').html("");
$('#model').append('<option value="">----------------</option>')
}
});
});
Here is another jQuery way of achieving the functionality you want (commented with explanation)
Added bootstrap class to select element for the looks.
HTML
<select id="mainCategorySelect" name="mainCategorySelect" class="form-control">
<option>Select category</option>
</select>
<select id="subCategorySelect" name="subCategorySelect" class="form-control"></select>
JS
// Wait for the dom to be ready
$(function () {
// For the sake of this example our business and products are arrays
var businesses = ["Microsoft","Apple"],
msProducts = ["Microsoft Phone","Microsoft Office","Microsoft Windows 10"],
appleProducts = ["Apple iPhone","Apple iPad","Apple iPod","Apple iSomething"],
// Declare variables for the select elements
mainCategorySelect = $('#mainCategorySelect'),
subCategorySelect = $('#subCategorySelect');
// Iterate thorugh businesses and populate the main select element
for (var i = 0; i < businesses.length; i++) {
mainCategorySelect.append("<option value='"+businesses[i]+"'>"+businesses[i]+"</option>");
}
// using jQuery .on('change')
mainCategorySelect.on('change', function() {
// Always clear the sub category select when main select element value is changed
subCategorySelect.empty();
// Retrieve the value of the main select element
var business = $(this).val();
// if else statement to deside which products to list in the sub category select element
if (business == "Microsoft") {
// if Microsoft then iterate through the msProducts array and append the values as option elements to the sub category select element
for (var i = 0; i < msProducts.length; i++) {
subCategorySelect.append("<option value='"+msProducts[i]+"'>"+msProducts[i]+"</option>");
}
} else if(business == "Apple") {
// if Apple then iterate through the appleProducts array and append the values as option elements to the sub category select element
for (var i = 0; i < appleProducts.length; i++) {
subCategorySelect.append("<option value='"+appleProducts[i]+"'>"+appleProducts[i]+"</option>");
}
}
// When the user changes the value of the sub category select element the do something with it
subCategorySelect.on('change', function() {
alert($(this).val());
});
});
});
And here is a working fiddle: http://jsfiddle.net/kagLhpka/
You already have onChange="populateSecond(this.value);" in your HTML code, no need for the .change in JS as well.
You can either define the function populateSecond entirely before the first call to it; or use only the jQuery method. I'm giving the jQuery result here only:
$(document).ready(function () {
$("#brand").on('change', function (id) {
if (id == 1) {
$('select[id=model]').append('<option value="a">iPhone</option>');
$('select[id=model]').append('<option value="a">iPad</option>');
} else {
$('select[id=model]').append('<option value="b">Windows</option>');
$('select[id=model]').append('<option value="b">Office</option>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="brand" id="brand">
<option value="">----------------</option>
<option value="1">Apple</option>
<option value="2">Microsoft</option>
</select>
<select id="model">
<option value="">----------------</option>
</select>
PS: I prefer using .on('change', handler) method over .change.
Here is the structured way.
var childData = {
apple: ["iPhone", "iPad"] ,
ms: ["Windows", "Office"]
};
$("#brand").change(function () {
var newData = childData[this.value];
var element = $("#model").empty();
element.append('<option>----------------</option>');
$.each(newData, function(i, val) {
element.append('<option value='+i+'>'+val+'</option>');
});
});
Check this Fiddle: http://jsfiddle.net/soundar24/w6E88/11/
Using explicit conditionals to validate against will make this difficult to maintain in the future if the product line expands beyond a certain quantity. Using some form of array is a better way to do it, as others have shown.
Also, while jQuery is a great library, don't forget about vanilla JavaScript. When coded well, even though it appears more convoluted, plain JavaScript should run faster than a jQuery counterpart. With that in mind, here's another solution, this time in "more or less" plain JavaScript -- I left in the on ready.
HTML
<select name="brand" id="brand">
<option value="-1">--------------------</option>
<option value="apple">Apple</option>
<option value="microsoft">Microsoft</option>
</select>
<select id="model">
<option value="-1">--------------------</option>
</select>
JavaScript
var products = {
apple: [
{ name: "iPhone 6 Plus", model: "iphone_6plus" },
{ name: "iPhone 6", model: "iphone_6" },
{ name: "iPhone 5s", model: "iphone_5s" },
{ name: "iPhone 5c", model: "iphone_5c" }
],
microsoft: [
{ name: "Windows 10", model: "windows_10" },
{ name: "Windows 8", model: "windows_8" },
{ name: "Office 2015", model: "office_2015" },
{ name: "Office 2014", model: "office_2014" }
]
};
function create_option(text, value) {
var option = document.createElement("option");
var txt = document.createTextNode(text);
option.value = value;
option.appendChild(txt);
return option;
}
function populate_model(selection) {
var select = document.getElementById("model");
var i, l;
if ((selection == -1) || (products[selection] === undefined))
return false;
while (select.lastChild)
select.removeChild(select.lastChild);
select.appendChild(document.createElement("option").appendChild(document.createTextNode("--------------------")));
for (i = 0, l = products[selection].length; i < l; i++)
select.appendChild(create_option(products[selection][i].name, products[selection][i].model));
}
$(document).ready(function() {
var brand = document.getElementById("brand");
brand.onchange = function() {
populate_model(this.options[this.selectedIndex].value);
};
brand.value = -1;
});
I've updated your JSFiddle as well: http://jsfiddle.net/w6E88/13/
Related
I want to bind control values based on the data from the database table. All the controls like textbox are getting bind except the dropdownlist values are not getting bind.
Below is my code
function BindDataTableToJSONProject(strVal) {
var ProjectData = JSON.parse(strVal);
var getJSONValue = ProjectData.Table[0];
if (getJSONValue.PROJECT_MANAGER_NAME != "" && getJSONValue.PROJECT_MANAGER_NAME != null) {
$('#ContentPlaceHolder1_ddlProjMan').val(getJSONValue.PROJECT_MANAGER_NAME);
}
}
</script>
<select name="ctl00$ContentPlaceHolder1$ddlProjMan" id="ContentPlaceHolder1_ddlProjMan" class="form-control">
<option value="0">--Select--</option>
<option value="1">ABC</option>
<option value="2">PQR</option>
<option value="3">XYZ</option>
</select>
Below is my json data for the same.
{ID: 6, MST_ID: 107, PROJECT_NO: "R4G-25-APD-210", CR_NO: "R4G-25-APD-ACR-1212", APPLICATION_NAME: "Workflow for VSAT Application", PROJECT_MANAGER_NAME: "XYZ", …}
One way would be looping through options inside select tag and then checking if the .text() is equal to PROJECT_MANAGER_NAME if yes then add selected true to that option.
Demo Code :
var getJSONValue = {
"ID": 6,
"MST_ID": 107,
"PROJECT_NO": "R4G-25-APD-210",
"CR_NO": "R4G-25-APD-ACR-1212",
"APPLICATION_NAME": "Workflow for VSAT Application",
"PROJECT_MANAGER_NAME": "XYZ"
}
BindDataTableToJSONProject();
function BindDataTableToJSONProject() {
if (getJSONValue.PROJECT_MANAGER_NAME != "" && getJSONValue.PROJECT_MANAGER_NAME != null) {
//loop through option
$('#ContentPlaceHolder1_ddlProjMan option').each(function() {
//get text of option check if equal to pmn
if ($(this).text() == getJSONValue.PROJECT_MANAGER_NAME) {
$(this).prop("selected", true) //set slectd true
}
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="ctl00$ContentPlaceHolder1$ddlProjMan" id="ContentPlaceHolder1_ddlProjMan" class="form-control">
<option value="0">--Select--</option>
<option value="1">ABC</option>
<option value="2">PQR</option>
<option value="3">XYZ</option>
</select>
You try to set value (that is 3) <option value="3">XYZ</option>
but you select the parameter of the text getJSONValue.PROJECT_MANAGER_NAME == "XYZ"
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P
I am creating an online exam system, and I have two drop-down menus. One menu checks for difficulty level, and based on the selection of "Easy", "Medium", and "Hard", the second menu displays the associated questions. Now, I am trying to retrieve the id of the questions from the second drop-down menu which is based off of the first. I'm pretty new to Ajax, so is there a way to achieve this? Any help would be appreciated. Thanks.
<form>
<select id="difficulty" name="difficulty" onchange="changeType();">
<option value="">Select a difficulty level</option>
<option value="E" >Easy</option>
<option value="M">Medium</option>
<option value="H">Hard</option>
</select>
<select name="questions" onchange="showQuestion(this.id)>
<option id="">Select a question</option>
<option id="1" onclick="showQuestion(this.id)">Question1</button>
<option id="2" onclick="showQuestion(this.id)">Question2</button>
<option id="3"></option>
<option id="4"></option>
<option id="5"></option>
<option id="6"></option>
</select>
</form>
<script>
var data =
[
{
name: "E",
options: ["Question1", "Question2"]
},
{
name: "M",
options: ["Question3", "Question4"]
},
{
name: "H",
options: ["Question5", "Question6"]
}
];
function changeType()
{
var i, optionSelected, str, j, optionE1Two;
//get currently selected first option
optionSelected = document.getElementById("difficulty").value;
i = 0;
while (i < data.length && data[i].name != optionSelected)
{
i++;
}
//populate second menu
if(i < data.length)
{
str = '';
for(j=0; j<data[i].options.length; j++)
{
str += '<option value = "'+data[i].options[j]+'">'+data[i].options[j]+'</option>';
}
optionE1Two = document.getElementById("questions");
optionE1Two.innerHTML = str;
}
}
document.getElementById("difficulty").addEventListener("change",changeType,false);
</script>
<br>
<div id="text" ><b><center>Questions you select will be listed here.</center></b></div>
<script>
function showQuestion(str) {
//alert(str); //alert outputs "questions"
if(str == "") {
document.getElementById("text").innerHTML="";
return;
}
if(window.XMLHttpRequest){
hr = new XMLHttpRequest();
}else {
hr = new ActiveXObject("Microsoft.XMLHTTP");
}
hr.onreadystatechange=function() {
if(this.readyState==4 && this.status==200){
document.getElementById("text").innerHTML=this.responseText;
}
};
hr.open("GET", "URL", true);
hr.send();
}
</script>
Welcome to Stack Overflow!
Here is my understanding of your logic.
User Selects the Difficulty
User Selects the Question to work with
Then you process that action
You are looking for the ID, value containing the ID, of the selected question? I have put together a Codepen of my solution. I tried to avoid making any dramatic changes. I did change:
Changed 'id' to 'value' on select options
Modified the 'onChange' event to send the whole element
Added line 52 to make the questionId a var to make future use a little easier
Using values is preferred for many reasons. One in particular is the accessibility. The DOM allows direct access to the selected index and its value. I do strongly recommend reviewing your code though for syntax errors. There are quite a few. I tackled a few that stuck out and hindered the solution to your question.
P.S. I have made a few more mods as well to fix the changeType() function. It was throwing an error when setting the innerHTML.
var data = [{
name: "E",
options: ["Question1", "Question2"]
},
{
name: "M",
options: ["Question3", "Question4"]
},
{
name: "H",
options: ["Question5", "Question6"]
}
];
function changeType() {
var i, optionSelected, str, j, optionE1Two;
//get currently selected first option
optionSelected = document.getElementById("difficulty").value;
i = 0;
while (i < data.length && data[i].name != optionSelected) {
i++;
}
//populate second menu
if (i < data.length) {
str = '<option value="">Select a question</option>';
for (j = 0; j < data[i].options.length; j++) {
str += '<option value = "' + data[i].options[j] + '">' + data[i].options[j] + '</option>';
}
optionE1Two = document.getElementById("questions");
optionE1Two.innerHTML = str;
document.getElementById("text").innerHTML = "<b><center>Questions you select will be listed here.</center></b>";
}
}
document.getElementById("difficulty").addEventListener("change", changeType, false);
function showQuestion(el) {
// Accepting the element allows direct access
console.dir(el.value); // consoles the value of the selected option.
var questionId = el.value;
if (questionId == "") {
document.getElementById("text").innerHTML = "<b><center>Questions you select will be listed here.</center></b>";
return;
} else {
document.getElementById("text").innerHTML = "<b><center>You have selected Question: " + el.options[el.selectedIndex].text + "</center></b>";
}
if (window.XMLHttpRequest) {
hr = new XMLHttpRequest();
} else {
hr = new ActiveXObject("Microsoft.XMLHTTP");
}
hr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("text").innerHTML = this.responseText;
}
};
hr.open("GET", "URL", true);
hr.send();
}
<form>
<select id="difficulty" name="difficulty" onchange="changeType();">
<option value="">Select a difficulty level</option>
<option value="E" >Easy</option>
<option value="M">Medium</option>
<option value="H">Hard</option>
</select>
<!-- changed the change event to send the element as a whole -->
<select name="questions" id="questions" onchange="showQuestion(this)">
<option value="">Select a question</option>
<option value="1">Question1</option>
<option value="2">Question2</option>
</select>
</form>
<br>
<div id="text">
<b><center>Questions you select will be listed here.</center></b>
</div>
I have a form that has a handful of dropdowns. I want to confirm all dropdowns have been selected before form submit. The id's of the elements are variable so i cant use them as a selector, so i put all the elements in the verify class. So now i need to iterate through all elements that have the verify class and make sure they are not empty/undefined/null. the number of elements is unknown as well. I am guessing I would map or use each on some level, I just don't know where to begin.
$('.verify').change(function()
{
//iterate through each item with verify class..
if (//All items are selected)
{
$(":button:contains('Complete')").removeAttr("disabled").removeClass('ui-state-disabled' );
}
});
html:
<td class='dialog'>
<select id='someVariable' class='verify'>
<option value=''></option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</td>
<td class='dialog'>
<select id='someOtherVariable' class='verify'>
<option value=''></option>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>
</td>
Try
var $varifies = $('.verify').change(function () {
//iterate through each item with verify class..
var invalid = $varifies.filter(function () {
return !$(this).val();
}).length;
$(":button:contains('Complete')").prop("disabled", invalid);
});
Demo: Fiddle
i suggest $('.verify').not('[value!=""]').length == 0
First select the elements which are having selected options in it. and compare its length with the overall count of select elements. If counts are same, All elements have been selected.
Try,
var $varifies = $('.verify').change(function () {
var xSelectedElems = $('.verify').filter(function () {
return $(this).find('option:selected').val() != '';
}).length;
var xTotalElems = $('.verify').length;
$(":button:contains('Complete')").prop("disabled", (xTotalElems != xSelectedElems));
});
DEMO
You might be over complicating it a little. On submit, loop over each select.verify element and check its value propery:
$($(".verify:first")[0].form).submit(function(event) {
var valid = true, $form = $(this);
$form.find(".verify").each(function() {
if (/^\s*$/.test(this.value)) {
valid = false;
$(this).addClass("ui-state-invalid");
}
else {
$(this).removeClass("ui-state-invalid");
}
});
if (valid) {
$form
.find(":button:contains('Complete')")
.removeAttr("disabled")
.removeClass('ui-state-disabled');
}
else {
event.preventDefault();
}
});
I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});