Jaakko Uusitalo Jaakko Uusitalo - 4 months ago 6
jQuery Question

Input field value + extra value that is toggleable

I have input field that already has value, let us call that value: "value0". When user checks a checkbox "1" will appear behind "value". Now input field value should be "value1". When user uncheck checkbox, input field should have value "value0".

$('input#inputfield1').change(function(){
var yes = '1';
$("input#answer").val($("input#answer").val()+yes);
});


How can I make that toggleable? I tried to search online, but couldn't find any clues how to proceed. Am I doing anything right?

EDIT: thanks to Utkanos

$('input#inputfield1').change(function(){
var answer = $("input#answer").val();
$("input#answer").val(answer+($(this).is(':checked') ? 1 : 0));
});


Currently output is value0101010...if user keeps switching between checked and unchecked. IT has to be value0 or value1.

This one worked! Thank you for your assistance! Any suggestions for better title?

$('input#inputfield1').change(function(){
var answer = $("input#answer").val();
$("input#answer").val(answer.substring(0, answer.length - 1)+($(this).is(':checked') ? 1 : 0));
});

Answer

This should work:

$('input#inputfield1').change(function(){
    var answer = $("input#answer").val();
    $("input#answer").val(answer.substring(0, answer.length - 1)+($(this).is(':checked') ? 1 : 0));
});
Comments