How to add value from select option with array - javascript

I have create bellow code and now i want to add value inside select option. Curently i am not getting value in all there drop downbox. For example you can set your option value to help me.
I have created array like this way:
var d = new Array("Any","D01 Boat Quay / Raffles Place","D02 Chinatown / Tanjong Pagar","D03 Alexandra / Commonwealth","D04 Harbourfront / Telok Blangah");
var options = '';
for (var i = 0; i < d.length; i++) {
options += '<option>' + d[i] + '</option>';
}
$("#TypeList1").html(options);
sb2.sync();
I have tried with this code:
var dd = {
Any : 'Any',
1 : 'D01 Boat Quay / Raffles Place',
2 : 'D02 Chinatown / Tanjong Pagar',
36 : 'D03 Alexandra / Commonwealth',
37 : 'D04 Harbourfront / Telok Blangah',
38 : 'D05 Buona Vista / West Coast'
};
var select = document.getElementById("TypeList1");
for(index in dd) {
select.options[select.options.length] = new Option(dd[index], index);
}
MY CODE:
<!doctype html>
<html>
<head>
<title>Custom Styled Selectbox</title>
<link rel="stylesheet" href="http://www.roblaplaca.com/docs/custom-selectbox/css/customSelectBox.css" />
<!--<link rel="stylesheet" href="customSelectBox.css" />-->
</head>
<body class="noJS">
<script type="text/javascript">
try{Typekit.load();}catch(e){}
var bodyTag = document.getElementsByTagName("body")[0];
bodyTag.className = bodyTag.className.replace("noJS", "hasJS");
</script>
<style type="text/css">
.hasJS select.custom1 {
position: absolute;
left: -999em;
}
</style>
<div class="grid-system clearfix">
<div class="row">
<div class="col span-9">
<div class="example clearfix">
<select class="custom interactive" id="properties">
<!--<option value="selectone">Select a Type</option>-->
<option value="One" selected>One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
</select>
<select class="custom interactive" id="TypeList">
<option selected>Any</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
</select>
<select class="custom1 interactive1" id="TypeList1">
</select>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.js"></script>
<script src="http://www.roblaplaca.com/docs/custom-selectbox/js/SelectBox.js"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="jquery.jscrollpane.js"></script>
<script src="SelectBox.js"></script> -->
<script type="text/javascript">
$(function() {
window.prettyPrint && prettyPrint()
/*
This is how initialization normally looks.
Typically it's just $("select.custom"), but to make this example more clear
I'm breaking from the pattern and excluding interactive
*/
var sb, sb2;
$("select.custom").not(".interactive").each(function() {
sb = new SelectBox({
selectbox: $(this),
height: 150,
width: 200
});
});
$("select.custom1").not(".interactive").each(function() {
sb2 = new SelectBox({
selectbox: $(this),
height: 150,
width: 250
});
});
/*
Adding some extra functionality for "interactive" selects
*/
var TypeList = {
//selectone: ["Any"],
'One': ["Any", "Landed", "Condominium", "HDB", "Others"],
'Two': ["Any", "Landed", "Condominium", "HDB", "Others"],
'Three': ["Any", "Industrial", "Retail", "Land", "Office", "Others"],
'Four': ["Any", "Industrial", "Retail", "Land", "Office", "Others"]
}
var defaultSelectboxSettings = {
height: 150,
width: 150
};
var country_SB = null,
city_SB = null;
$("select.interactive").each(function() {
if ($(this).attr("id") == "properties") {
country_SB = new SelectBox($.extend(defaultSelectboxSettings, {
selectbox: $(this),
changeCallback: function(val) {
if (TypeList[val]) {
city_SB.enable();
updateCities(val);
}
if (val == "selectone") {
city_SB.disable();
}
<!------------------------------Code By Me---------------------------->
var getType = jQuery( "#TypeList option:selected" ).text();
if(getType == "HDB"){
var e = new Array("Any","Boat Quay","Chinatown","Havelock Road","Marina Square");
var options = '';
for (var i = 0; i < e.length; i++) {
options += '<option>' + e[i] + '</option>';
}
$("#TypeList1").html(options);
sb2.sync();
}else{
var d = new Array("Any","D01 Boat Quay / Raffles Place","D02 Chinatown / Tanjong Pagar","D03 Alexandra / Commonwealth","D04 Harbourfront / Telok Blangah");
var options = '';
for (var i = 0; i < d.length; i++) {
options += '<option>' + d[i] + '</option>';
}
$("#TypeList1").html(options);
sb2.sync();
}
<!------------------------------Code By Me---------------------------->
}
}));
} else if ($(this).attr("id") === "TypeList") {
city_SB = new SelectBox($.extend(defaultSelectboxSettings, {
selectbox: $(this)
}));
}
//if(jQuery( "#properties option:selected" ).text())
});
updateCities($("#properties").val());
if ($("#properties").val() == "selectone") {
//city_SB.disable();
}
<!------------------------------Code By Me---------------------------->
if(jQuery( "#TypeList option:selected" ).text()){
var dd = new Array("Any","D01 Boat Quay / Raffles Place","D02 Chinatown / Tanjong Pagar","D03 Alexandra / Commonwealth","D04 Harbourfront / Telok Blangah");
var options = '';
for (var i = 0; i < dd.length; i++) {
options += '<option>' + dd[i] + '</option>';
}
$("#TypeList1").html(options);
sb2.sync();
}
<!------------------------------Code By Me---------------------------->
function updateCities(val) {
var $select = $("select#TypeList"),
html = "";
for (var i = 0; i < TypeList[val].length; i++) {
html += '<option value="' + TypeList[val][i] + '">' + TypeList[val][i] + '</option>';
}
$select.html(html);
// HACK: chrome is too fast?
setTimeout(function() {
city_SB.sync();
}, 1);
}
});
</script>
</body>
</html>
Any ideas or suggestions? Thanks.

