Show all hidden table rows when selecting empty option in select box - javascript

So far my code works fine but when I select empty select option, all the rows in my table should be visible (in other words reset the table to initial state) again. How do I do it?
I've seen this (JQuery Selector for table with hidden row - alternate row colouring) but couldn't apply to my structure.
Thanks
JQUERY:
$(document).ready(function()
{
$("#cars").change(function()
{
var selected = $(this).val();
if (selected != '')
{
var values = $.map($('#cars>option'), function(e) { return e.value; });
values.forEach(function(item)
{
if (item != '')
{
if (selected == item)
{
$('.' + item).show();
}
else
{
$('.' + item).hide();
}
}
else
{
//Show all rows
}
});
}
});
});
HTML:
<table border="1">
<tr id="header">
<td>1</td>
<td><select id="cars">
<option value=""></option>
<option value="bmw">BMW</option>
<option value="audi">AUDI</option>
<option value="mercedes">MERCEDES</option>
</select></td>
</tr>
<tr class="bmw">
<td>3.16</td>
<td>BMW</td>
</tr>
<tr class="bmw">
<td>3.18</td>
<td>BMW</td>
</tr>
<tr class="bmw">
<td>3.00</td>
<td>BMW</td>
</tr>
<tr class="audi">
<td>A1</td>
<td>AUDI</td>
</tr>
<tr class="audi">
<td>A3</td>
<td>AUDI</td>
</tr>
<tr class="mercedes">
<td>300sel</td>
<td>MERCEDES</td>
</tr>
</table>

Working Fiddle
Add this else part in your code
else {
$('table tr').show();
}

just place this:
$(this).closest('table').find('tr:hidden').show();
Although you can simplify your code like this:
$("#cars").change(function(){
$(this).closest('table').find('tr:gt(0)').hide();
this.value !== '' ? $('.'+this.value).show() : $(this).closest('table').find('tr:hidden').show();
});

Your code is unnecessarily complex. You don't need map, foreach, etc.
$("#cars").change(function()
{
$('tr[id!=header]').hide()
if (this.value)
$('.' + this.value).show()
else
$('tr').show()
}
)

Related

Sorting an HTML Table using one input field and one Select - Javascript

