I am using an onchange function for my select tag to filter a list of items based on the select option value.
The code I have currently have only works for a single select tag but I want it to be able to work for multiple select tags, which would require each select option value to cooperate.
For example, if I have "Departments" and "Locations" as tags for each item in the list and I choose Department -> IT and Location -> New York in the select tags, I only want to see a list of IT departments in New York.
I am having a hard time understanding how I would do this properly. I would assume some sort of for loop to get each select tag and then get the value of the current option in each select tag and only show the list items if they meet the select option value criteria.
I would appreciate any help of how I could achieve this!
HTML:
<select class="filterTags" id="filterDepartment">
<option>All</option>
<option>IT</option>
<option>Marketing</option>
</select>
<select class="filterTags" id="filterLocation">
<option>All</option>
<option>New York</option>
<option>Washington</option>
</select>
<div class="tags-container">
<div class="tags tags-departments">
<span class="department tag">IT</span>
<span class="department tag">Marketing</span>
</div>
<div class="tags tags-locations">
<span class="location tag">New York</span>
<span class="location tag">Washington</span>
</div>
</div>
JavaScript:
var selectClass = document.getElementsByClassName("filterTags")
selectClass = selectClass[0]
selectClass.onchange= function() {
var filterOptions, tags, i, span;
filterOptions = this.options[this.selectedIndex].value
tags = document.getElementsByClassName("tags-departments")
span = document.querySelectorAll(".department")
for (i = 0; i < tags.length; i++) {
if (span) {
if (span[i].innerHTML.indexOf(filterOptions) > -1) {
span[i].parentNode.parentNode.parentNode.style.display = ""
} else {
span[i].parentNode.parentNode.parentNode.style.display = "none"
}
if(filterOptions == "All") {
span[i].parentNode.parentNode.parentNode.style.display = ""
}
}
}
}
Well, I would suggest the following logic, add a function to the onchange event of both selection elements, the function would:
Detect the ID of the selection element that triggered the event.
Based on the selection element that triggered the change, loop over the corresponding span elements.
For each span, based on the selected value in the selection, check if it should be displayed or not.
Here is a fully working code and a working example with it:
//Iterate the selection elements and add the function to the 'change' event
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++)
{
sels[i].addEventListener('change', function() {
//get the selection id of the selected that was change - this returns the selection element
selectionID = this.id;
if(selectionID === "filterDepartment")
{
//the value of the selected department
var selectedDepartment = document.getElementById("filterDepartment").value
//we will iterate the departments spans and check their text value agains the selected department value (or if the value is 'All' we dont need to check//
var spans = document.getElementsByClassName('tags tags-departments')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedDepartment == "All" || spans[i].innerText == selectedDepartment)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
if(selectionID === "filterLocation")
{
var selectedLocation = document.getElementById("filterLocation").value;
var spans = document.getElementsByClassName('tags tags-locations')[0].getElementsByTagName('span');
for(var i = 0; i < spans.length; i++)
{
if(selectedLocation == "All" || spans[i].innerText == selectedLocation)
{
spans[i].style.display = "block";
}
else
{
spans[i].style.display = "none";
}
}
}
}, false);}
im adding table row data using json response. here is my code
var i;
for (i = 0; i < result.length; i++) {
$.get('LoadserviceSplit', {
"sectcode" : result[i]
},
function (jsonResponse) {
if (jsonResponse != null) {
var table2 = $("#table_assign");
$.each(jsonResponse, function (key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['serviceId']);
rowNew.children().eq(1).text(value['title']);
rowNew.children().eq(2).html('<input type="text" id="date_set" name="date_set"/>');
rowNew.children().eq(3).html('<input type="text" id="date_set1" name="date_set1"/>');
rowNew.children().eq(4).html('<input type="text" id="date_set2" name="date_set2"/>');
rowNew.children().eq(5).html('<select class="status1" id="status1">');
rowNew.appendTo(table2);
});
}
});
var pass_unit_code = "001";
$.get('LoadDivisionCodeServlet', { //call LoadDivisionCodeServlet controller
unitCode : pass_unit_code //pass the value of "sample" to unitCode:
}, function (jsonResponse) { //json response
var select = $('#status1'); //select #status1 option
select.find('option').remove(); //remoev all item in #divcode option
$.each(jsonResponse, function (index, value) {
$('<option>').val(value).text(value).appendTo(select); //response from JSON in array value{column:value,column:value,column:value}
});
});
}
it works fine except the select tag part. only the first row of table have value. the rest has no value. i want all drop-down list inside the table has same value.. can anyone help me about this.
Take a look at
rowNew.children().eq(5).html('<select class="status1" id="status1">');
You're creating new select elements in a $.each and assigning the same id, that is status1 to all of them.
Then you're selecting the select element that has an id of status1 like
var select = $('#status1'); //select #status1 option
Therefore, only the first select element will be selected.
EDIT:
Your question is not completely clear.
However, this is how you can add different Id for select inside each of your <td>
Replace this
rowNew.children().eq(5).html('<select class="status1" id="status1">');
With something like
rowNew.children().eq(5).html('<select class="status1" id="status'+key+'">');
So this will have different Ids.
I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}
I am supporting some legacy code and having some issues in implementing a new feature.
I have 2 multiple select options, first one showing a list of states, second showing a list of cities. The idea is that the list of cities will be filtered dependant on the selected states in the first select.
Currently the cities are contained in a javascript array which is used in an if statement to attach the relevant options to the select, howeber this only works on a single state selection.
How can I filter the cities on multiple state selections?
I have tried numerous if statement combinations with no luck. My jquery knowledge is obviously lacking and haven't found anything similar in google/stackoverflow - however I appreciate I may be approaching this from the wrong angle.
<form name="newform">
<select multiple size="10" name="getStateSelect" id="getStateSelectID" onchange="GetSeries(document.newform.getStateSelect.options [document.newform.getStateSelect.selectedIndex].value);">
<option value="1">Alaska</option>
<option value="2">Arizona</option>
<option value="3">Californa</option>
</select>
<br />
<br />
<select id="getCitySelect" multiple="multiple" size="10"></select>
</form>
var fsArray = [{id: 1,stateid: 1,cityname: "Anchorage"},
{id: 2,stateid: 1,cityname: "Fairbanks"},
{id: 3,stateid: 1,cityname: "Wasilla"},
{id: 4,stateid: 2,cityname: "Flagstaff"},
{id: 5,stateid: 2,cityname: "Phoenix"},
{id: 6,stateid: 2,cityname: "Tucson"},
{id: 7,stateid: 3,cityname: "Fremont"},
{id: 8,stateid: 3,cityname: "Lakeport"},
{id: 9,stateid: 3,cityname: "Los Angeles"}];
function GetSeries(i) {
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
for (j in fsArray) {
if (fsArray[j].stateid == i) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
http://jsfiddle.net/fcp3h7mw/1/
Any help greatly appreciated!
Thanks
I just added a for loop on the getStateSelectID values to check if each element for selection status, if selected it runs your loop to add the cities.
the fiddle: http://jsfiddle.net/fcp3h7mw/5/
javascript:
var fsArray = [
{id:1,stateid:1,cityname:"Anchorage"},
{id:2,stateid:1,cityname:"Fairbanks"},
{id:3,stateid:1,cityname:"Wasilla"},
{id:4,stateid:2,cityname:"Flagstaff"},
{id:5,stateid:2,cityname:"Phoenix"},
{id:6,stateid:2,cityname:"Tucson"},
{id:7,stateid:3,cityname:"Fremont"},
{id:8,stateid:3,cityname:"Lakeport"},
{id:9,stateid:3,cityname:"Los Angeles"}
];
function GetSeries(i) {
var id = document.getElementById("getStateSelectID");
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
var states = 0;
for (states=0; states < id.length; states++) {
if(id[states].selected){
for (j in fsArray) {
if (fsArray[j].stateid == id[states].value) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
}
}
Markup: I also took out a lot of your function call in the markup
<select multiple size="10" name="getStateSelect" id="getStateSelectID" onchange="GetSeries();">
I've updated your code to be able to select multiple states and display the correct cities.
Essentially, you needed to get a list of options with attribute "selected" and store the option values in an array (onchange)
Afterwards, you would iterate through the new array and match against the values in the array instead of a single value.
Here's the updated code: http://jsfiddle.net/biz79/fcp3h7mw/3/
var fsArray = [
{id:1,stateid:1,cityname:"Anchorage"},
{id:2,stateid:1,cityname:"Fairbanks"},
{id:3,stateid:1,cityname:"Wasilla"},
{id:4,stateid:2,cityname:"Flagstaff"},
{id:5,stateid:2,cityname:"Phoenix"},
{id:6,stateid:2,cityname:"Tucson"},
{id:7,stateid:3,cityname:"Fremont"},
{id:8,stateid:3,cityname:"Lakeport"},
{id:9,stateid:3,cityname:"Los Angeles"}
];
function getSeries() {
var SeriesSelectBox = document.getElementById("getCitySelect");
SeriesSelectBox.options.length = 0;
var arr = getStateSelected();
for (var i = 0; i< arr.length; i++) {
for (var j in fsArray) {
if (fsArray[j].stateid == arr[i]) {
var seriesLength = SeriesSelectBox.options.length;
SeriesSelectBox.options[seriesLength] = new Option(fsArray[j].cityname, fsArray[j].id);
}
}
}
}
function getStateSelected() {
var sel = document.querySelectorAll('#getStateSelectID option');
var arr = [];
for (var i = 0; i< sel.length; i++ ) {
if ( sel[i].selected ) {
arr.push(sel[i].value);
}
}
return arr;
}
Hope this helps. Let me know if you have questions.
I have a Dropdown box, Which is getting filled by values from mySQL database, here is the part of the script that I am using to fill the drop down.
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
and here is HTML,
<select name="package" name="package-id" id="package-id">
<option></option>
</select>
But the dropdown shows the values as 1234 where as I am expecting them as,
1
2
3
4
Any workarounds for this?
try Changing This:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id option').append(details.aaData[i].id);
}
to this:
var details = JSON.parse(data);
console.log(details);
for ( i = 0; i < details.aaData.length; i++) {
console.log(details.aaData[i].id);
$('select#package-id').append("<option value='"+details.aaData[i].id+"'>"+details.aaData[i].id+"</option>");
}
it looks right now like you may be creating a bunch of option inside the blank option.