your array can look like this
var options = [{
option: option1,
value: value1
}, {
option: option2,
value: value2
}];
You will then loop over that json array like so
for (var i = 0; i < options.length; i++) {
var option = options[i];
}
and change this line
options += '<option>' + d[i] + '</option>';
to (add this into the for loop)
options += '<option value="' + d.value + '">' + d.option + '</option>';

Do as follows:
Prepare json object as follows:
var data = [
{
"id": "id1",
"name": "name1"},
{
"id": "id2",
"name": "name2"}
];
Then prepare options list as follows:
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});

Related

JavaScript class did not function in asp.net

I have created a javascript function in my aspx page..
below are the sample code,
<script type="text/javascript">
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
</script>
I would like this function execute in the property such as
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>
As the code running, the javascript function above should be executed and display the " Choose Year" propery inside as shown above.
I try to run this code but nothing happens to the property. Any help would be appreciated. Thank u.
Your code seems to be working as below. However you may be missing the jQuery script so you can check if that exists.
$(document).ready(function () {
console.log("ready!");
var output = [];
var yr = 1950;
for (var i = 0; i <= 70; i++) {
if (i == 0) {
output[i] = '<option value="0" selected="selected"> Choose Year</option>';
}
else {
output[i] = '<option value="' + (parseInt(1950) + parseInt(i - 1)) + '">' + (parseInt(1950) + parseInt(i - 1)) + '</option>';
}
}
$('#yearid').get(0).innerHTML = output.join('');
});
$("#yearid").change(function () {
var select = $("#yearid option:selected").val();
$("#yearval").val(select);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-4 form-group">
<span>Year : </span>
<select id="yearid" class="form-control" runat="server">
</select>
<input id="yearval" type="hidden" runat="server"/>
</div>

How to stop adding duplicate values in select list box

I'm new to java script. I want prevent adding duplicate values to fourth list box. For example, It would not be same like below i) Paper Manufacturers << Paper Converters << Molded Pulp Products ii) Paper Manufacturers << Paper Converters << Molded Pulp Products And If there is no values in the fourth box, The "Remove Category" Button should be in disabled mode. If there is values & if i select any values in 4th box, The "Remove Category" Button should be enabled & "Add Category" button should be disabled.
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#tget");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 20 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 20) ? $numChoice + " more " : "up to 20 ";
choice.text(strText);
}
function appendChoice() {
var count="";
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0) {alert('This category has already been added.');
return count=1;
}
else {
selectedList.append('<option value="'+ givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] +'">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
return count=2;
}
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
var a=appendChoice();
if(a==2){
setAvailableChoice(availableChoice - 1);
}
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function() {
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option value="1">Paper Manufacturers</option>
<option value="2">Paper Products Suppliers</option>
<option value="3">Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option value="1">Paper Converters</option>
<option value="2">Lab Apparatus & Supplies</option>
<option value="3">Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option value="1">Molded Pulp Products</option>
<option value="2">Software Vendors</option>
<option value="3">Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>
Use this script. It will show alert if try to add duplicate entry. I have changed in function appendChoice().
$(document).ready(function () {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function () {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton() {
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton);
}
function getNumberOfSelectedOption() {
return selectedList.find("option").length;
}
function getAvailableChoice() {
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice) {
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice() {
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function () {
var availableChoice = getAvailableChoice();
if (availableChoice >= 1) {
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function () {
removeCategoryButton.prop("disabled", false);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener() {
removeCategoryButton.click(function () {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if (0 < availableChoice < 6) {
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
});
}
});
Check the working code snippet
$(document).ready(function() {
var firstCategorySelector = '.select-manage-category';
var secondCategorySelector = '.select-manage-category1';
var thirdCategorySelector = '.select-manage-category2';
var firstCategory = $(firstCategorySelector);
var secondCategory = $(secondCategorySelector);
var thirdCategory = $(thirdCategorySelector);
var addCategoryButton = $("#add-category");
var removeCategoryButton = $('#remove-category');
var selectedList = $('#selected-lst-values');
var choice = $("#target");
$('.select-manage-category, .select-manage-category1, .select-manage-category2').change(function() {
AddCategoryButtonEnable();
});
function getCategoryValues() {
var firstCategoryValue = firstCategory.val();
var secondCategoryValue = secondCategory.val();
var thirdCategoryValue = thirdCategory.val();
return [firstCategoryValue, secondCategoryValue, thirdCategoryValue];
}
function isDisableAddButton(){
var values = getCategoryValues();
return (!values[0] || !values[1] || !values[2]);
}
function AddCategoryButtonEnable() {
var isDisableAddCategoryButton = isDisableAddButton();
addCategoryButton.prop("disabled", isDisableAddCategoryButton).toggleClass('text-bold', isDisableAddCategoryButton );
}
function getNumberOfSelectedOption(){
return selectedList.find("option").length;
}
function getAvailableChoice(){
return 5 - parseInt(getNumberOfSelectedOption());
}
function setAvailableChoice($numChoice){
var strText = ($numChoice !== 5) ? $numChoice + " more " : "up to 5 ";
choice.text(strText);
}
function appendChoice(){
var givenCategoryArrayValue = getCategoryValues();
if ($('#selected-lst-values option:contains("' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '")').length > 0)
alert('Duplicate value not allowed.');
else
selectedList.append('<option value="">' + givenCategoryArrayValue[0] + ' << ' + givenCategoryArrayValue[1] + ' << ' + givenCategoryArrayValue[2] + '</option>');
}
addCategoryButton.click(function() {
var availableChoice = getAvailableChoice();
if(availableChoice >= 1){
appendChoice();
setAvailableChoice(availableChoice - 1);
} else {
setAvailableChoice(0);
}
});
var option = selectedList.find('option:selected');
selectedList.change(function(){
removeCategoryButton.prop("disabled", false);
addCategoryButton.prop("disabled", true);
_addRemoveButtonClickListener();
});
function _addRemoveButtonClickListener(){
removeCategoryButton.click(function() {
selectedList.find('option:selected').remove();
var availableChoice = getAvailableChoice();
if(0 < availableChoice < 6){
setAvailableChoice(availableChoice);
} else {
setAvailableChoice(0);
}
removeCategoryButton.prop("disabled", true);
});
}
});
.select-manage-category,
.select-manage-category1,
.select-manage-category2 {
width: 100px;
float: left;
margin-right: 4px;
}
p {
clear: left;
text-align: center;
}
#selected-lst-values {
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><select class="form-control select-manage-category" size="5">
<option>Paper Manufacturers</option>
<option>Paper Products Suppliers</option>
<option>Paper Chemicals Suppliers</option>
</select></div>
<div><select class="form-control select-manage-category1" size="5">
<option>Paper Converters</option>
<option>Lab Apparatus & Supplies</option>
<option>Service Providers</option>
</select></div>
<div><select class="form-control select-manage-category2" size="5">
<option>Molded Pulp Products</option>
<option>Software Vendors</option>
<option>Information Services</option>
</select>
</div>
<p style="padding-top:10px;color:red;">You can add <span id="target">up to 5</span> categories</p>
</div>
<input id="add-category" name="add" type="button" value="Add Category" disabled="true">
<input id="remove-category" name="add" type="button" value="Remove Category" disabled="true">
<div><select id="selected-lst-values" class="form-group percent-100" size="7" multiple="multiple">
</select></div>
<button id="mnage-category-savebtn" class="btn btn-md btn-radius pi-btn prodetails-btn" type="button"><strong>Save Categories</strong> <span class="glyphicon glyphicon-menu-right right-arrow-head-icon"></span></button>

Adding HTML form using JavaScript to get a total in text box

So for the final piece of my code, I need to add all the form values together and show a running total in a textbox underneath the 'table'. Is there a way using JavaScript that this can be done? I have my drop down boxes with values in them.
This is a snippet of my code:
function eraseText() {
var out = document.querySelectorAll(".out");
for (var i=0;i<out.length;i++) {
out[i].value="";
}
}
var sections = {
p1 : {sname: "Dynamic Table ", mscore: 20},
p2 : {sname: "IntelliJ Usage ", mscore: 10},
p3 : {sname: "Calender Control", mscore: 30},
p4 : {sname: "Active Form ", mscore: 20},
p5 : {sname: "Object Database ", mscore: 20}
};
document.write("<pre>");
document.write(Object.keys(sections).reduce(function(s, p, i) {
var o = sections[p];
return s + (i>0?'<br><br><br><br>':'')
+ o.sname + ' '
+ o.mscore + ' '
+ '<textarea class="out" id="output" rows="4" cols="25"></textarea>'
+ ' '
+ '<select>'
+ '<option value="1">1</option>'
+ '<option value="2">2</option>'
+ '<option value="3">3</option>'
+ '</select>' }, '')
);
document.write("</pre>");
Something like this?
var selects = [].slice.call(document.querySelectorAll('select')); // [].slice.call turns NodeList into an array
var total = selects.reduce(function (previousValue, select) {
previousValue += select.options[select.selectedIndex].value || 0;
}, 0);
// ... then query for textbox, set the value of it to 'total'
You'd want to bind to the onchange event of each select, and recalculate the sum each time.
var output = document.getElementById('output'),
selects = document.querySelectorAll('select');
//helper method
function doToAll(elems, fn) {
var len = elems.length;
while (--len > -1) {
fn(elems[len]);
}
}
//sum values
function sumSelects() {
var sum = 0;
doToAll(selects, function(t) {
sum += parseInt(t.value);
});
return sum;
}
//bind to onchange event
doToAll(selects, function(t) {
t.addEventListener('change', function() {
output.textContent = sumSelects();
});
});
//run once on load
window.addEventListener('load', function() {
output.textContent = sumSelects();
});
<select>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<select>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<select>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<p>The current total is
<span id="output"></span>
</p>

Cascading Dropdown is not working using jquery

by the way i just got the js code from one of the questions here but i don't why it will not work on mine. please help me.
.js file
jQuery(function ($) {
var College = {
'College of Engineering': ['Civil Engineering', 'Computer Engineering', 'Electronics and Communication Engineering', 'Electrical Engineering', 'Industrial Engineering'],
}
var $College = $('#college');
$('#department').change(function () {
var department = $(this).val(), clg = College[department] || [];
var html = $.map(clg, function (cl) {
return '<option value="' + cl + '">' + cl + '</option>'
}).join('');
$College.html(html)
});
});
is my code wrong? i dont know why it will not work.
the html code for this is
<select class="form-control" name="college" id="college" runat="server">
<option value="College">Select College</option>
<option value="College of Engineering">College of Engineering</option>
<option value="CAS">College of Arts and Science</option>
<option value="Commerce">College of Commerce</option>
</select>
<select id="department" class="form-control" runat="server" placeholder="Department" >
<option value="Department">Select Department</option>
</select>
You could do something like this: https://jsfiddle.net/rockmandew/12ej2rt3/
Set your HTML Markup like so: (*this example contains a three step dropdown selection)
<select id="main_list">
<option value="default" selected>Select Your List</option>
<option value="mobile">mobile list</option>
<option value="laptop">laptop list</option>
</select>
<select id="brand" class="secondary"></select>
<select id="version" class="secondary"></select>
Then the JS as follows:
$(function() {
var sel, i,
list = ['mobile', 'laptop'],
phone = ['Samsung', 'Nokia'],
laptop = ['HP', 'Dell'],
android = ['4.1', '4.2'],
windows = ['8', '8.1'],
dev_default = '<option value="default" selected>Select your Device brand</option>',
os_default = '<option value="default" selected>Select your OS version</option>';
sel_brand = $('#brand');
sel_version = $('#version');
$('select').change(function() {
switch (this.id) {
case 'main_list':
$('.secondary').hide();
sel_brand.find('option').remove();
sel_brand.append(dev_default);
sel_brand.show();
if (this.value == 'mobile') {
for (i = 0; i < phone.length; i++) {
$("#brand").append(
'<option value="' + phone[i] + '">' + phone[i] + '</option>'
);
}
}else if (this.value == 'laptop') {
for (i = 0; i < phone.length; i++) {
$("#brand").append(
'<option value="' + laptop[i] + '">' + laptop[i] + '</option>'
);
}
}
break;
case 'brand':
sel_version.find('option').remove();
sel_version.append(os_default);
sel_version.show();
if (this.value == 'Samsung') {
for (i = 0; i < android.length; i++) {
$("#version").append(
'<option value="' + android[i] + '">' + android[i] + '</option>'
);
}
}else if (this.value == 'Nokia' || this.value == 'HP' || this.value == 'Dell') {
for (i = 0; i < windows.length; i++) {
$("#version").append(
'<option value="' + windows[i] + '">' + windows[i] + '</option>'
);
}
}
break;
}
});
}); //END document.ready()
Also, if you need/want more information on how to populate these dropdowns dynamically from either a text file, JSON, or a database - check out this article: https://css-tricks.com/dynamic-dropdowns/

jquery .grep is not removing array element

$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function ()
{
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
}); >
});
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>'; >
}
$('#ad_list').append(option);
});
below is html code dropdownlist showing element in array
<label>ADD:</label>
<select name="ADD_list" id="ad_list"></select>
<input type="submit" id="btn" />
You need to update your option after removing the selected element:
function updateOption(numbers) {
$("#ad_list").empty();
var option = '';
for (i = 0; i < numbers.length; i++) {
option += '<option value="' + i + '">' + numbers[i] + '</option>';
}
$('#ad_list').append(option);
}
$(document).ready(function () {
var numbers = ['sachin', 'raaj', 'rahul', 'mahesh', 'sandip'];
$('#btn').click(function () {
var c = $("#ad_list option:selected").text();
numbers = jQuery.grep(numbers, function (value) {
return value != c;
});
updateOption(numbers);
});
updateOption(numbers);
});
Fiddle Demo

Categories

Resources