I have a project that merges in one form field two variables.
- Number of rooms
- Number of persons per room.
This only field will have the value each room/persons per room and each room will be delimited by “|”.
So you have 3 rooms and 2 persons in each room = 2|2|2
Or 2 rooms, 1st room 2 persons and 2nd room 3 persons = 2|3
I have ready two jQuery functions:
- A cloning of the # of persons and
- The update of the values of the cloned items.
The problem I have is that each function works independently and when the users update one the single form field dos not update.
How can merge or update the two functions that work as one?
I have posted a working example @
Here is the HTML code
Number of rooms<br />
<select id="itemCount" name="itemCount">
<option selected value="1">1 item</option>
<option value="2">2 items</option>
<option value="3">3 items</option>
<option value="4">4 items</option>
</select><br /><br />
Number of persons<br />
<select name="cloneElement1" id="item_dup_1" class="room">
<option value="">Select One</option>
<option value="1">1</option>
<option selected value="2">2</option>
<option value="3">3</option>
</select><br /><br />
<input type="text" name="myNumbers" value="2">
And here the jQuery
// fn Clone Boxes
jQuery.fn.fieldsManage = function (number) {
var ele = $(this);
var clones = ele.data("clones");
clones = clones ? clones : new Array(ele.attr("id"));
if (clones.length < number) {
var clone;
while(clones.length < number) {
clone = ele.clone(true);
var id = clones[0]+clones.length;
clone.attr("id", id);
$("#"+clones[clones.length-1]).after(clone);
clones.push(id);
}
} else {
while(clones.length > number) {
$("#"+clones.pop()).remove();
$(function(){
$("[name='myNumbers']").val(myNumbers.join('|'));
});
}
}
ele.data("clones", clones);
}
// Create Clone Boxes
$(document).ready(function() {
$("#itemCount").change(function() {
$("#item_dup_1").fieldsManage(this.value);
});
});
// Values from Cloned Boxes
$(function(){
$('.room').change(function(e){
var myNumbers = [];
$('.room').each(function(){
myNumbers.push($(this).val());
})
$("[name='myNumbers']").val(myNumbers.join('|'));
});
});
Is your problem that the value is not refreshing when you select a different number of rooms? If so take a look at this http://jsfiddle.net/gSkpq/
Note you can use jQuery’s live to bind an event to elements that might be dynamically added and removed