How do i manipulate select box using jquery? - javascript

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?

Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.

Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});

I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Related

form select option dynamic attr

I need to make Select name with option value, to select a specific value or index. the data where comes from db in a value "{{design}}".
I do get the value currectly, but I dont manage to set "selected" on the currect option value.
here is the code:
console.log("{{design}}");
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( options[i].innerHTML==="{{design}}")
{
options.selectedIndex=i;
}
}
});
the html is :
<select name="design" required id="design" >
<option value="1">flowers</option>
<option value="2">classic</option>
<option value="3">roses</option>
</select>
I need to make to currect {{design}} value, lets say it's 2, so it will be <option value="2" selected>classic</option>`
thanks!
SOLVED
Hi, found the solution to the issue, if anyone eles goes into trouble.
$(document).ready(function () {
var options = $('select').children('option');
var size = $('select').children('option').length;
for (i=0;i<size;i++)
{
if ( $('select').children('option')[i].value === "{{design}}")
{
$('select').children('option')[i].selected=true;
}
}
});
the currect way is to find the right option value and then-> [i].selected=true
goodluck
Try this
var selectedvalue=2; //option with value 2 should be selected
$("#design option[value=selectedvalue]").attr("selected","selected");
Hope this helps...
If I understood right, you are on the right path just taking a minor detour. Try this:
if ( options[i].innerHTML==="{{design}}")
{
options.attr('selected', 'selected');
}
The example of .each() usage:
$(document).ready(function(){
$('select option').each(function(i){
if( i.value === "{{design}}"){
$(this).attr('selected','selected');
}
});
});
try this:
$(document).ready(function(){
$('select option').each(function(i){
//if this option contains the word "{{design}}" Then this is selected
if( $(this).html().indexOf("{{design}}") != -1)
$(this).attr('selected',true);
});
});

Change Javascript function from checkbox to select

I have a function that based on a checkbox id determines a price value. This works fine except I need to change the checkbox to a select. I tried to change the line:
if(peo14.checked==true)
To this:
if(peo14.select==Yes)
This did not work...how do I alter this to a Yes/No select?
function peoPrice()
{
var peoPrice=0;
//Get a reference to the form id="quicksheet"
var theForm = document.forms["quicksheet"];
//Get a reference to the checkbox id
var peo14 = theForm.elements["peo14"];
//If they checked the box set peoPrice to value
if(peo14.checked==true)
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}
You have to use the .options property and choose the selected index, then get the value of that index.
if (peo14.options[ peo14.selectedIndex ].value === 'Yes') {
peoPrice = 199;
}
Select Box
<select id="peo14" name='peo14' >
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
function peoPrice()
{
var peoPrice=0;
var e = document.getElementById("peo14");
var peo14val = e.options[e.selectedIndex].value;
if(peo14val=="Yes")
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}

How can we arrange the three select box into one sequence through Jquery

I would like to know how can we arrange the three select box, with having some options, it will be configured according to the previous select box value.
Please look at the code which we applied for our program.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var rtype = $("#rtype").val();
var rarray = rtype.split(' ');
var max_adults = rarray[1];
var min_adults = rarray[0];
//var max_adults = 3;
//var min_adults = 2;
$('#rooms').change(function(){
var room_num = $(this).val();
var options = '';
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) { options += '<option value="'+i+'">'+i+'</option>' } $('#person').html(options); }); $('#rooms').change(); });
</script>
</head>
<body>Room Type <select name="rtype" id="rtype"><option Selected value="">Select</option><option value="2 3">Room 2-3</option> <option value="3 4">Room 3-4</option></select> Category: <select name="rooms" id="rooms"> <option Selected value="">Select</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option> </select>Persons<select name="person" id="person"> </select></body>
Above this code is working fine if we remove the code for "rtype" ID, and entered the hard coded value to the query like this.
var max_adults = 3;
var min_adults = 2;
but we likt to update this value when we change the "rtype" id, the value for the an option is ( 2 3), we just have to split these value in to two part, the higher one will put into " var max_adults", and lower one will go to "var min_adult".
Please give me the proper solution, how can we arrange the codes accordingly.
You need to put the rtype code inside the change event handler tof the #rooms element:
$(function () {
$('#rooms').change(function(){
//get the `#rtype` value
var rtype = $("#rtype").val();
//check to make sure the `#rtype` value isn't an empty string
if (rtype != '') {
var room_num = $(this).val(),
rarray = rtype.split(' '),
options = '',
max_adults = rarray[1],
min_adults = rarray[0];
for (var i = min_adults * room_num; i <= max_adults * room_num; i++) {
options += '<option value="'+i+'">'+i+'</option>';
}
$('#person').html(options);
} else {
//since no `#rtype` value was found alert the user
alert('Please Select a Room Type');
}
//trigger the change event by chaining rather than re-selecting the same element
}).change();
});
Update
To make one element appear when the other changes, add this to the document.ready event handler:
$('#rtype').change(function () {
//if a value has not been selected then hide the `#rooms` element, otherwise show it
if (this.value == '') {
$('#rooms').hide();
} else {
$('#rooms').show();
}
});
You then need to add the following CSS for the #rooms element:
#rooms {
display : none;
}

