1

each time I click on a option his data-type should appear in the input.

But I want if the value is already in the .val of the input should not appear anymore and if I click twice I want to remove the data-type from input.

Here is my Jsfiddle:

$('.checkbox').on('click', function () {
        var type = $(this).data('type'),
                answer = $('.answer'),
                initial = $('.answer').val();

        $(this).toggleClass('checked');

        if (answer.val().length === 0) {
            answer.val(type);
        } else {
            answer.val(initial + ',' + type);
        }


    });

http://jsfiddle.net/xbwocrf3/

Thanks!

1
  • Is there a reason to use this special type of "checkbox", and not the native <input type="checkbox">? Commented Dec 16, 2014 at 9:48

6 Answers 6

7

One solution is using jquery map:

$('.checkbox').on('click', function() {
  $(this).toggleClass('checked');
  //save the values of checked in an array
  var answerValues = $(".checkbox.checked").map(function() {
    return $(this).data("type");
  }).get();

  //update input text with this values
  $(".answer").val(answerValues);
});
.checkbox.checked {
  border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />

<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>

Sign up to request clarification or add additional context in comments.

5 Comments

Pretty much the same to my fiddle. By the way, return $(this).attr("data-type"); can be return $(this).data("type");
There is no differnce in this situation, but .data('type') is a little shorter.
Thanks for your answers, what if I have multiple inputs jsfiddle.net/xbwocrf3/7 like this? Why is adding the inital values to the second input?
You can go this way fiddle. Add to the selector a second argument(provides the context in which to search the element matched by the first selector).
And my version of the same, but without $('.wrap').each.
0

Do another check before adding the value there:

$('.checkbox').on('click', function () {
    var type = $(this).data('type'),
        answer = $('.answer'),
        initial = $('.answer').val();

    $(this).toggleClass('checked');

    if (answer.val().length === 0) {
        answer.val(type);
    } else if (!new RegExp("\,?" + type + "\,?").test(initial)) {
        answer.val(initial + ',' + type);
    }
});
.checkbox.checked {
    border:2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="answer" />
<div class="checkbox" data-type="1">Option #1</div>
<div class="checkbox" data-type="2">Option #2</div>
<div class="checkbox" data-type="3">Option #3</div>
<div class="checkbox" data-type="4">Option #4</div>

Comments

0

Use jQuery's map function to get the type data from all elements. Then combine using the join function.

http://jsfiddle.net/xbwocrf3/8/

$('.checkbox').on('click', function() {
    var answer = $('.answer');
    $(this).toggleClass('checked');
    answer.val( $(".checkbox.checked").map(function() {return $(this).data("type")}).get().join(", ") );
});

3 Comments

Thanks for your answers, what if I have multiple inputs jsfiddle.net/xbwocrf3/7 like this? Why is adding the inital values to the second input?
In such a case you need to select the checked items that are children of a certain common parent. That said you could (and should) wrap both the answer and the options in an element and refer to that when querying the selected answers.
Or refer to everything by parent. This is less clean but still works: jsfiddle.net/xbwocrf3/11
0

This solution is a little cleaner:

http://jsfiddle.net/xbwocrf3/9/ (link updated, I pasted it wrong before)

  • It uses native checkboxes
  • Instead of doing something as hard as trying to remove old values, it rewrites the whole value of the input from scratch
  • The items appear always in their natural order

HTML

<input type="text" class="answer" />

<div>
<input type="checkbox" value="1" name="something" id="something1"/>
<label for="something1">Option #1</label>
</div>

<div>
    <input type="checkbox" value="2" name="something" id="something2"/>
    <label for="something2">Option #2</label>
</div>

<div>
    <input type="checkbox" value="3" name="something" id="something3"/>
    <label for="something3">Option #3</label>
</div>

<div>
    <input type="checkbox" value="4" name="something" id="something4"/>
    <label for="something4">Option #4</label>
</div>

CSS

input[type="checkbox"]{
    display: none;
}
input[type="checkbox"]:checked + label{
    border:2px solid green;
}

Javascript

$('input[type=checkbox]').on('change', function() {
    var $answer = $(".answer");

    var checked_values = $.map($("input:checked"), function (element){
        return element.value;
    });

    $answer.val(checked_values);       
});

Comments

0

please check fiddle

    $('.checkbox').on('click', function () {

    $(this).toggleClass('checked');

    var typen = '';
    $(".checkbox").each(function () {
        var type = $(this).data('type');
        if ($(this).hasClass('checkbox checked')) {
            typen = typen + ',' + type;
        }

    });

    if (typen.length > 0) {
        typen = typen.substring(1, typen.length);
    }

    $('.answer').val(typen);

});

1 Comment

Have you checked your own fiddle? First of all, there is $('.answer').val(); instead of $('.answer').val(''); in fiddle. Secondly, the idea is to show all selected options, not only last one. And finally it will be better to save $('.answer') in variable (answer) in the very beginning of code and to use variable instead of multiple same selections.
0

Check if the input has checked class:

if($(this).hasClass('checked'))
        return;

Final:

$('.checkbox').on('click', function() {
    if($(this).hasClass('checked'))
        return;//Stop the execution of the function

    var type = $(this).data('type'),
        answer = $('.answer'),
        initial = $('.answer').val();

    $(this).toggleClass('checked');

    if(answer.val().length === 0) {
        answer.val(type);
    } else {
        answer.val(initial +','+ type);                   
    }

});

Comments

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.