3

I've made a jQuery script, appending/adding to the existing value of an input field. I am doing this by checking if a checkbox is checked, if it is, add text, if it is yet again unchecked, I want to remove that text - not clear the entire value, just remove that little part of the value - I've tried to do this by replacing the added value with nothing, but it doesn't seem to work.

Here is my script;

$(document).ready(
  function(){
    $('.checkbox').change(function(){
    if ($(this).is(':checked')) {
      if($('#output').val().indexOf('?') >= 0) {
        var input = $( "#output" );
        $('#output').val($('#output').val() + '&avatar');
      } else {
        $('#output').val($('#output').val() + '?avatar');
      }
    } else {
      $('#output').val(value.replace('?avatar', ''));
      $('#output').val(value.replace('&avatar', ''));
    }
  });
});

I am not the best at jQuery here - I only really do it if I have to, so I might just miss the obvious here.

Here's a jsFiddle including my HTML as well.

I've been struggling with this here for a while, any help appreciated - thank you in advance!

1 Answer 1

3

Your fiddle had some error - your div container had class checkbox also, so was causing a double-click.

Also fixed up some other pieces, nothing called value was defined.

https://jsfiddle.net/vws4hpez/1/

$(document).ready(
  function() {
    $('.checkbox').change(function() {
      if ($(this).is(':checked')) {
        console.log('checked');
        if ($('#output').val().indexOf('?') >= 0) {
          var input = $("#output");
          $('#output').val($('#output').val() + '&avatar');
        } else {
          $('#output').val($('#output').val() + '?avatar');
        }
      } else {
        console.log('not');
        $('#output').val($('#output').val().replace('?avatar', ''));
        $('#output').val($('#output').val().replace('&avatar', ''));
      }
    });
  });

*HTML:

<div class="checkboxDiv">
  <label>
    <input id="avatar" type="checkbox" class="checkbox">Player avatar</label>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, I was really just missing the obvious here :) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.