This script works for sorting an HTML Table using two standard input fields, but I am trying to use a select as the second input field and I cant seem to find a way to call the function onchange for the select specialtyid id to work as an input. Please help.
Thank you very much!
Here is the code:
<script src="https://code.jquery.com/jquery-1.7.1.js"></script>
<input type="text" id="infoid" placeholder="Contractor Name">
<select id="specialtyid" onChange=" ">
<option value="">Select Contractor Type:</option>
<option value="Electrician">Electrician</option>
<option value="HVAC">HVAC</option>
<option value="Plumber">Plumber</option>
</select>
<p></p>
<table id="table">
<tr>
<td>Jack Doe</td>
<td>HVAC</td>
</tr>
<tr>
<td>Jack Doe JR</td>
<td>Plumber</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>Electrician</td>
</tr>
<tr>
<td>Rick Pro</td>
<td>Plumber</td>
</tr>
</table>
$(window).load(function() {
var $rows = $('#table tr'),
info,
specialty;
$('input').keyup(function() {
infovalue = $('#infoid').val().toLowerCase(),
specialtyvalue = $('#specialtyid').val().toLowerCase();
$rows.each(function(index, tr) {
info = $(tr).find('td:nth-of-type(1)').text().toLowerCase(),
specialty = $(tr).find('td:nth-of-type(2)').text().toLowerCase();
if ((info.indexOf(infovalue) != -1) && (specialty.indexOf(specialtyvalue) != -1)) {
$(this).show();
} else {
$(this).hide();
}
});
if ((searchVal1 === '') && (searchVal2 === '')) {
$rows.show();
}
});
});
Here is few things to change:
Change the selctor #table for table
Change the condition to fit with your variables (infovalue === '') && (specialtyvalue === '')
Create a function to attach on both events
Add the event $('#specialtyid').change(filterTable);
$(window).load(function() {
var $rows = $('table tr'),
info,
specialty;
function filterTable(){
infovalue = $('#infoid').val().toLowerCase(),
specialtyvalue = $('#specialtyid').val().toLowerCase();
$rows.each(function(index, tr) {
info = $(tr).find('td:nth-of-type(1)').text().toLowerCase(),
specialty = $(tr).find('td:nth-of-type(2)').text().toLowerCase();
if ((info.indexOf(infovalue) != -1) && (specialty.indexOf(specialtyvalue) != -1)) {
$(this).show();
} else {
$(this).hide();
}
});
if ((infovalue === '') && (specialtyvalue === '')) {
$rows.show();
}
}
$('input').keyup(filterTable);
$('#specialtyid').change(filterTable);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<input type="text" id="infoid" placeholder="Contractor Name">
<select id="specialtyid" onChange=" ">
<option value="">Select Contractor Type:</option>
<option value="Electrician">Electrician</option>
<option value="HVAC">HVAC</option>
<option value="Plumber">Plumber</option>
</select>
<p></p>
<table>
<tr>
<td>Jack Doe</td>
<td>HVAC</td>
</tr>
<tr>
<td>Jack Doe JR</td>
<td>Plumber</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>Electrician</td>
</tr>
<tr>
<td>Rick Pro</td>
<td>Plumber</td>
</tr>
</table>

How to hide, show and re-hide and re-show tr in table in HTML

Supposedly, I have on select option. The table should only displays a row in a table based on my option in select tag.
Let say I choose the first option, and its value is A, other rows which don't contains "A" (only) will be hidden. But when it comes to option BB, supposedly the table only displays the row which only contains text "BB", the third row is successfully hidden, but then the first row is still there.
$(document).ready(function() {
$("button").click(function() {
var searchString = $('#enter').find(":selected").text();
$("#mytable tr td:contains('" + searchString + "')").each(function() {
if ($(this).text() != searchString) {
$(this).parent().hide();
} else {
$(this).parent().show();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
<option value="A">A</option>
<option value="BB">BB</option>
<option value="CCC">CCC</option>
</select>
<button>Set text content for all p elements</button>
<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>AA</td>
<td>BB</td>
<td>CC</td>
</tr>
<tr>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
</table>
Is my jQuery correct or it does have a logical error?
For this to work you need to perform an exact match on the contents of the td elements. :contains by default is a greedy match, so searching for A will match all three rows. To fix this you can use filter():
$("button").click(function() {
var searchString = $('#enter').val();
$("#mytable tr").hide().find('td').filter(function() {
return $(this).text().trim() === searchString;
}).parent().show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
<option value="A">A</option>
<option value="BB">BB</option>
<option value="CCC">CCC</option>
</select>
<button>Set text content for all p elements</button>
<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>AA</td>
<td>BB</td>
<td>CC</td>
</tr>
<tr>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
</table>
Your code doesn't account for when a row has been hidden, but then one of the table-cells' siblings do not contain the string. For instance, the each function reaches CC, which doesn't contain BB, and then the parent is shown again.
I've amended your code, hopefully this helps.
$(document).ready(function() {
$("button").click(function() {
var searchString = $('#enter').find(":selected").text();
$("#mytable tr td").each(function() {
if ($(this).text().indexOf() > -1 || $(this).siblings().text().indexOf(searchString) > -1 ) {
$(this).parent().hide();
} else {
$(this).parent().show();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="enter">
<option value="A">A</option>
<option value="BB">BB</option>
<option value="CCC">CCC</option>
</select>
<button>Set text content for all p elements</button>
<table border="0" align="center" width="45%" cellpadding="2" cellspacing="2" id="mytable">
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>AA</td>
<td>BB</td>
<td>CC</td>
</tr>
<tr>
<td>AAA</td>
<td>BBB</td>
<td>CCC</td>
</tr>
</table>
You have to change small thing in your code..
Make your logic like :
1) First Hide all <tr>
2) Then search for the string in <tr> and show them ..
Example in your code :
$(document).ready(function() {
$("button").click(function() {
var searchString = $('#enter').find(":selected").text();
$('tr').hide(); //<------First Update
$("#mytable tr td:contains('" + searchString + "')").each(function() {
$(this).parent().show(); //<------Second update
});
});
});
I do the complete coding also . You can check it..
JSFiddle link : https://jsfiddle.net/cebL4jpv/5/
your selector "#mytable tr td:contains('" + searchString + "')" starts the loop right
after it find the element. which was causing the issue . try below
` $(document).ready(function() {
$("button").click(function() {
var searchString = $('#enter').find(":selected").text();
var trs = $('#mytable').find('tr');
trs.each(function(i, ele) {
$(ele).children('td').each(function(j, ele1) {
if ($(ele1).text() != searchString) {
$(ele1).parent().hide();
} else {
$(ele1).parent().show();
return false;
}
})
})
});
});`

Using Toggle to Display information in table once selection is made

I have really been struggling with this for a while now and I am down to the wire and really need help. I want to display an 1 row / 4 column table on the page with a single drop down menu in the far left column, then based on what is selected in from that drop down I want specific information to display in the remaining 1 row / 3 columns. Here is what I have to far I just cant get my data to display in the columns I want them to.
<html>
<body onLoad="hideAll()">
<script>
function toggleOption(thisselect) {
var selected = thisselect.options[thisselect.selectedIndex].value;
toggleRow(selected);
}
function toggleRow(id) {
var row = document.getElementById(id);
if (row.style.display == '') {
row.style.display = 'none';
}
else {
row.style.display = '';
}
}
function showRow(id) {
var row = document.getElementById(id);
row.style.display = '';
}
function hideRow(id) {
var row = document.getElementById(id);
row.style.display = 'none';
}
function hideAll() {
hideRow('optionA');
hideRow('optionB');
hideRow('optionC');
hideRow('optionD');
}
</script>
<table>
<tbody>
<tr>
<th>Size</th>
<th>Part Number</th>
<th>Description</th>
<th>Material</th>
</tr>
<tr>
<td>
<select id="options" onchange="toggleOption(this)">
<option value="optionA">3/16"</option>
<option value="optionB">1/4"</option>
<option value="optionC">5/16"</option>
<option value="optionD">3/8"</option>
</select>
</td>
<tr id="optionA"><td>3BMH</td><td>Brass Hose Mender</td><td>Brass</td></tr>
<tr id="optionB"><td>4BMH</td><td>Brass Hose Mender</td><td>Brass</td></tr>
<tr id="optionC"><td>5BMH</td><td>Brass Hose Mender</td><td>Brass</td></tr>
<tr id="optionD"><td>6BMH</td><td>Brass Hose Mender</td><td>Brass</td></tr>
</tr>
</tbody>
</table>
</body>
</html>
The problem you are encountering is that your rows (tr) should be cells (td), but this is a very bad approach, what you should do is to use only a row whit four cells inside, the first one with your select and the others empty, and then inject your data to those (just change the innerHTML of your td), here is a example:
<html>
<head>
<script>
function toggleoption(opt) {
var selected = opt.options[opt.selectedIndex].value;
if ("optiona" === selected) {
document.getElementById("partn").innerHTML = "3BMH";
document.getElementById("desc").innerHTML = "Brass Hose Mender";
document.getElementById("mat").innerHTML = "Brass";
} else if ("optionb" === selected) {
document.getElementById("partn").innerHTML = "4BMH";
document.getElementById("desc").innerHTML = "Brass Hose Mender";
document.getElementById("mat").innerHTML = "Brass";
} else if ("optionc" === selected) {
document.getElementById("partn").innerHTML = "5BMH";
document.getElementById("desc").innerHTML = "Brass Hose Mender";
document.getElementById("mat").innerHTML = "Brass";
} else if ("optiond" === selected) {
document.getElementById("partn").innerHTML = "6BMH";
document.getElementById("desc").innerHTML = "Brass Hose Mender";
document.getElementById("mat").innerHTML = "Brass";
}
}
</script>
</head>
<body>
<table>
<tbody>
<tr>
<th>Size</th>
<th>Part Number</th>
<th>Description</th>
<th>Material</th>
</tr>
<tr>
<td>
<select id="options" onchange="toggleoption(this)">
<option value="optiona">3/16"</option>
<option value="optionb">1/4"</option>
<option value="optionc">5/16"</option>
<option value="optiond">3/8"</option>
</select>
</td>
<td id="partn"></td>
<td id="desc"></td>
<td id="mat"></td>
</tr>
</tbody>
</table>
</body>
</html>
Of course this code can be largely improved and i'll strongly recommend the use of jquery, but that is up to you.

Once button is click the dropdown will reset

I have this script:
$(function () {
/* function for dynamic numbering */
function updateRowOrder() {
$('td.id').each(function (i) {
$(this).text(i + 1);
});
}
/* if input textValue get press keyboard enter */
$("#textValue").keydown(function (e) {
if (e.keyCode == 13) {
/* if get so trigger to addBtn */
$("#addBtn").trigger("click");
$(this).val("");
}
});
$(document).on("click", "#addBtn, .delRow ", function (e) {
/* if document clicked is addBtn */
if ($(this).is("#addBtn")) {
/* Append template script to table tbody */
$($("#template").html()).appendTo("#dataTables-example tbody");
/* Append textValue value to class rowValue and change classname */
$(".rowValue").append($("#textValue").val()).attr("class", "rowValues");
$(".taskValue").append($("#task").val()).attr("class", "taskValues");
$(".roleValue").append($("#role").val()).attr("class", "roleValues");
var appendComma = ($(".roleValue1").val() == '') ? '' : ' , ';
$(".roleValue1").append(appendComma + $("#id_select").val()).attr("class", "roleValues");
/* Update Numbering */
updateRowOrder();
}
else {
/* Just remove the tr on the click of a mouse */
$(this).closest("tr").remove();
/* Update Numbering */
updateRowOrder();
}
$('.up, .down').click(function(e){
e.preventDefault();
var row = $(this).parents("tr:first");
//selects all of row's tds except position number
// var row = $(this).parents("tr:first");
// selects the entire row
if ($(this).is(".up")) {
row.insertBefore(row.prev());
}
else if ($(this).is(".down")){
row.insertAfter(row.next());
}
else{
}
$('tbody tr[class="move"] td:first-child').each(function(idx, item) {
$(this).text(idx+1);
});
});
/* clearing input textValue */
$("#textValue").val("");
$('select option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected');
});
});
I include here that when addBtn click the drop down o select tag will reset into its default value.
This code:
$('select option').filter(function(i){ return this.hasAttribute('selected') }).prop('selected', 'selected');
And this is my sample table:
<table class="table table-bordered" id="dataTables-example">
<thead>
<tr>
<td>Activity</td>
<td><input type="text" id="textValue" class="typeahead form-control"/></td>
</tr>
<tr>
<td>Task Code</td>
<td>
<select name="" id="task" class="selectpicker form-control">
<option value="default" disabled="disabled" selected="selected">Default</option>
<?php
foreach($tasktype as $task)
{
?>
<option value="<?=$task['TaskCode']?>"><?=$task['TaskCode']?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Primary Role Code</td>
<td>
<select name="" id="role" class="selectpicker form-control">
<option value=""></option>
<?php
foreach($rolecode as $role)
{
?>
<option value="<?=$role['RoleName']?>"><?=$role['RoleName']?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Secondary Role Code</td>
<td>
<select id="id_select" class="selectpicker form-control" multiple data-live-search="true">
<?php
foreach($rolecode as $role)
{
?>
<option value="<?=$role['RoleName']?>"><?=$role['RoleName']?></option>
<?php
}
?>
</select>
</td>
</tr>
</thead>
</table>
<button type="button" class="btn btn-primary" id="addBtn"><i class="fa fa-plus fa-fw"></i>Add</button>
When I try it, I select values then click the Add button but still it not reset but instead it display the one I selected. And when I add again without choosing anything in the drop down, the value is null or no value.
I think it is working at the back-end but not working on the one I display.
Anyone tell me what is the problem?
Set the value on the select, not the selected property on the option.
function displaymessage() {
$("select").each(function() { this.selectedIndex = 0 });}
This Will reset the drop down value to index number 0.

Change and Update parameter value when Onchange combobox triggered

I have a problem to change url parameter when event onchange triggered in combobox.
Here is the preview :
My default url like this :
http://reserv_book.php?id=1 the number id is according to row (from database).
When i select in Cart combobox i want to add parameter cart=standard or cart=extra according to combobox value.
So URL update like this :
http://reserv_book.php?id=1&cart=standard
When i select in Caddy combobox i want to add parameter caddy=standard or caddy=extra according to combobox value.
So URL update like this :
http://reserv_book.php?id=1&cart=standard&caddy=standard
Here is my function that called when onChange event in combobox triggered.
function changeValue(type, id) {
var valCart = document.getElementById("cart").value;
var valCaddy = document.getElementById("caddy").value;
if (type == "cart") {
//alert("Cart : "+val+" , "+id);
$("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&caddy="+ valCaddy +"&cart=";
if (valCart == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
} else {
//alert("Caddy : "+val+" , "+id);
$("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&cart="+ valCart +"&caddy=";
if (valCaddy == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
}
}
And this is html file in combobox :
<table width="100%" class="ry-table-gold" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<th>No.</th>
<th>Date</th>
<th>Time</th>
<th>Player(s)</th>
<th>Price</th>
<th>Caddy</th>
<th>Cart</th>
<th> </th>
</tr>
<tr>
<td>1</td>
<td>Oct 28 2013</td>
<td>14:50</td>
<td>3</td>
<td>IDR 450,000.0</td>
<td>
<select id="caddy" onchange="changeValue('caddy',1)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
<select id="cart" onchange="changeValue('cart',1)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
Book Now
</td>
</tr>
<tr>
<td>2</td>
<td>Oct 10 2013</td>
<td>14:00</td>
<td>3</td>
<td>IDR 700,000.0</td>
<td>
<select id="caddy" onchange="changeValue('caddy',2)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
<select id="cart" onchange="changeValue('cart',2)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>
</td>
<td>
Book Now
</td>
</tr>
</tbody>
</table>
Another problem is, if the data cart and caddy in first row changed. It affect to another row.
You need to find closest tr and search for links inside the table row. Since you are using inline handlers you need to pass additional argument.
function changeValue(type, id, element) {
var valCart = $("#cart").val(); //use val to get the value of select.
var valCaddy = $("#caddy").val();
if (type == "cart") {
//alert("Cart : "+val+" , "+id);
$(element).closest("tr").find("a.book").each(function() {
var link = "reserv_book.php?id="+id+"&caddy="+ valCaddy +"&cart=";
if (valCart == "standard") {
$(this).attr("href", link + 'standard');
} else {
$(this).attr("href", link + 'extra');
}
});
} else {
...
//same here
}
}
HTML
<select id="cart" onchange="changeValue('cart',1, this)">
<option value="standard">Standard</option>
<option value="extra">Extra</option>
</select>

Categories

Resources