Issue
I'm working on a jQuery input to get all the values of the selectboxes clicked on select options. When I click all the values after the first option, I am unable to see the selected values unless I go back and re-click the first option. What I'm trying to do is make it so each time an option is clicked, it automatically shows on a div or input value. Also, when unclicked, it will be removed.
My jQuery Code.
$(document).ready(function() {
$("#checku").change(function() {
var favorite = [];
$.each($("input[type='checkbox']:checked"),
function(){
favorite.push($(this).val());
$("#values").val(favorite.join(", "));
});
});
});
My Form HTML
<form id="formu">
<input type="text" id="values" name="values">
<ul>
<li>Title One <input type="checkbox" id="checku" name="checku[]" value="1"></li>
<li>Title Two <input type="checkbox" id="checku" name="checku[]" value="2"></li>
<li>Title Three <input type="checkbox" id="checku" name="checku[]" value="3"></li>
<li>Title Four <input type="checkbox" id="checku" name="checku[]" value="4"></li>
<li>Title Five<input type="checkbox" id="checku" name="checku[]" value="5"></li>
<li>Title Six <input type="checkbox" id="checku" name="checku[]" value="6"></li>
</ul>
Solution
First, like the comments IDs
should be unique!
Try this:
$(document).ready(function() {
$("input[type='checkbox']").change(function() {
var favorite = [];
$.each($("input[type='checkbox']:checked"),
function() {
favorite.push($(this).val());
$("#values").val(favorite.join(", "));
});
if ($("input[type='checkbox']:checked").length == 0) {
$("#values").val('')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="formu">
<input type="text" id="values" name="values" />
<ul>
<li>Title One
<input type="checkbox" id="check1" name="checku[]" value="1" />
</li>
<li>Title Two
<input type="checkbox" id="check2" name="checku[]" value="2" />
</li>
<li>Title Three
<input type="checkbox" id="check3" name="checku[]" value="3" />
</li>
<li>Title Four
<input type="checkbox" id="check4" name="checku[]" value="4" />
</li>
<li>Title Five
<input type="checkbox" id="check5" name="checku[]" value="5" />
</li>
<li>Title Six
<input type="checkbox" id="check6" name="checku[]" value="6" />
</li>
</ul>
</form>
I binded the event to the input
. But if you want, you can change it to a specific group of inputs
, for example adding the class titles
to the ul
and doing $('.titles input[type='checkbox']')
as the selector.
Answered By - Joel Almeida
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.