Fresher Programmer
Fresher Programmer

Reputation: 91

Remove Textbox Value based on Checkbox Check

I have a dynamically created checkbox. When I click on it the value gets added inside the textbox. This is working perfectly fine.

How can I remove that value when I uncheck the checkbox?

var ChkId = stringSplit[0];
var ChkName = stringSplit[1];
var checkLevel1 = $('input:checkbox[name=LevelOne' + ChkId + ']').is(':checked');
if (checkLevel1 == true) {
  var txtLevel1 = $("#<%= txtSectionData.ClientID %>").val();
  $("#<%= txtSectionData.ClientID %>").val(txtLevel1 + ChkName + "   ");
} else {
}

Upvotes: 1

Views: 126

Answers (2)

radulle
radulle

Reputation: 1525

Not the best practice what you are doing to be honest but you can simply do it like this:

var ChkId = stringSplit[0];
var ChkName = stringSplit[1];
var checkLevel1 = $('input:checkbox[name=LevelOne' + ChkId + ']').is(':checked');
var txtLevel1 = $("#<%= txtSectionData.ClientID %>").val();
if (checkLevel1 == true) {
  $("#<%= txtSectionData.ClientID %>").val(txtLevel1 + ChkName + "   ");
} else {
  $("#<%= txtSectionData.ClientID %>").val(txtLevel1.replace(ChkName + "   ","");
}

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Instead of maintaining the values when a checkbox is checked/unchecked, a much simpler pattern is to put a common class on all the checkboxes which you can use to build an array of the values whenever one changes. This can then be joined together in to a single string and set as the value of the textbox. Something like this:

$(document).on('change', '.level-one', function() {
  var values = $('.level-one:checked').map((i, e) => e.value).get().join(', ');
  $('#section-data').val(values);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
  <input type="checkbox" class="level-one" value="foo" /> Foo
</label>
<label>
  <input type="checkbox" class="level-one" value="bar" /> Bar
</label>
<label>
  <input type="checkbox" class="level-one" value="fizz" /> Fizz
</label>
<label>
  <input type="checkbox" class="level-one" value="buzz" /> Buzz
</label>
<input type="text" id="section-data" />

Upvotes: 1

Related Questions