javascript - Check/Uncheck using jQuery not working -
i trying make check boxes behave radio buttons in asp .net mvc
web application. have got 20-30 check boxes grouped in two. example:
<input type="checkbox" id="@riggingtype.riggingtypeid 1" name="riggingtypeplus" value="@riggingtype.riggingtypeid" checked="@riggingtypeids.contains(riggingtype.riggingtypeid)" /> <input type="checkbox" id="@riggingtype.riggingtypeid 2" name="riggingtypeminus" value="@riggingtype.riggingtypeid" checked="@riggingtypeids.contains(riggingtype.riggingtypeid)" />
goal:
i want make check boxes behave in such way if plus
check box checked minus
unchecked automatically , vice versa. have written following code try , achieve functionality:
$(":checkbox").change(function () { var inputs = $(this).parents("form").eq(0).find(":checkbox"); var idx = inputs.index(this); if (this.name.substring(this.name.length - 4, this.name.length) === "plus") { // trying check if getting right // , getting right id // alert(inputs[idx + 1].id); // not work $("#" + inputs[idx + 1].id).prop('checked', false); } });
am doing wrong here:
$("#" + inputs[idx + 1].id).prop('checked', false);
any appreciated.
i know can use radio buttons , group them same name rendering elements in loop have same name different values , don't want name them differently because using data on server side... there better way this?
answer:
got working using following:
$(document).ready(function(){ $(":checkbox").on('click', function () { var $this = $(this); var inputs = $this.closest("form").find(":checkbox"); if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "plus" && $this.attr('checked')) { $this.next().prop('checked', false); } else { $this.prev().prop('checked', false); } }); });
fiddle: https://jsfiddle.net/24gmnjwm/1/
$(document).ready(function(){ $(":checkbox").on('click', function () { var $this = $(this); var inputs = $this.closest("form").find(":checkbox"); if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "plus") { $this.next().prop('checked', false); } }); });
Comments
Post a Comment