Reputation: 2385
I have a one field which is hidden and that gets added dynamically to track the another select box's selected items.
for e.g:
hidden_field_name= count_select;
select_box_name = select1;
both gets added dynamically when user click "add" button. Now I want to store the select1's selected item count in count_select for every instance.
But when I use the val() method it write the total click's in count_select value.
Here is code:
Html code :
function getCount() {
top.count = $("select.container_countable option:selected[value!='']").length;
$('.countable').val(top.count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='hidden' class='countable' id='count_containerfilter' name='countable_cont' value=0>
<select onclick='getCount()' class='container_countable' multiple='multiple' name='new_containerfilter'>
Any idea why is this happening?
Upvotes: 2
Views: 11348
Reputation: 28387
Based on your this comment above:
what I want to achieve is : select_box = 2 item selected ,newly added select box = 3 item selected , so finally count_select should contain count_select = [2, 3]....
You could use an array to track the selections. Once done, either assign that array directly to the hidden
input
or stringify
it and assign the string.
See this snippet:
var tmp = [];
$("select.countable").on("change", function() {
tmp = [];
$("select.countable").each(function() {
var ctr = $(this).find("option:selected").length;
tmp.push(ctr);
});
$("#ctr").val(JSON.stringify(tmp));
$("#result").text($("#ctr").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='hidden' id='ctr' />
<hr/>
<select class="countable" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<select class="countable" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<hr/>
<p id="result"></p>
Here is a fiddle for you to play with: http://jsfiddle.net/abhitalks/f6o3ped8/1/
Try adding more select
s and see the result.
.
Upvotes: 1
Reputation: 10394
This code is from jQuery docs for :selected
(with slight modification):
$("select")
.change(function() {
var count = $("select option:selected").length; // Count selected
$("input").val(count); // Update field
})
.trigger("change"); // Trigger at least once
select{
height:100px;
width:100px;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option>Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option selected="selected">Dirt</option>
</select>
<input />
Upvotes: 0