Show data only when it matches a search - html

I have a search with filter that narrows down data as expected. I would like to implement the functionality of hiding all the data by default, and only show results when they match a search. At the moment if nothing is typed everything is shown. The list will be very long once all data will be added, hence the request. Many thanks.
$(document).ready(function(){
$("#search-box").on("keyup", function() {
var value = $(this).val().toLowerCase();
var filter = $('#search-filter').val().toLowerCase();
if(filter == "listitem") {
$(".listitem").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$(".td-"+filter).filter(function() {
$(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
}
});
$('#search-filter').on("change",function(){
var value = $("#search-box").val().toLowerCase();
var filter = $(this).val().toLowerCase();
if(filter == "listitem") {
$(".listitem").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
} else {
$(".td-"+filter).filter(function() {
$(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="input-group">
<div class="input-group-append">
<select id="search-filter" name="search-filter">
<!--<option value="listitem">All</option>-->
<option value="" disabled selected>Search by</option>
<option value="name">Name</option>
<option value="surname">Surname</option>
</select>
</div>
<input id="search-box" type="text" name="search" placeholder="Type here..." required="required"/>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<tr class="listitem">
<td class="td-name">Jane</td>
<td class="td-surname">Doe</td>
</tr>
<tr class="listitem">
<td class="td-name">Dela</td>
<td class="td-surname">Cruz</td>
</tr>
</tbody>
</table>
</div>

Start by hiding everything. Then use an if statement to test if the search value is not empty, and show the matching elements.
I've also pulled the filtering code out into a named function, so we don't have to repeat it in both event listeners.
.filter() shouldn't be used to execute operations on each element, that should be done with .each(). But in this case you can use it to return a new collection that's just the matching elements, and you can then show them all together.
function filter_items(value, filter) {
$(".listitem, thead").hide();
if (value != '') {
if (filter == "listitem") {
$(".listitem").filter(function() {
return $(this).text().toLowerCase().includes(value)
}).show();
} else {
$(".td-" + filter).filter(function() {
return $(this).text().toLowerCase().includes(value)
}).closest(".listitem").show();
}
if ($(".listitem:visible").length > 0) {
$("thead").show();
}
}
}
$(document).ready(function() {
$("#search-box").on("keyup", function() {
var value = $(this).val().toLowerCase();
var filter = $('#search-filter').val().toLowerCase();
filter_items(value, filter);
});
$('#search-filter').on("change", function() {
var value = $("#search-box").val().toLowerCase();
var filter = $(this).val().toLowerCase();
filter_items(value, filter);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="input-group">
<div class="input-group-append">
<select id="search-filter" name="search-filter">
<!--<option value="listitem">All</option>-->
<option value="" disabled selected>Search by</option>
<option value="name">Name</option>
<option value="surname">Surname</option>
</select>
</div>
<input id="search-box" type="text" name="search" placeholder="Type here..." required="required" />
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<tr class="listitem">
<td class="td-name">Jane</td>
<td class="td-surname">Doe</td>
</tr>
<tr class="listitem">
<td class="td-name">Dela</td>
<td class="td-surname">Cruz</td>
</tr>
</tbody>
</table>
</div>

Related

How to deal with checkboxes in html page?

I want to get the output as single row like group name and visible or not. but in my scenario i am getting different output .
enter image description here
Here is my html code.
#model List<F3CentricMVCApp.Areas.KnowledgeBox.Models.GroupResponse>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<div class="col-12">
<table id="tblSectionGroups" class="table responsive table-striped" bPaginate="true">
<thead>
<tr>
<th width="95%">Groups</th>
<th width="5%" class="no-sort"></th>
</tr>
</thead>
<tbody>
#if (#ViewBag.UnAssidnedGroups is not null)
{
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
#foreach (var unassinedGroup in ViewBag.UnAssidnedGroups)
{
#if (#unassinedGroup.GroupId == #item.Id)
{
<td>
<input type="checkbox" class="chkSectionVisibility" />
</td>
}
else
{
<td>
<input type="checkbox" class="chkSectionVisibility" checked="checked" />
</td>
}
}
</tr>
}
}
</tbody>
</table>
</div>
<script>
$('#tblSectionGroups').DataTable({
"bLengthChange": false,
"pageLength": 5,
"bPaginate": true,
"stripeClasses": [],
"info": false,
language: {
searchPlaceholder: "Type to filter list",
search: ""
},
"order": [],
"columnDefs": [{
"targets": 'no-sort',
"orderable": false,
}]
});
</script>
<div class="col-md-12 text-right">
<button type="button" class="btn btn-custom" tabindex="3" id="btnSave">Save</button>
</div>
Single checkbox for each group in a row is my requirement. any body can guide me how to deal with two collections in a code which is going through 2 foreach statements. but the logic should not be disturbed after all.
Update your foreach code as below i.e.
#if (#ViewBag.UnAssidnedGroups is not null)
{
#foreach (var item in Model)
{
int isUnassigned = 0;
<tr>
<td>#item.Name</td>
#foreach (var unassinedGroup in ViewBag.UnAssidnedGroups)
{
#if (#unassinedGroup.GroupId == #item.Id)
{
<td>
<input type="checkbox" class="chkSectionVisibility" />
</td>
// Setting.
isUnassigned++;
}
}
if (isUnassigned <= 0)
{
<td>
<input type="checkbox" class="chkSectionVisibility" checked="checked" />
</td>
}
</tr>
}
}
Hopefully this will solve your issue.

jQuery code doesn't work on dynamically appended elements

my jquery code doesn't work on dynamically appended elements. It is working fine for the elements that already present there but When I embed a new row using the jQuery append function, then the jquery code no longer works.
Here is the jquery code that embeds a new row
<script>
$(document).ready(function() {
$('#add_row').click(function(){
$('#sale_table').append('<tr><td><select class="form-control" name="item_name[]"><option>Select an Item</option><?php while($item_result = mysqli_fetch_assoc($select_item_query)) { ?><option><?php echo $item_result['item_name']; ?></option><?php } ?></select></td><td><input type="text" class="form-control" name="item_quantity[]" id="sale_item_quantity" placeholder="0.00"></td><td><input type="text" class="form-control" name="item_price[]" id="sale_item_price" placeholder="0.00"></td><td><input type="text" class="form-control" name="item_discount[]" id="sale_item_discount" placeholder="%"></td><td><input type="text" class="form-control" name="item_total_amount[]" id="sale_item_total_amount" placeholder="0.00"></td></tr>');
});
});
</script>
and this is the jquery code that I'm trying to run on appended row. This code doesn't work on appended rows
<script>
$(document).ready(function() {
$('#sale_item_price, #sale_item_quantity').on('keyup', function(){
var sum = 0;
$('.sale-entry > tbody > tr').each(function() {
var qty = $(this).find('#sale_item_quantity').val();
var price = $(this).find('#sale_item_price').val();
var discount = $(this).find('#sale_item_discount').val();
var amount = (qty * price);
if(discount){
amount = amount - discount;
}
$(this).find('#sale_item_total_amount').val(amount);
sum += amount;
});
$('#sale_subtotal_amount').text(sum);
$('#sale_total_amount').text(sum);
$("#sale_item_discount").on('keyup', function() {
var discount = $("#sale_item_discount").val();
$("#sale_item_total_amount").val(sum - discount);
$("#sale_subtotal_amount").text(sum - discount);
$("#sale_total_amount").text(sum - discount);
});
});
});
</script>
and here is the HTML code
<table class="table sale-entry" id="sale_table">
<thead class="thead-light">
<tr>
<th scope="col">Item Name</th>
<th scope="col">Quantity</th>
<th scope="col">Rate</th>
<th scope="col">Discount</th>
<th scope="col">Total Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><select class="form-control" name="item_name[]">
<option>Select an Item</option>
<?php while($item_result = mysqli_fetch_assoc($select_item_query)) { ?>
<option><?php echo $item_result['item_name']; ?></option>
<?php } ?>
</select>
</td>
<td><input type="text" class="form-control" name="item_quantity[]" id="sale_item_quantity" placeholder="0.00"></td>
<td><input type="text" class="form-control" name="item_price[]" id="sale_item_price" placeholder="0.00"></td>
<td><input type="text" class="form-control" name="item_discount[]" id="sale_item_discount" placeholder="%"></td>
<td><input type="text" class="form-control" name="item_total_amount[]" id="sale_item_total_amount" placeholder="0.00"></td>
</tr>
</tbody>
</table>
What could be the issue?
if $('#sale_item_price, #sale_item_quantity').on('keyup'... not working then $(document).on('keyup', '#sale_item_price, #sale_item_quantity',... works.
Here, $('#sale_item_price, #sale_item_quantity') is unaware of DOM changed.
Have a look in example:-
$(document).ready(function() {
$(document).on('keyup', '#sale_item_price, #sale_item_quantity, #sale_item_discount', function() {
var sum = 0;
$('.sale-entry > tbody > tr').each(function() {
var qty = $(this).find('#sale_item_quantity').val();
var price = $(this).find('#sale_item_price').val();
var discount = $(this).find('#sale_item_discount').val();
var amount = (qty * price);
if (discount) {
amount = amount - discount;
}
$(this).find('#sale_item_total_amount').val(amount);
sum += amount;
});
$('#sale_subtotal_amount').text(sum);
$('#sale_total_amount').text(sum);
});
});
$(document).ready(function() {
$('#add_row').click(function() {
$('#sale_table').append('<tr><td><select class="form-control" name="item_name[]"><option>Select an Item</option></select></td><td><input type="text" class="form-control" name="item_quantity[]" id="sale_item_quantity" placeholder="0.00"></td><td><input type="text" class="form-control" name="item_price[]" id="sale_item_price" placeholder="0.00"></td><td><input type="text" class="form-control" name="item_discount[]" id="sale_item_discount" placeholder="%"></td><td><input type="text" class="form-control" name="item_total_amount[]" id="sale_item_total_amount" placeholder="0.00"></td></tr>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table sale-entry" id="sale_table">
<thead class="thead-light">
<tr>
<th scope="col">Item Name</th>
<th scope="col">Quantity</th>
<th scope="col">Rate</th>
<th scope="col">Discount</th>
<th scope="col">Total Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="form-control" name="item_name[]">
<option>Select an Item</option>
</select>
</td>
<td><input type="text" class="form-control" name="item_quantity[]" id="sale_item_quantity" placeholder="0.00"></td>
<td><input type="text" class="form-control" name="item_price[]" id="sale_item_price" placeholder="0.00"></td>
<td><input type="text" class="form-control" name="item_discount[]" id="sale_item_discount" placeholder="%"></td>
<td><input type="text" class="form-control" name="item_total_amount[]" id="sale_item_total_amount" placeholder="0.00"></td>
</tr>
</tbody>
</table>
<button id="add_row" type="button">Add row</button>
<div>sale_subtotal_amount: <span id="sale_subtotal_amount"></span></div>
<div>sale_total_amount: <span id="sale_total_amount"></span></div>

Dynamic row add/delete in Thymeleaf

I have implemented dynamic row add/delete in thymeleaf using jquery. But I am unable to capture the row values as array of json objects.
$(function(){
$('#addMore').on('click', function() {
var data = $("#tab_logic tr:eq(1)").clone(true).appendTo("#tab_logic");
data.find("input").val('');
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
}
});
The table to which dynamic row gets added/deleted is as below:-
<table class="table table-bordered table-hover" id="tab_logic">
<tr class="tr-header">
<label for="requestno">Sales target</label>
<th>Team lead</th>
<th>Sales volume</th>
<th><a href="javascript:void(0);"
style="font-size: 18px;" id="addMore"> <span
class="glyphicon glyphicon-plus"></span></a></th>
</tr>
<tr>
<td>
<input type="text" name="teamLead" class="form-control" ></input>
</td>
<td>
<input type="text" name="salesVolume" class="form-control" ></input>
</td>
<td>
<a href='javascript:void(0);' class='remove'><span
class='glyphicon glyphicon-remove'></span></a>
</td>
</tr>
</table>
You can serialized forms inputs using the serialize() function. This will return a query string that then can be converted to JSON object using JSON.stringify(). So, my recommendation, would be to add everything inside a form and then serialize it.
HTML
<table class="table table-bordered table-hover" id="tab_logic">
<tr class="tr-header">
<label for="requestno">Sales target</label>
<th>Team lead</th>
<th>Sales volume</th>
<th><a href="javascript:void(0);"
style="font-size: 18px;" id="addMore"> <span
class="glyphicon glyphicon-plus"></span></a></th>
</tr>
<form id="myForm>
<tr>
<td>
<input type="text" name="teamLead" class="form-control" ></input>
</td>
<td>
<input type="text" name="salesVolume" class="form-control" ></input>
</td>
<td>
<a href='javascript:void(0);' class='remove'><span
class='glyphicon glyphicon-remove'></span></a>
</td>
</tr>
</form>
</table>
Javascript/jQuery
$(function(){
$('#addMore').on('click', function() {
// Add the row to your form, not the table.
var data = $("#tab_logic tr:eq(1)").clone(true).appendTo("#myForm");
data.find("input").val('');
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
}
});
// Method that will generate the JSON object.
function toJSON() {
var data = $('#myForm').serialize();
console.log(JSON.stringify(data));
}

How to create dynamic scope variables in Angularjs?

I want create the screen like this.
The select dropdowns and input fields should not effect on each other (right now if I select company, that is showing as selected in the next set, it should not like that). How can I implement this?
'use strict';
angular.module('newmonthlyplanning.controllers', [])
.controller('newmonthlyplanningCtrl', ['$scope','$window', '$state', 'serviceFactory', '$compile', '$interval','targetPlanningService',
function ($scope,$window,$state, serviceFactory, $compile,$interval,targetPlanningService) {
$scope.status = '200';
$scope.months = ['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct','Nov','Dec'];
$scope.getAllSectors = function(){
targetPlanningService.getAllsectors().then(function (response) {
$scope.status = response.status;
console.log(response);
if (response.status === 200) {
$scope.sectors = response.data.sector_list;
}
else {
}
}, function (response) {
console.log(response);
if (response.status === 401) {
$state.go('login');
}
});
};
$scope.getcustomers = function(sector){
console.log("selected sector ",sector);
targetPlanningService.getAllCustomers(sector).then(function (response) {
$scope.status = response.status;
console.log(response);
if (response.status === 200) {
$scope.customers = response.data.customer_list;
}
else {
}
}, function (response) {
console.log(response);
if (response.status === 401) {
$state.go('login');
}
});
};
$scope.targetDetails = [];
$scope.getAllCompanies = function(){
targetPlanningService.getAllCompanies().then(function (response) {
$scope.status = response.status;
console.log("companies---> ",response);
if (response.status === 200) {
$scope.companies = response.data.companies;
$scope.targetDetails.push({'companies':$scope.companies,'sectors': $scope.sectors ,'customers': $scope.customers ,'targetss': $scope.targets});
}
else {
}
}, function (response) {
console.log(response);
if (response.status === 401) {
$state.go('login');
}
});
};
$scope.getAllproductIds = function(){
/* var details = {
'company' : $scope.targetDetails.company,
'sector' : $scope.targetDetails.sector
}
console.log("details--->",details);*/
console.log("$scope.targetDetails.company--->",$scope.targetDetails.company);
targetPlanningService.getAllproductIds($scope.targetDetails.company).then(function (response) {
$scope.status = response.status;
console.log("product_ids--->",response);
if (response.status === 200) {
$scope.productids = response.data.item_list;
}
else
{
}
}, function (response) {
console.log(response);
if (response.status === 401) {
$state.go('login');
}
});
};
$scope.targets = [{'pid': '','week1': '', 'week2': '','week3':'','week4':''}];
var i=1;
$scope.addNewChoice = function(id) {
$scope.targetDetails;
i++;
$scope.targets.push({'pid': '','week1': '', 'week2': '','week3':'','week4':''});
};
$scope.removeChoice = function(val) {
console.log("index------>",val);
$scope.targets.splice(val,1);
};
//$scope.targetDetails = [];
console.log("companies at targetDetails------>",$scope.companies);
var i =0;
$scope.addorder = function(){
var object = {};
object['targetss'] = $scope.targets;
// $scope.targetDetails.push({'companies':$scope.companies,'sectors': $scope.sectors ,'customers': '','targetss': $scope.targets});
$scope.targetDetails.push(object);
};
$scope.init = function () {
console.log("present state...",$state.current.name);
if($state.current.name==="monthly"){
$scope.getAllSectors();
// $scope.getnumberOfweeks();
$scope.getAllCompanies();
// $scope.getTargetDetails();
//$scope.getCommentDetails();
}
};
$scope.init();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="padding: 0px" ng-repeat="details in targetDetails">
<div class="row">
<table class="table table-bordered">
<thead>
<tr>
<th>Company</th>
<th>Sector</th>
<th>Customer</th>
</tr>
</thead>
<tbody>
<tr >
<td>
<div>
<select class="form-control" data-ng-model="targetDetails.company" ng-change="getAllproductIds()" style="border: 1px solid skyblue;">
<option value="">Select Company</option>
<option ng-repeat="company in details.companies track by $index" value="{{company}}" >{{company}}</option>
</select>
</div>
</td>
<td >
<div >
<select class="form-control" data-ng-model="targetDetails.sector" ng-change="getcustomers(targetDetails.sector)" style="border: 1px solid skyblue;">
<option value="">Select Sector</option>
<option ng-repeat=" sector in details.sectors track by $index" value="{{sector}}">{{sector}}</option>
</select>
</div>
</td>
<td>
<div >
<select class="form-control" data-ng-model="targetDetails.customer" style="border: 1px solid skyblue;">
<option value="Customer"> Customer</option>
<option ng-repeat=" customer in details.customers track by $index" value="{{customer}}">{{customer}}</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div class="row" style="padding: 0px">
<table class="table table-bordered">
<thead>
<tr>
<th>Product Id</th>
<th >WEEK1</th>
<th >WEEK2</th>
<th >WEEK3</th>
<th >WEEK4</th>
<!-- <th>Total</th> -->
<!-- <th>Status</th> -->
<th >Action</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="target in details.targetss">
<td align="center" >
<select class="form-control" style="width: 120px;border: 1px solid skyblue;" data-ng-model="target.pid" ng-change="getUnitsofProduct(target.pid)">
<option value="">Select pid</option>
<option data-ng-repeat="pid in productids">{{pid}}</option>
</select>
</td>
<td align="center">
<input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week1">
</td>
<td align="center">
<input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week2">
</td>
<td align="center">
<input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week3">
</td>
<td align="center">
<input class="form-control" style="width: 70px" type="text" name="" ng-model="target.week4">
</td>
<!-- <td align="center" >
{{ (target.week1 * 1) + (target.week2 * 1)+ (target.week3 * 1)+ (target.week4 *1)+ (target.week5 *1) }} {{target.uom}}
</td> -->
<!-- <td ng-if="target.status==''"></td>
<td ng-if="target.status==='Pending'"><span style="color: blue">{{target.status}}</span></td>
<td ng-if="target.status==='Rejected'"><span style="color: red">{{target.status}}</span></td>
<td ng-if="target.status==='Accepted'"><span style="color: green">{{target.status}}</span></td> -->
<td align="center">
<button class="add" style="background-color: #008CBA;" data-ng-show="$last" data-ng-click="addNewChoice($parent.$index)">+</button>
<button class="sub" data-ng-click="removeChoice($index)" style="background-color:#f44336;margin:0px;">-</button>
</td>
<td>{{$parent.$index}}</td>
</tr>
</tbody>
</table>
<br>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="padding: 0px">
<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1" >
<button data-ng-click="addorder()" style=" padding: 5px;margin: 0px">Add Order</button>
</div>
</div>
</div>
You can use $index for the purpose.
For example:
<select class="form-control" data-ng-model="targetDetails.company[$index]" ng-change="getAllproductIds()" style="border: 1px solid skyblue;">
<option value="">Select Company</option>
<option ng-repeat="company in details.companies track by $index" value="{{company}}" >{{company}}</option>
</select>
Use in ng-model:
data-ng-model = "targetDetails.company[$index]"
Hope this helps.

state city dropdown not working

I found country state city dropdown code online. But i just wanted state and city. so made some changes, bt its not working properly, this is the edited code, please tell me whts wrong with it?
thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.1 Transitional//EN">
<html>
<font face="Arial,Helvetica,Geneva,Swiss,SunSans-Regular">
<head>
<!--start head-->
<title>State - City Dropdown</title>
<script type="text/javascript">
// State lists
var cities = new Array();
cities['Gujarat'] = new Array('Ahmedabad','Vadodara','Surat');
cities['Rajasthan'] = new Array('Jaisalmer','Chittod','Jaipur');
cities['maharashtra'] = new Array('Mumbai','Pune','Nasik');
// City lists
function setcities() {
stateSel = document.getElementById('state');
cityList = cities[stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setcities();
});
</script>
<fieldset style="width: 300px;">
<legend><strong>Make your selection</strong></legend>
<p>
<!-- <form name="test" method="POST" action="processingpage.php"> -->
<form>
<table>
<tr>
<td style="text-align: left;">States:</td>
<td style="text-align: left;">
<select name="State" id="State" onChange="setcities();">
<option value="Gujarat">Gujarat</option>
<option value="Rajasthan">Rajasthan</option>
<option value="Maharashtra">Maharashtra</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">City:</td>
<td style="text-align: left;">
<select name="City" id="city" onChange="setcities();">
<option value="">Please select a City </option>
</select>
</td>
</tr>
</table>
</form>
</fieldset>
</font></body></html>
javaScript attributes are Case Sensitive
You have Used state for State and maharashtra for Maharashtra Correct it or
Use the following Code,
<!--start head-->
<title>State - City Dropdown</title>
<script type="text/javascript">
// State lists
var cities = new Array();
cities['Gujarat'] = new Array('Ahmedabad','Vadodara','Surat');
cities['Rajasthan'] = new Array('Jaisalmer','Chittod','Jaipur');
cities['Maharashtra'] = new Array('Mumbai','Pune','Nasik');
// City lists
function setcities() {
stateSel = document.getElementById('State');
cityList = cities[stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setcities();
});
</script>
<fieldset style="width: 300px;">
<legend><strong>Make your selection</strong></legend>
<p>
<!-- <form name="test" method="POST" action="processingpage.php"> -->
<form>
<table>
<tr>
<td style="text-align: left;">States:</td>
<td style="text-align: left;">
<select name="State" id="State" onChange="setcities();">
<option value="Gujarat">Gujarat</option>
<option value="Rajasthan">Rajasthan</option>
<option value="Maharashtra">Maharashtra</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">City:</td>
<td style="text-align: left;">
<select name="City" id="city" onChange="setcities();">
<option value="">Please select a City </option>
</select>
</td>
</tr>
</table>
</form>
</fieldset>
</font></body></html>
The html component you declared is with id as 'State' but you reading for 'state'. Best practice will be using jQuery in the project. jQuery will take care of the cross browser issues and will be handy while coding.
Change the id state to State and change cities['maharashtra'] to cities['Maharashtra']
Try this code:
DEMO
function setcities() {
var stateSel = document.getElementById("State");
console.log(stateSel);
cityList = cities[stateSel.value];
changeSelect('city', cityList, cityList);
}