How to add dynamically a combobox using jQuery - javascript

I've this working code which is creating one combobox:
You can see it working here: jsfiddle
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if ($(this).find('option').size() > 2) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newComboBox);
}
}
});
Which is resulting something this, everytime I fill a combobox, the next one is opened.
How can I change that code to have this? Which means two comboboxes opening (please forget the style)
Thank you.

I'm not entirely sure if your intent, but it seems like you want to have groups of two select elements and then adding a new group when the user selects a value.
In that case I suggest grouping your two selects in a fieldset like this:
<fieldset>
<select id="combo1" class="combo" data-index="1">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
<select id="combo2" class="combo" data-index="2">
<option></option>
<option val="Opt1">Opt1</option>
<option val="Opt2">Opt2</option>
<option val="Opt3">Opt3</option>
</select>
</fieldset>
​
And then looking up that parent fieldset and cloning it like this:
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
var fieldset = $(this).parents('fieldset');
if ($(this).find('option').size() > 2) {
var newFieldset = fieldset.clone();
var newComboBox = $(fieldset).children('.combo:first');
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
if (selectedValue !== '') {
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('body').append(newFieldset);
}
}
});​
There are some details probably not exactly the way you need it, but in general this is the approach I'd recomment.
Find the updated Fiddle here: http://jsfiddle.net/JaVVe/8/

If you just want to double the amount of combo boxes you could use a for-loop and set their values depending on the value of the counter-variable.

Related

How to populate a dropdown select box by matching contained text?

I have created two identical dropdown select boxes as below:
HTML
<select id="ddl1" name="ddl1">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
<select id="ddl2" name="ddl2">
<option value="1">TEXT 1</option>
<option value="2">TEXT 2</option>
<option value="3">TEXT 3</option>
</select>
Using jquery I have created code to update the value of one when the other changes and vice versa as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option[value="' + val + '"]').prop('selected', true);
$(a).selectmenu('refresh');
}
};
My requirements now are to update the select boxes based on their contained TEXT and not their value.
QUESTION
How to update a dropdown select box based on another select box contained TEXT?
After some research I have tried but failed to do this as below:
JQUERY
var a = ('#ddl1'),
b = ('#ddl2');
$(a + ',' + b).change(selectddl);
$(selectddl);
function selectddl() {
var val = $(this).val();
var text = $(this).text();
if (this.id === 'ddl1') {
$(b + ' option[value="' + val + '"]').prop('selected', true);
$(b).selectmenu('refresh');
} else if (this.id === 'ddl2') {
$(a + ' option:contains("' + text + '")').prop('selected', true);
$(a).selectmenu('refresh');
}
};
CLICK FOR DEMO
Can anyone explain how this can be achieved?
The correct answer to this question would NOT use contains due to the conflicts that could arise with text such as:
TEXT
TEXT1
You can use the .filter() function to achieve what you are requesting. You will basically need to select all of the options, then call .filter(), passing in a function that only accepts the option who's text is equal to what you expect.
For example, your else if statement might look like this:
else if (this.id === 'ddl2') {
$(a + ' option').filter(function() {
return this.text === text;
}).prop('selected', true);
$(a).selectmenu('refresh');
}
Also, it looks like you need to change your text variable as well. You should change it to something that will select the text of the currently selection option, like so:
var text = $(this).find(':selected').text();
Here's a working Fiddle.

Counting no. of dropdownlists inside a div

<div id="myDiv">
<select id="ddl1" name="31">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected="selected">Three</option>
</select>
<select id="ddl2" name=32>
<option value="1">A</option>
<option value="2" selected="selected">B</option>
<option value="3">C</option>
</select>
</div>
Thats my div. The number of dropdowns inside this div vary. What I want is this in a string:-
31,3||32,2
The above is name attribute value of dropdowns, 2nd number after comma is the "value" of the selected option and values of both dropdownlists are separated by pipe symbol. The dropdowns can be 3 and 4 in number too. How can I acheive this in jquery?
A little something like this:
var selects = [];
$("#myDiv select").each(function() {
selects.push(this.name + "," + $(this).val());
});
var output = selects.join("||");
Where the .each() method is used to iterate through all the select elements and push their name and current value into the selects array, then the array .join() method is used to turn the array into a string using "||" as the separator.
try this snippet:
var output = [];
$('#myDiv select').each(function() {
output.push([this.name, $(this).val()].join(','));
});
console.log(output.join('||'));
Try the following:
var values = [];
$('#myDiv select').each(function() {
values.push($(this).attr('name') + ',' + $(this).val());
});
var result = values.join('||');
var val = "";
$("select").each(function(){
val += $(this).attr("name") + "," + $("option:selected",this).val()+ "||";
})
if(val != "")
val = val.substring(0, val.length - 2);
console.log(val);

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;
}

How do i manipulate select box using jquery?

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

Set class of div with value of selected option in list

Using jquery, I need to set the class of a div using a select list.
For instance:
<select name="id[3]" id="id[3]">
<option value="11">- Please Select -</option>
<option value="16">Something</option>
<option value="15">Something else</option>
<option value="13">Etc...</option>
</select>
And this is the div that needs the class to be updated:
<div id="textpreview" class="textpreview"></div>
I have tried this code but I'm afraid my understanding of jquery is lacking:
$('#id\\[3\\]').change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
if (str==16){
$("#textpreview").attr('class', 'sixteen');
}
})
.trigger('change');
Any ideas?
I think you want to do what I have in this jsfiddle. The code goes like this:
$('#id\\[3\\]').change(function () {
if ($(this).val() === "16"){
$("#textpreview").addClass('sixteen');
} else
{
$("#textpreview").removeClass('sixteen');
}
}).trigger('change');
var $textpreview = $("#textpreview");
$('#id\\[3\\]').change(function() {
var val = $(this).val();
if (val == 16)
$textpreview.addClass('sixteen');
else
$textpreview.removeClass('sixteen');
});

Categories

Resources