+ 2

JavaScript Help needed

Have a look at the code. Explained with example of the code. https://code.sololearn.com/WUwd146mtYCb/#html

2nd Apr 2017, 2:14 AM
theBlueGHOST
theBlueGHOST - avatar
8 Answers
+ 6
//Replace your select with this select <select id="sort-by" onchange="onChange()"> <option value="searchBy" selected disabled>Search by</option> <option value="countries">Countries</option> <option value="cities">Cities</option> </select> //Add this code to your JS to detect what column of tr to sort upon var selectedIndex = 0; //Default countries function onChange(){ var value = document.getElementById("sort-by").value; if(value == 'cities'){ selectedIndex = 1; } else selectedIndex = 0; } //Change one line in your existing function myFunction from td = tr[i].getElementsByTagName("td")[0]; //to td = tr[i].getElementsByTagName("td")[selectedIndex];
2nd Apr 2017, 2:39 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 6
Remove selectedIndex declaration inside myfunction as it's declared outside and we want to use that. Also, replace the HTML part as i said. It will work.
2nd Apr 2017, 3:06 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 5
Check if this is working for you or not. https://code.sololearn.com/WZk9sq7Ar5H2/?ref=app
2nd Apr 2017, 3:29 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 5
No problem @theBlueGHOST. Now i am deleting my code.
2nd Apr 2017, 3:45 AM
Ashwani Kumar
Ashwani Kumar - avatar
+ 2
@ashwani it didnt work, can you please write the whole javascript code to me please? function myFunction() { // Declare variables var input, filter, table, tr, td, selectedIndex, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); selectedIndex = 0; // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[selectedIndex]; if (td) { if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } var selectedIndex = 0; //Default countries function onChange(){ var value = document.getElementById("sort-by").value; if(value == 'cities'){ selectedIndex = 1; } else selectedIndex = 0; } }
2nd Apr 2017, 3:04 AM
theBlueGHOST
theBlueGHOST - avatar
+ 2
tried as you said, not working. :(
2nd Apr 2017, 3:24 AM
theBlueGHOST
theBlueGHOST - avatar
+ 2
Thanks a lot mate. It helped. I was having a syntax error with my own code. Really appreciate your help.
2nd Apr 2017, 3:41 AM
theBlueGHOST
theBlueGHOST - avatar
+ 1
The fix that comes to my head right now is to change the 0 to document.getElementById("sort-by").selectedIndex-1 and checking if the selected index is 0 in case that the user doesn't select any option or selects the default.
2nd Apr 2017, 2:42 AM
Luca Garrera