LeoMogMooseBell LeoMogMooseBell - 2 months ago 6
HTML Question

trying to remove something from value using jquery

I would like the value of the input to change when the checkbox is checked and unchecked.

I have it working so that when a box is checked the values of the unchecked boxes becomes


"ATTPVAT2", "ATTPTAX2", "ATTPBHS2"


etc. but I am not sure how to set up the jquery so when a box is unchecked it removes the 2 and becomes


"ATTPVAT", "ATTPTAX", "ATTPBHS"


again.

The line

var core2Name = $(".ATT:not(:checked)").val() - "2";


returns a NaN



function core2() {
var i = 0;

$('.ATT').each(function() {
if ($(this).is(':checked')) {
i += 1
}
});
$('.ATT').each(function() {
if ($(this).is(':not(:visible)')) {
i += 1
}
});

if (i < 0) {
var core2Name = $(".ATT:not(:checked)").val() - "2";
$(".ATT:not(:checked)").val(core2Name);

};


if (i == 1) {
$(".ATT:checked").prop('disabled', true);
var core2Name = $(".ATT:not(:checked)").val() + "2";
$(".ATT:not(:checked)").val(core2Name);

};

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="examlist" value="ATTPTAX" id="ATTPTAX1" class="ATT" onclick=" if(core2()){this.checked=false}; " />
<input type="checkbox" name="examlist" value="ATTPVAT" id="ATTPVAT2" class="ATT" onclick=" if(core2()){this.checked=false}; " />
<input type="checkbox" name="examlist" value="ATTPBHS" id="ATTPBHS3" class="ATT" onclick=" if(core2()){this.checked=false}; " />




Answer

- is for subtraction of numbers, it doesn't work with strings. You get NaN because "ATTPVAT2" isn't a number, so it doesn't make sense to perform arithmetic with it.

The function to remove a character from a string is String.prototype.replace. It should be:

var core2Name = $(".ATT:not(:checked)").val().replace('2', '');
Comments