Add <select> options based on the value of a text input

How I can add options to a select field based on the value of a text input?
This is my input text:
<input type="text" id="amount" size="30" />
This is my element I want to add to:
<span id="span_combo">
<select name="foo" id="combo">
<option value="1">1</option>
<option value="2">2</option>
</select>
</span>
This is my current JS:
$("#amount").keyup(function(){
var flag;
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
var i;
for(i=1;i<=a-1;i++){
$("#span_combo").append($("#span_combo select").first().clone(true));
}
});
Something like this should do it
Live demo here : http://jsfiddle.net/NdpuM/1/
$("#amount").keyup(function(){
var $combo = $('#combo');
$combo.html('');
var value = parseInt($('#amount').val(), 10);
for (i = 1; i <= value; i++) {
var $option = $('<option>').val(i).html(i);
$combo.append($option);
}
});
Basically, clear the select box everytime there is a keydown and repopulate it. You could optimize this more by adding a few checks to see whether it's the same value
If you want to rebuild the entire array:
$("#amount").keyup(function(){
$("#combo").show("slow");
var a = $("#amount").val();
if(a==""){
$("#span_combo select").remove(true);
}
$('#combo').empty();
for(var i=1;i<=a-1;i++){
$('<option />').attr('value', i)
.text(i)
.appendTo($('#combo'));
}
});
I think this could work:
$("#amount").keyup(function() {
var current = $("#combo option").length;
if(current < $(this).val()) {
for(var i = current + 1;i<=$(this).val();i++) {
$("#combo").append('<option value="'+i+'">'+i+'</option>');
}
} else {
for(var i=(parseInt($(this).val(),10)+1);i<=current;i++) {
$('#combo option[value="'+i+'"]').remove();
}
}
});
You might want to add input verification to this function, but it does what you want if you use it right.
EDIT: Just to clarify, this code doesn't clear the whole select box on every keyup event, it just adds new options or removes the last ones to get the specified amount of values.

jQuery Filtering

Is there a way to filter a multi-line select box using jQuery?
I'm a new to jQuery and can't seem to figure out the best way to do this.
For example if I have:
<select size="10">
<option>abc</option>
<option>acb</option>
<option>a</option>
<option>bca</option>
<option>bac</option>
<option>cab</option>
<option>cba</option>
...
</select>
I want to filter this list based on a selection drop down with:
<select>
<option value="a">Filter by a</option>
<option value="b">Filter by b</option>
<option value="c">Filter by c</option>
</select>
Something like this might do the trick (assuming you give your 'Filter by...' select an id of filter and the filtered / other select an id of otherOptions):
$(document).ready(function() {
$('#filter').change(function() {
var selectedFilter = $(this).val();
$('#otherOptions option').show().each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) !== 0) {
$currentOption.hide();
}
});
});
});
UPDATE: As #Brian Liang pointed out in the comments, you might have problems setting the <option> tags to display:none. Therefore the following should give you a better cross-browser solution:
$(document).ready(function() {
var allOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
allOptions[$currentOption.val()] = $currentOption.text();
});
$('#filter').change(function() {
// Reset the filtered select before applying the filter again
setOptions('#otherOptions', allOptions);
var selectedFilter = $(this).val();
var filteredOptions = {};
$('#otherOptions option').each(function(i) {
var $currentOption = $(this);
if ($currentOption.val().indexOf(selectedFilter) === 0) {
filteredOptions[$currentOption.val()] = $currentOption.text();
}
});
setOptions('#otherOptions', filteredOptions);
});
function setOptions(selectId, filteredOptions) {
var $select = $(selectId);
$select.html('');
var options = new Array();
for (var i in filteredOptions) {
options.push('<option value="');
options.push(i);
options.push('">');
options.push(filteredOptions[i]);
options.push('</option>');
}
$select.html(options.join(''));
}
});

Categories

Resources