Hi i'm trying to apply a callback to use on my dynamic select boxes instead of TimeOut
Currently i have 4 select options boxes(3 are dynamic options): City, District(options based on city options), Ward(options based on district options) and Street(options based on district options)
It's a search form so the next page form should has the previous form values, i use Django to determined if a previous form values are select , then if so it will add a hidden div with id="value-filter" in the template. And now i use the Jquery to check if that div exists to change the select options
If a user click on the city option then it will activate the city onchange event to call an api that populate District options with the corresponding city Id, Ward and Street options are the same but based on District options to call their api in order to populate their options.
$(document).ready(function() {
//call district api if city option is selected
$('select#city').change(function(event) {
$.getJSON("/api_get_districts/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- District --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#district").html(options);
});
});
//call ward and street api if district option is selected
$('select#district').change(function(event) {
$.getJSON("/api_get_wards/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- Ward --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#ward").html(options);
});
$.getJSON("/api_get_streets/", {
id: $(this).val()
}, function(j) {
var options = '<option selected disabled>-- Street --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#street").html(options);
});
});
// main one to handle select option if the div of a values is present in html
if ($('#district-filter').length) {
$('select#city').val("{{ filter_form_values.city |safe }}").change();
setTimeout(function() {
$('select#district').val("{{ filter_form_values.district |safe }}").change();
if ($('#ward-filter').length) {
setTimeout(function() {
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
}, 500);
}
if ($('#street-filter').length) {
setTimeout(function() {
$('select#street').val("{{ filter_form_values.street |safe }}").change();
}, 500);
}
}, 500);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label>Tỉnh </label>
<select class="form-control form-control-sm" name="city" id="city" required="">
<option selected="" disabled="">-- City --</option>
<option value="1">Hà Nội</option>
<option value="2">Hồ Chí Minh</option>
<option value="3">Bình Dương</option>
<option value="4">Đà Nẵng</option>
<option value="5">Hải Phòng</option>
<option value="6">Long An</option>
<option value="7">Bà Rịa Vũng Tàu</option>
<option value="8">An Giang</option>
<option value="9">Bắc Giang</option>
<option value="10">Bắc Kạn</option>
<option value="11">Bạc Liêu</option>
<option value="12">Bắc Ninh</option>
<option value="13">Bến Tre</option>
<option value="14">Bình Định</option>
<option value="15">Bình Phước</option>
<option value="16">Bình Thuận</option>
<option value="17">Cà Mau</option>
<option value="18">Cần Thơ</option>
<option value="19">Cao Bằng</option>
<option value="20">Đắk Lắk</option>
<option value="21">Đắk Nông</option>
<option value="22">Điện Biên</option>
<option value="23">Đồng Nai</option>
<option value="24">Đồng Tháp</option>
<option value="25">Gia Lai</option>
<option value="26">Hà Giang</option>
<option value="27">Hà Nam</option>
<option value="28">Hà Tĩnh</option>
<option value="29">Hải Dương</option>
<option value="30">Hậu Giang</option>
<option value="31">Hòa Bình</option>
<option value="32">Hưng Yên</option>
<option value="33">Khánh Hòa</option>
<option value="34">Kiên Giang</option>
<option value="35">Kon Tum</option>
<option value="36">Lai Châu</option>
<option value="37">Lâm Đồng</option>
<option value="38">Lạng Sơn</option>
<option value="39">Lào Cai</option>
<option value="40">Nam Định</option>
<option value="41">Nghệ An</option>
<option value="42">Ninh Bình</option>
<option value="43">Ninh Thuận</option>
<option value="44">Phú Thọ</option>
<option value="45">Phú Yên</option>
<option value="46">Quảng Bình</option>
<option value="47">Quảng Nam</option>
<option value="48">Quảng Ngãi</option>
<option value="49">Quảng Ninh</option>
<option value="50">Quảng Trị</option>
<option value="51">Sóc Trăng</option>
<option value="52">Sơn La</option>
<option value="53">Tây Ninh</option>
<option value="54">Thái Bình</option>
<option value="55">Thái Nguyên</option>
<option value="56">Thanh Hóa</option>
<option value="57">Thừa Thiên Huế</option>
<option value="58">Tiền Giang</option>
<option value="59">Trà Vinh</option>
<option value="60">Tuyên Quang</option>
<option value="61">Vĩnh Long</option>
<option value="62">Vĩnh Phúc</option>
<option value="63">Yên Bái</option>
</select>
</div>
<div class="form-group">
<label>District </label>
<div id="district-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="district" id="district">
<option selected="" disabled="">-- District --</option>
</select>
</div>
<div class="form-group">
<label>Ward </label>
<div id="ward-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="ward" id="ward">
<option selected="" disabled="">-- Ward --</option>
</select>
</div>
<div class="form-group">
<label>Street </label>
<div id="street-filter" style="display: none"></div>
<select class="form-control form-control-sm" name="street" id="street">
<option selected="" disabled="">-- Street --</option>
</select>
</div>
Everything worked great but now i want to try to change my timeOut function in the if ($('#district-filter').length) {} to a callback. I had tried the following by using when() to apply callback:
if ($('#district-filter').length) {
$.when($('select#city').val("{{ filter_form_values.city |safe }}").change()).then(function() {
$.when($('select#district').val("{{ filter_form_values.district |safe }}").change()).then(function() {
if ($('#ward-filter').length) {
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
}
if ($('#street-filter').length) {
$('select#street').val("{{ filter_form_values.street |safe }}").change();
}
});
});
}
On page load the city is select and the District load but the district options didn't get select so the Ward and Street options also empty.
How do i use callback to wait for my Api to populate an options then select that option?
I had decided to just use normal callback and add the request api function in the check:
if ($('#city-filter').length) {
$('select#city').val("{{ filter_form_values.city |safe }}").change();
}
if ($('#district-filter').length || $('#ward-filter').length || $('#street-filter').length) {
$.getJSON("/api_get_district/", {
id: "{{ filter_form_values.city |safe }}"
}, function(j) {
var options = '<option selected disabled>-- District --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#district").html(options);
$('select#district').val("{{ filter_form_values.district |safe }}").change();
if ($('#ward-filter').length) {
$.getJSON("/api_get_ward/", {
id: "{{ filter_form_values.district |safe }}"
}, function(j) {
var options = '<option selected disabled>-- Ward --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#ward").html(options);
$('select#ward').val("{{ filter_form_values.ward |safe }}").change();
});
}
if ($('#street-filter').length) {
$.getJSON("/api_get_street/", {
id: "{{ filter_form_values.district |safe }}"
}, function(j) {
var options = '<option selected disabled>-- Street --</option>';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
}
$("select#street").html(options);
$('select#street').val("{{ filter_form_values.street |safe }}").change();
});
}
});
}
also add city check to the html:
<div id="city-filter" style="display: none"></div>
And now it worked but i will take any suggestion to improve it as answer(since calling api 2 times isn't consider a good idea)!
Related
I have this form where I want to hide specific parts of it based on the subsubcategory_id selected but I can't seem to make it work.
I have a script that changes subcategory based on category selected and another one that changes subsubcategory based on subcategory selected.
The script for hiding parts of the form works but only for category that comes from the DB and not for subsubcategory that is affected by the first script. The value of the option element in the select just seems to register as empty for the 2nd script. What should I do to fix it?
<script type="text/javascript">
$(document).ready(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="subsubcategory_id"]').html('');
var d = $('select[name="subcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subcategory_name + '</option>');
});
},
});
} else {
alert('danger');
}
});
$('select[name="subcategory_id"]').on('change', function() {
var subcategory_id = $(this).val();
if (subcategory_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory/product') }}/" +
subcategory_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="subsubcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subsubcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subsubcategory_name + '</option>');
});
},
});
} else {
alert('danger');
}
});
});
</script>
// script to hide parts of the form
<script>
$(document).ready(function() {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
$("#test").change(function() {
var subsubcategory_id = $(this).val();
if (subsubcategory_id == 1) {
$('#fieldLaptop').show();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
} else if (subsubcategory_id == 2) {
$('#fieldLaptop').hide();
$('#fieldTablet').show();
$('#fieldPhone').hide();
} else if (subsubcategory_id == 3) {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').show();
} else {
$('#fieldLaptop').hide();
$('#fieldTablet').hide();
$('#fieldPhone').hide();
}
});
});
$("#test").trigger("change");
</script>
<form method="post" action="{{ route('product-store') }}" enctype="multipart/form-data">
#csrf
<div class="row mbn-20">
<div class="col-3 mb-20">
<label for="formLayoutUsername3">Brand</label>
<select name="brand_id" class="form-control">
<option value="" selected="" disabled="">Brand</option>
<option value="{{ $brand->id }}">
{{ $brand->brand_name }}
</option>
#endforeach
</select>
#error('brand_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</select>
</div>
<div class="col-3 mb-20">
<label for="formLayoutEmail3">Categorie</label>
<select name="category_id" class="form-control">
<option value="" selected="" disabled="">Category
</option>
<option value="{{ $category->id }}">
{{ $category->category_name }}
</option>
#endforeach
</select>
#error('category_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
<div class="col-3 mb-20">
<label for="formLayoutPassword3">SubCategory</label>
<select name="subcategory_id" class="form-control">
<option value="" selected="" disabled="">Select SubCategory
</option>
</select>
#error('subcategory_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
<div class="col-3 mb-20">
<label for="formLayoutAddress1">SubSubCategory</label>
<select name="subsubcategory_id" class="form-control" id="test">
<option value="" selected="" disabled="">Select SubSubCategory
</option>
</select>
#error('subsubcategory_id')
<span class="text-danger"><strong>{{ $message }}</strong></span>
#enderror
</div>
</form>
Based on your explanation, I think you're looking for this:
$(document).on('change', '[data-child]', function() {
const selected_group = $(this).val();
let el = $(`#${$(this).attr("id")}`);
if (selected_group === null) {
el.hide();
} else {
el.show();
}
let child_select = $("#" + $(this).attr("data-child"));
value = child_select.find("option").hide().filter(function(i, e) {
return $(e).val().startsWith(selected_group);
}).show().eq(0).val();
child_select.val(value);
child_select.trigger("change");
});
$("[data-child]").eq(0).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="row m-4 justify-content-center">
<div class="col-3">
<span>Operating system</span>
<select data-child="niv1" class="selectdata form-control custom-select">
<option value="1-1">Android</option>
<option value="1-2">Linux</option>
<option value="1-3" selected>Windows</option>
</select>
</div>
<div class="col-3">
<span>System version</span>
<select id="niv1" data-child="niv2" class="selectdata form-control custom-select">
<option data-group="1-1" value="1-1-1">9.0 Pie</option>
<option data-group="1-2" value="1-2-1">Ubuntu</option>
<option data-group="1-3" value="1-3-1">Windows 7</option>
<option data-group="1-3" value="1-3-2">Windows 8</option>
<option data-group="1-3" value="1-3-3">Windows 10</option>
</select>
</div>
<div class="col-3">
<span>Edition</span>
<select id="niv2" data-child="niv3" class="selectdata form-control custom-select">
<option data-group="1-2-1" value="1-2-1-1">Trusty Tahr</option>
<option data-group="1-2-1" value="1-2-1-2">Xenial Xerus</option>
<option data-group="1-2-1" value="1-2-1-3">Bionic Beaver</option>
<option data-group="1-3-1" value="1-3-1-1">Windows 7 Home</option>
<option data-group="1-3-1" value="1-3-1-2">Windows 7 Pro</option>
<option data-group="1-3-2" value="1-3-2-1">Windows 8 Home</option>
<option data-group="1-3-2" value="1-3-2-2">Windows 8 Pro</option>
<option data-group="1-3-3" value="1-3-3-1">Windows 10 Home</option>
<option data-group="1-3-3" value="1-3-3-2">Windows 10 Pro</option>
</select>
</div>
<div class="col-3">
<span>Build</span>
<select id="niv3" data-child="niv4" class="selectdata form-control custom-select">
<option data-group="1-2-1-2" value="1-2-1-2-1">18.04 LTS</option>
<option data-group="1-3-1-1" value="1-3-1-1-1">Win 7 Home - A</option>
<option data-group="1-3-1-1" value="1-3-1-1-2">Win 7 Home - B</option>
<option data-group="1-3-1-2" value="1-3-1-2-1">Win 7 Pro - A</option>
<option data-group="1-3-1-2" value="1-3-1-2-2">Win 7 Pro - B</option>
<option data-group="1-3-2-1" value="1-3-2-1-1">Win 8 Home - A</option>
<option data-group="1-3-2-1" value="1-3-2-1-2">Win 8 Home - B</option>
<option data-group="1-3-2-2" value="1-3-2-2-1">Win 8 Pro - A</option>
<option data-group="1-3-2-2" value="1-3-2-2-2">Win 8 Pro - B</option>
<option data-group="1-3-3-1" value="1-3-3-1-1">Win 10 Home - A</option>
<option data-group="1-3-3-1" value="1-3-3-1-2">Win 1 Home - B</option>
<option data-group="1-3-3-2" value="1-3-3-2-1">Win 10 Pro - A</option>
<option data-group="1-3-3-2" value="1-3-3-2-2">Win 10 Pro - B</option>
</select>
</div>
</div>
So this is the way to make it work. If there is only one option You should probably trigger it manually after putting stuff in it so it runs with the first chosen option
The change is only called when the user changes it, and not after the AJAX runs. So in your case, you probably always want to call change to make sure your UI is in sync with what came from the server initially
$('select[name="subcategory_id"]').on('change', function() {
var subcategory_id = $(this).val();
if (subcategory_id) {
$.ajax({
url: "{{ url('/category/subcategory/subsubcategory/product') }}/" +
subcategory_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="subsubcategory_id"]').empty();
$.each(data, function(key, value) {
$('select[name="subsubcategory_id"]').append(
'<option value="' + value.id + '">' + value
.subsubcategory_name + '</option>');
});
// the tigger is set here for one option in the select !!!
$("#test").trigger("change");
},
});
} else {
alert('danger');
}
});
Then if there are multiple options the user will trigger them after so the first (initial) code would work.
I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}
You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array
If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)
I have 2 selects and what i wanna do is (without refreshing the page): the moment the user selects a value from the first select (value1 or value2) changes the second select: if he choosed value1, then he have a select with values a, b, c, d; if he choosed value2, then he can choose on second select e, f, g, h.
Is this possible without refreshing the page?
Edit: I know you all are not here to write code for others; just wanted to keep it simple instead of posting all my messy code :). So, what i want to do, is to modify the second select id=selectAccessiblePaths with the onchange function applyGroupSelection()
function initDivWithConfig () {
divWithInfo = document.createElement('div');
divWithInfo.class = 'divWithInfoControls';
divWithInfo.style.position = 'absolute';
divWithInfo.style.top = '10px';
divWithInfo.style.width = '100%';
divWithInfo.style.textAlign = 'center';
var groupToDisplay = '<p id="pSelectGroup" style="display: block;">Select the user group: ';
groupToDisplay += '<select id="selectGroup" onchange="applyGroupSelection()">';
groupToDisplay += '<option selected>Nothing selected</option>';
for ( var g in userGroups ) {
groupToDisplay += '<option>' + g + '</option>';
}
groupToDisplay += '</select></p>';
divWithInfo.innerHTML += groupToDisplay;
groupSelected = 'group1';
var accessiblePathsToDisplay = '<p id="pSelectAccessiblePaths" style="display: none;">Select the accessible paths: ';
accessiblePathsToDisplay += '<select id="selectAccessiblePaths" onchange="applyAccessiblePathsSelection()">';
accessiblePathsToDisplay += '<option selected>Nothing selected</option>';
for ( var ap=0; ap<userGroups[ groupSelected ].accessiblePaths.length; ap++ ) {
var pathsForThisGroup = userGroups[ groupSelected ].accessiblePaths[ ap ][ "ns0:svg" ][ "groupPathsName" ];
accessiblePathsToDisplay += '<option>' + pathsForThisGroup + '</option>';
}
accessiblePathsToDisplay += '</select></p>';
divWithInfo.innerHTML += accessiblePathsToDisplay;
document.body.appendChild( divWithInfo );
}
function applyGroupSelection () {
groupSelected = "group2";
hideUnhideObject( "pSelectGroup" );
hideUnhideObject( "pSelectAccessiblePaths" );
}
Easy with HTML, CSS and a JavaScript line:
HTML:
<select id='firstselect' onchange="document.getElementById('secondselect').className=this.value">
<option value='select'>Select a value</option>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<select id='secondselect'>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
<option value='d'>d</option>
<option value='e'>e</option>
<option value='f'>f</option>
<option value='g'>g</option>
<option value='h'>h</option>
</select>
CSS:
#secondselect, #secondselect option {
display: none;
}
#secondselect.value1, #secondselect.value2 {
display: block;
}
.value1 option[value="a"], .value1 option[value="b"], .value1 option[value="c"], .value1 option[value="d"] {
display: block !important;
}
.value2 option[value="e"], .value2 option[value="f"], .value2 option[value="g"], .value2 option[value="h"] {
display: block !important;
}
See in action: http://jsfiddle.net/nukz3ns3/
UPDATED:
Also you can do a function for change to default value when firstselect change:
function setSecondSelect( select ){
var secondselect = document.getElementById('secondselect');
secondselect.className=select.value;
secondselect.selectedIndex = (select.value === 'value1')?0:4;
}
See how it works: http://jsfiddle.net/nukz3ns3/1/
Yes this is possible by using ajax post method.
Yes its possible if you used ajax.
http://api.jquery.com/jquery.ajax/
try this:
<script type="text/javascript">
$(document).ready(function () {
$("#select1").change(function() {
if($(this).data('options') == undefined){
$(this).data('options',$('#select2 option').clone());}
var id = $(this).val();
// alert(id);
var options = $(this).data('options').filter('[value=' + id + ']');
if(options.val() == undefined){
//$('#select2').hide();
$('#select2').prop("disabled",true);
}else{
//$('#select2').show();
$('#select2').prop("disabled",false);
$('#select2').html(options);
}
});
});
</script>
<div class="pageCol1">
<div class="panel">
<div class="templateTitle">Request for Items</div>
<table class="grid" border="0" cellspacing="0" cellpadding="0">
<tr class="gridAlternateRow">
<td><b>Item to be Request</b></td>
<td>
<select name="select1" id="select1">
<option value="1">--Select--</option>
<option value="2">Stationaries</option>
<option value="3">Computer Accessories</option>
<option value="4">Bottle</option>
<option value="5">Chair</option>
<option value="6">Office File</option>
<option value="7">Phone Facility</option>
<option value="8">Other Facilities</option>
</select>
</td></tr>
<tr><td>
<b>Category</b>
</td>
<td>
<select name="select2" id="select2" >
<option value="1">--Select--</option>
<option value="2">Note Books</option>
<option value="2">Books</option>
<option value="2">Pen</option>
<option value="2">Pencil</option>
<option value="2">Eraser</option>
<option value="2">Drawing sheets</option>
<option value="2">Others</option>
<option value="3">Laptop</option>
<option value="3">PC</option>
<option value="3">CPU</option>
<option value="3">Monitor</option>
<option value="3">Mouse</option>
<option value="3">Keyboard</option>
<option value="3">Mouse Pad</option>
<option value="3">Hard Disk</option>
<option value="3">Pendrive</option>
<option value="3">CD/DVD Writer</option>
<option value="3">RAM</option>
<option value="3">Mother Board</option>
<option value="3">SMPS</option>
<option value="3">Network Cables</option>
<option value="3">Connectors</option>
<option value="7">Land Line</option>
<option value="7">BlackBerry </option>
<option value="7">Other</option>
</select>
</td>
</tr>
</table>
</div>
</div>
</div>
your html can be of your required format.
If you are trying to populate the second select from existing options,
Try using filter() on a change handler
$("firstselect").change(function() {
var options = $("secondselect").filter(function() {
//return the options you want to display
});
$("secondselect").html(options);
});
Or if you want to retrieve options from server, use AJAX and form the options
and do an innerHTML as above.
I've three select-box here to choose Format, Amount & Shipping type. After selection, it will calculate price automatically.
here, how those select-box look like:
<p>Format: <select class="calculate" name="format">
<option value="0">Please Select</option>
<option value="0">Format 1</option>
<option value="0">Format 2</option>
</select></p>
<p>Amount: <select class="calculate" name="amount">
<option value="0">Select amount</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
currently, the Amount for the both Format (Format 1/Format 2) are same.
what i'm trying to do is like: for the Format 1, the current Amount will remain same, but if user select Format 2 then the Amount will something like this:
<option value="0">Select amount</option>
<option value="300">250pcs</option>
<option value="350">1,000pcs</option>
<option value="400">2,500pcs</option>
where the value is different! how can i achive this?
here goes the JSfiddle
Thanks in advance for any help!
You should first set the new values in an array. So you can loop through them while changing the first select.
Then you can easily get the options from the 2nd select, and update them with the correct new values:
$(".calculate, #surcharge").on("change", function(){
if($(this).val() == 1)
{
var amountValues = new Array(0,250,400,500);
$("#menge option").each(function(key,value)
{
$(this).val(amountValues[key]);
});
} else if($(this).val() == 2)
{
var amount Values = new Array();
// .....
}
});
http://jsfiddle.net/7Bfk5/15/
You can do this by checking the text() in the options you are selecting
if ($('#sel option:selected').text() === 'Format 2') {
$('#amt option').each(function () {
alert($(this).text());
if ($(this).text() == "250pcs") $(this).val("300");
else if ($(this).text() == "1,000pcs") $(this).val("350");
else $(this).val("400");
});
}
working fiddle
You can create a function that does values/options replacement and call it on your select changes.
I did an example for you but used static html options to replace old ones, this might not be the best way but tried to keep it as simple as possible.
HTML
<p>Format: <select class="calculate format" name="format">
<option value="0">Please Select</option>
<option value="1">Format 1</option>
<option value="2">Format 2</option>
</select></p>
<p>Amount: <select class="calculate amount" name="menge">
<option value="0">Select Menge</option>
<option value="247">250pcs</option>
<option value="279">1,000pcs</option>
<option value="389">2,500pcs</option>
</select></p>
<p>Shipping type: <select id="surcharge" name="shipping">
<option value="0">Select Shipping</option>
<option value="10%">Standard</option>
<option value="15%">Express</option>
</select></p>
<p>Price: <span id="total">0 €</span></p>
Javascript
var updateValues = function (){
if($('.format').val() == 1) {
html = '<option value="300">300pcs</option>';
html += '<option value="400">400pcs</option>';
html += '<option value="500">500pcs</option>';
$('.amount').html(html);
} else if( $('.format').val() == 2) {
html = '<option value="600">600pcs</option>';
html += '<option value="900">900pcs</option>';
html += '<option value="1200">1200pcs</option>';
$('.amount').html(html);
}
};
$('.format').change(function(){updateValues()});
$(".calculate, #surcharge").on("change", function(){
var total = 0;
$('.calculate').each(function() {
if($(this).val() != 0) {
total += parseFloat($(this).val());
}
});
if($('#surcharge').val() != 0) {
total = total * ((100 + parseFloat($('#surcharge').val())) / 100);
}
$('#total').text(total.toFixed(2) + ' €');
});
Fiddle link
http://jsfiddle.net/7Bfk5/23/
I have this select; to select countries and add to a new select multiple with a limit of 5 countries, but I just want to add 1 country by select or more countries if i do a multiple select.
My mistake is in my function addC(), when I want to add more than 1 country in my select, it add the several countries in 1 option tag like this:
<option>South KoreaUSAJapan</option>
What I can modify to display the following way if i do a multiple select?:
<option>South Korea</option>
<option>USA</option>
<option>Japan</option>
My code:http://jsbin.com/osesem/4/edit
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected").text());
$("#addCountry").append("<option>" + newC + "</option>");
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<label for="provincia2"><b>¿Country?</b></label><br>
<span>
<select multiple="multiple" size="5" id="countries">
<option value="1">South Korea</option>
<option value="2">USA</option>
<option value="2">Japan</option>
<option value="3">Italy</option>
<option value="4">Spain</option>
<option value="5">Mexico</option>
<option value="6">England</option>
<option value="7">Phillipins</option>
<option value="8">Portugal</option>
<option value="9">France</option>
<option value="10">Germany</option>
<option value="11">Hong Kong</option>
<option value="12">New Zeland</option>
<option value="13">Ireland</option>
<option value="14">Panama</option>
<option value="15">Norwey</option>
<option value="16">Sweeden</option>
<option value="17">India</option>
<option value="18">Morroco</option>
<option value="19">Russia</option>
<option value="20">China</option>
</select>
</span>
<div class="addremover">
<input class="add" type="button" onclick="addC()" value="Addd »" />
<br/>
</div>
<span>
<select id="addCountry" multiple="multiple" size="5">
</select>
</span>
use each function to loop through the text and append it..
try this
function addC() {
if ($("#agregarProvincia option").length < 5) {
var newC = ($("#countries option:selected"));
newC.each(function(){
$("#addCountry").append("<option>" + $(this).text() + "</option>");
})
}
}
JSbin here
Or just clone the selected <option>'s
function addC() {
if ($('#countries option:selected').size() < 5)
{
$('#addCountry').append($('#countries option:selected').clone());
}
else
{
alert('you can only select 5');
}
}