disable previously selected dropdown option, check both text & id value - javascript

In a table, how to loop through all dropdowns text & id in a table's col, and save them in array. So that I can disable previously selected options
Once an option is selected, I do not want it to be available again. How to check the selected text of previously selected options in the table set that option to disabled on all other dropdowns in the page.
(this question is different from other SO questions since its disabling after checking both selected text & selected value inside a table and needs to target the dropdown in the specified column)
var allSelectedValuesArray = array();
allSelectedValuesArray.push($("#tblVersions .Model option:selected").text());
var rows = $("body tr",$("#tblVersions")).map(function() {
return [$("td:eq(0) input:checkbox:checked",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
<table id="tblversions">
<tbody id="body">
<tr class="rowcss">
<td>
<select class="Manufacturer">
<option value="1">Toyota </option>
<option value="2">Honda</option>
<option value="3">BMW</option>
</select>
</td>
<td>
<select class="Model">
<!-- If user selects Honda my Ajax populates Honda Models/Cars like below-->
<option value="1">Accord</option>
<option value="2">Toyota 2</option>
<option value="3">Honda 3</option>
</select>
</td>
</tr>
<tr class="rowcss">
<td>
<select class="Manufacturer">
<option value="1">Toyota </option>
<option value="2">Honda</option>
<option value="3">BMW</option>
</select>
</td>
<td>
<select class="Model">
<!-- If user selects BMW my Ajax populates BMW models Cars like below-->
<option value="1">X5 Suv</option>
<option value="2">318 series Cheap</option>
<option value="3">540i too expensive!</option>
</select>
</td>
</tr>
</tbody>
</table>

I didn't understand the second part of your question, but if you want to get text and values for all dropdowns you could do something like this.
// Called when any of the dropdowns change
( "#tblversions" ).change(function() {
var allSelectedValuesArray = [];
// Search for all selects in the #tblversions
$("#tblversions select option:selected").each(function() {
// for each one, push it into the array
allSelectedValuesArray.push({text:$(this).text(), value:this.value});
});
});
This creates an array of objects in the format {text:"sometext",value:"somevalue"} for each of the dropdowns in the table.

Related

Hide/Show <option> in select element when another option in another select is selected

I've been trying to achieve this using javascript but it doesn't seem to work, I have a JSTL based Select element in my JSP. Since I want to filter by "name" attribute those elements in the second Select that match with the ones in the first, So if I select "A" in first select, I want the options for the second select to be [A1,A2,A3...] and if I select "B" in the first select, I want the options for the second select to be [B1,B2,B3...] and so on.
That's why I use the "A" or "B" as name attribute on the second Select for every option that may match with the ones in the first Select.
My JSP snippet goes like this:
<tr>
<td align="right">address:</td>
<select id = "addressSelector" onchange = "filterBlocksByAddress()">
<option value="">
Choose an Address
</option>
<c:forEach items="${realStatesList}" var="realState">
<option>${realState.realStateID.address}</option>
</c:forEach>
</select>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td align="right">block:</td>
<select id ="blockSelector">
<option value="">Choose a Block</option>
<c:forEach items="${realStatesList}" var="realState">
<option class = "hidden" name = "${realState.realStateID.address}">
${realState.realStateID.block}
</option>
</c:forEach>
</select>
<td><input type="text" name="block"></td>
</tr>
My Javascript method goes like this:
function filterBlocksByAddress() {
let flag = true;
let addressText = document.getElementById('addressSelector').options[document.getElementById('addressSelector').selectedIndex].text;
let blockOptions = document.getElementsByName(addressText);
for (i = 0; i < blockOptions.length; i++) {
blockOptions[i].classList.add("hidden");
}
for (i = 0; i < blockOptions.length; i++) {
if(blockOptions[i].getAttribute("name") == addressText) {
blockOptions[i].classList.remove("hidden");
}
}
return flag;
}
the hidden class is defined on css as .hidden{ display:none; }
When the jsp loads the second select gets all its options hidden but as soon as I start to select Options in the first select, then second select starts to show the ones that matches (that's what I want), but the problem is that they never get hidden anymore when I change the selected option in the first select.
Any Ideas?, Thanks a lot.
You can use document.querySelectorAll('#blockSelector option[name]').. to add hidden class to all your options and then remove hidden class from options where name="yourfirstselectvalue" .
Demo Code :
function filterBlocksByAddress(addressText) {
console.log(addressText)
//hide all options.
document.querySelectorAll('#blockSelector option[name]').forEach(function(el) {
el.classList.add("hidden")
});
//if not first one slected
if (addressText != "Choose an Address") {
//loop through options where values matches..
document.querySelectorAll('#blockSelector option[name=' + addressText + ']').forEach(function(el) {
el.classList.remove("hidden"); //remove class
})
}
document.getElementById('blockSelector').selectedIndex = 0 //set first vlau slected
}
.hidden {
display: none
}
<select id="addressSelector" onchange="filterBlocksByAddress(this.options[this.selectedIndex].text)">
<option value="">Choose an Address</option>
<option>A</option>
<option>B</option>
</select>
<select id="blockSelector">
<option value="">Choose a Block</option>
<option class="hidden" name="A">
A1
</option>
<option class="hidden" name="A">
A2
</option>
<option class="hidden" name="B">
B1
</option>
<option class="hidden" name="B">
B2
</option>
</select>

Chained Dropdown(s) and Textbox in HTML

I am having a use case for a design:
There are students who have to pay their fees every month in a class.
So I am trying to do the following:
1. Dropdown #1: Contains Student Names
2. Dropdown #2: Contains Month Names
3. Textbox: Contains Fees amount for the selected month.
I am using the following code:
$(document).ready(function() {
$("#myDropdown").change(function() {
var selectedValue = $(this).val();
$("#txtBox").val(selectedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tab1">
<tr>
<td>Select Affiliate Source:</td>
<td>
<select id="myDropdown">
<option value="jan" label="2000">January</option>
<option value="apr" label="2500">April</option>
<option value="jul" label="2000">July</option>
<option value="oct" label="2500">October</option>
</select>
<div>
<input id="txtBox" type="text" readonly='1'>
</div>
</td>
</tr>
</table>
taken from stackoverflow. but i am unable to:
1. add a dropdown (for students) in a chained fashion, such that once a student is selected only then the months dropdown gets active.
2. once a month is selected, the value in its label attribute should be displayed in the textbox.
Any inputs will be more than appreciated.
Regards,
GenXCoders
Enable month select box onchange of student select box.
Get the value of month select box on onchange and set in text box.
$(document).ready(function() {
$("#student").change(function() {
$('#month').prop('disabled', false);
});
$("#month").change(function() {
var selectedValue = $('#month :selected').attr('label');
$("#txtBox").val(selectedValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="tab1">
<tr>
<td>Select Affiliate Source:</td>
<td>
<select id="student">
<option value="Student1">Student1</option>
<option value="Student2">Student2</option>
<option value="Student3">Student3</option>
</select>
<select id="month" disabled>
<option value="jan" label="2000">January</option>
<option value="apr" label="2500">April</option>
<option value="jul" label="2000">July</option>
<option value="oct" label="2500">October</option>
</select>
<div>
<input id="txtBox" type="text" readonly='1'>
</div>
</td>
</tr>
</table>

How to determine which drop-down is changed from a number of selects sharing same name as an array

I have a number of dropdowns (like dozens) arranged in rows in a table with same name and square brackets (objects[]) so that I can have their values as an array when posted.
<tr 1>
<select name="objects[]">
<option value='Choice 1'>Choice 1</option>
<option value='Choice 2'>Choice 2</option>
</select>
</tr>
<tr 2>
<select name="objects[]">
<option value='Choice 1'>Choice 1</option>
<option value='Choice 2'>Choice 2</option>
</select>
</tr>
Question
When I change the value of a drop-down, using jquery/js is it possible to uniquely identify which drop-down's value is changed from this set of drop-downs? i.e to get the index of the drop-down.
Use Case is to populate a text field next to the changed drop-down in the same row and as they all share the same name with [] I want to identify which one is changed to update text field at the correct place.
Thanks.
There is no need to get the index of the element, we can watch for change using the .on() function, we attach it to all the select elements, then we get the value using .val() and set the same to the adjacent input we find using .next function.
//optional code - for initalization
$('select').each(function(){
$(this).next( "input" ).val($(this).val());
});
//optional code - for initalization
$('select').on("change", function(){
$(this).next( "input" ).val($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr 1>
<select name="objects[]">
<option value='Choice 1'>Choice 1</option>
<option value='Choice 2'>Choice 2</option>
</select>
<input type="text"/>
</tr>
<tr 2>
<select name="objects[]">
<option value='Choice 1'>Choice 1</option>
<option value='Choice 2'>Choice 2</option>
</select>
<input type="text"/>
</tr>

jQuery - order html table rows dynamically, not using ui-sortable

I'm trying to make a controllable html table list.
My List is like that:
<table>
<tr id="selection_18">
<td>
<select id="colors_18">
<option value="0">All</option>
<option value="1">Red</option>
<option value="2">Yellow</option>
</select>
</td>
</tr>
<tr id="selection_27">
<td>
<select id="colors_27">
<option value="0">All</option>
<option value="1">Red</option>
<option value="2">Yellow</option>
</select>
</td>
</tr>
<tr id="selection_5">
<td>
<select id="colors_5">
<option value="0">All</option>
<option value="1">Red</option>
<option value="2">Yellow</option>
</select>
</td>
</tr>
<tr>
<td>
<button onclick="orderRows();" />
</td>
</tr>
</table>
Scenario is like that: user select all colors for example;
for first row he selected red, for second row he selected yellow, for third row he selected again red, ... and for ninetieth row he selected yellow.
And user wants to order all rows by color again to see for example which color is selected how many times.
What should i write in javascript function orderRows(). I can use jQuery but not want to use jQuery UI sortable. Because in some of my list, it has 400 rows. I think it would be not good solution.
You can use this;
$("#order").on("click", function() {
$('tr').sort(function(a, b){
return $(a).find("option:selected").text() > $(b).find("option:selected").text();
}).appendTo('table')
});
$("#order").appendTo("table"); // this is for keep button place
Here is a working demo: jsfiddle
In demo, you can select colors, and click order button. After order, you can select your colors again and click order to shuffle.
Note: a, and b in function refers to specific two elements n and n+1 for each iteration. It means, it is comparing nth and (n+1)th element for each iteration. If n > n+1 element, n remains same, if not, n+1 moves place before n
The function below will build a hashmap that groups the IDs of the select elements based on the color selected. You could use that hashmap to render the table however you would like to.
See the working demo at:
JSFiddle
JS:
function orderRows(){
var colorArray = [ 'All', 'Red', 'Yellow' ];
var colorMap = {};
$('table select').each(function(){
var color = colorArray[$(this).val()];
if( colorMap[color] == undefined ){
colorMap[color] = [];
}
colorMap[color].push($(this).attr('id'));
});
$('div#display').html(JSON.stringify(colorMap));
}
HTML added (notice that the button was pulled out of the table):
<div>
<button onclick="orderRows()">orderRows</button>
</div>
<div id="display">
</div>
JSON displayed example:
{"Red":["colors_18","colors_5"],"Yellow":["colors_27"]}

How can I show/hide options in a select when another option is selected

I'm trying to make an Unnoficial character creation tester for the popular game Mount & Blade. The script should in theory, depending on the options chosen, determine the characters stats as it would do in game.
At the moment when I choose male/female in the select box none of the specified fields disappear. What have I done wrong?
When the stats are changed I want to automatically display them in a tabular form, would that require me to give an id to each td or could I somehow reference which cell so like the third cell from the left two cells down would be table1(3,2) or is that too difficult/impossible?
Here is the Javascript:
// Base Stats -
var sGender; // Male or Female
var iAgi = 6;
var iStr = 5;
var iInt = 5;
var iCha = 5;
$("#selGender").change(function() {
var mnf = $(this).val();
sGender = parseInt(mnf);
if (sGender = 1){
// Show/hide options
$('#fnomad').hide();
$('#fnoble').hide();
$('#fsquire').hide();
$('#mnomad').show();
$('#mnoble').show();
$('#msquire').show();
iAgi++;
iInt++;
this.disabled=true;
} else {
$('#mnomad').hide();
$('#mnoble').hide();
$('#msquire').hide();
$('#fnomad').show();
$('#fnoble').show();
$('#fsquire').show();
iStr++;
iCha++;
this.disabled=true;
}
}
Here is the HTML
<legend>Choose your background:</legend>
<label>Gender</label>
<select id="selGender">
<option value="1" >Male</option>
<option value="2">Female</option>
</select>
<label>Your father was ...</label>
<select id="selFather">
<option id="fnoble" value="fnoble">a Noble</option>
<option id="mnoble" value="mnoble">a Noble</option>
<option value="merchant">a Merchant</option>
<option value="vetwarrior">a Veteran Warrior</option>
<option value="thief">a Thief</option>
<option id="fnomad" value="fnomad">a Nomad</option>
<option id="mnomad" value="mnomad">a Nomad</option>
</select>
EDIT: Also, I've made sure I've linked to the jQuery file in the header.
<script type="text/javascript" src="jquery.min.js"></script>
EDIT2: this is the section where mSquire and fSquire are:
<label>When you grew to a young adult, you became a ...</label>
<select id="selAdult">
<option id="msquire" value="msquire">a Squire</option>
<option id="fsquire" value="fsquire">a Lady in waiting</option>
<option value="troubadour">Troubadour</option>
<option value="student">Student</option>
<option value="peddle">Peddler</option>
<option value="poacher">Poacher</option>
</select>
See http://jsfiddle.net/KvNVN/
Instead of showing/hiding each element, you can add classes to them:
<select id="selFather">
<option id="fnoble" value="fnoble" class="f">a Noble (f)</option>
<option id="mnoble" value="mnoble" class="m">a Noble (m)</option>
<option value="merchant">a Merchant</option>
<option value="vetwarrior">a Veteran Warrior</option>
<option value="thief">a Thief</option>
<option id="fnomad" value="fnomad" class="f">a Nomad (f)</option>
<option id="mnomad" value="mnomad" class="m">a Nomad (m)</option>
</select>
And then
$('.f').hide();
$('.m').show();
You could also create a CSS stylesheet with: .f{display:none} .m{display:block;}
Your code has a problem: if you have ...
<select id="selGender">
<option value="1" >Male</option>
<option value="2">Female</option>
</select>
... the default selected value is "Male", so if you select it it doesn't trigger onchange event. You can use
<select id="selGender">
<option selected="selected" disabled="disabled">Select gender:</option>
<option value="1" >Male</option>
<option value="2">Female</option>
</select>
Moreover, you have
if (sGender = 1)
You should use
if (sGender == 1)
because you are comparing, not setting values.
About your other question (navigate through a table), you can create a JavaScript function which does that. But I don't understand very well what you want with "the third cell from the left two cells down".
Edit:
If I understand well you have a table like
<table id="table">
<tbody>
<tr>
<td>Skill 1</td>
<td>Skill 2</td>
<td>Skill 3</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</tbody>
</table>
And you want
table(1,1)=Skill 1 cell
table(1,2)=Value 1 cell
table(2,1)=Skill 2 cell
table(2,2)=Value 2 cell
...
Then,
function table(col,row){
return document.getElementById('table').tBodies[0].getElementsByTagName('tr')[row-1].getElementsByTagName('td')[col-1];
}
See it here: http://jsfiddle.net/UGHHd/

Categories

Resources