Reputation: 3014
I'm trying to take the values of checkboxes and put them into an input field after they are checked. By using JavaScript, I am able to display these values within a <span>
tag. However, when I try to do this within an <input>
tag, they do not appear.
HTML:
<table width="680" border="0" cellspacing="0" cellpadding="5">
<tbody>
<tr>
<td width="550" nowrap=""><br>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="1" oncheck="cat_id.value=1" />Value 1</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="2" oncheck="cat_id.value=2" />Value 2</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="3" oncheck="cat_id.value=3" />Value 3</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="4" oncheck="cat_id.value=4" />Value 4</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="5" oncheck="cat_id.value=5" />Value 5</label>
</li>
</ul>
</div>
</td>
</tr>
<!-- Display values from checkboxes within this input tag -->
<tr>
<td>
<div class="dropdown_box">
<input name="cat_id" type="text" id="cat_id" />
</div>
</td>
<td width="550" nowrap=""> </td>
</tr>
</tbody>
</table>
JavaScript:
$(function () {
$(".dropdown_container input").change(function () {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box input");
span.html(checked.map(function () {
return $(this).val().replace("_"," ");
}).get().join(", "));
});
});
Upvotes: 1
Views: 70
Reputation: 36609
Use
.val()
instead of.html()
as you are settingvalue
property of the element, not updatinginnerHTML
of the element
$(function() {
$(".dropdown_container input").change(function() {
var checked = $(".dropdown_container input:checked");
var span = $(".dropdown_box input");
span.val(checked.map(function() {
return $(this).val();
}).get().join(", "));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table width="680" border="0" cellspacing="0" cellpadding="5">
<tbody>
<tr>
<td width="550" nowrap="">
<br>
<div class="dropdown_container">
<ul id="select_colors">
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="1" />Value 1</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="2" />Value 2</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="3" />Value 3</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="4" />Value 4</label>
</li>
<li>
<label>
<input name="categories" type="checkbox" id="categories" value="5" />Value 5</label>
</li>
</ul>
</div>
</td>
</tr>
<tr>
<td>
<div class="dropdown_box">
<input name="cat_id" type="text" id="cat_id" />
</div>
</td>
<td width="550" nowrap=""> </td>
</tr>
</tbody>
</table>
Upvotes: 2