Create a dynamic checkbox value (value) using ajax

Asked

Viewed 416 times

1

I have an ajax code http://jsfiddle.net/rubensoul/dcb14q79/ and I need the values that appear to be dynamic, example:

In the link I put has 3 inputs and in js I created for only 1, if I put for everyone it would send normally

    checkbox:$($("#checkbox input")[0]).prop("checked")?$($("#checkbox input")[0]).val():'',

Except that I need these values to be dynamic, that is, I do not need to put 1 by 1. I would put only 1. that it would assign the value of each input automatically without having to touch this code again.

It’s possible and how I can fix it?

I stand by

  • How do you want to receive this in PHP? a string? a JSON?

  • Sorry, I forgot to mention this, it is by json it will be updated it gets the values

1 answer

1


From your HTML you get the idea that all inputs are descended from this div #checkbox.

So you can use the .find() to find the inputs and then using the .filter() and the .map() create an array of values that are checked. Then you can send this as JSON in AJAX. I also used .get() jQuery to give me a native array and only work with native Javascript from there.

Something like that:

$('#checkbox').on('click', function () {
    var checkboxes = $(this).find('input[name="checkbox[]"]').get().filter(function (input) {
        return input.checked;
    }).map(function (input) {
        return input.value;
    });
    $.ajax({
        type: "POST",
        url: "teste4.php",

        data: {
            checkbox: JSON.stringify(checkboxes),
            profissional: $("#profissional").val()
        },
  • How would the inputs in html look in this case, it delivers the values to the json of test4? I need to change the value="" of it?

  • @Rubensjunior in HTML is like you have in jsFiddle. The value that passes is respectively "clinical", "pediatric" and "dermatologist".

  • 1

    It worked out your tip, solved my problem, thank you very much

  • all right? sorry to return to this topic, but how do I return this code to the default value after canceling the click? he’s getting the same value of flagged, I did something wrong?

  • @Rubensjunior what do you call "default value"? the value you had when you opened the page?

  • It has the default time value, (which waits for the professional fill to release) and when clicked on one of the checkbox, it sends the checkbox value, only when unchecking, it does not return to the 'default' http://rubensoul.com.br/teste/agendar-interno.html

  • @Rubensjunior, did you find the problem? i don’t think this is related to my answer but if you need help later when I’m home I can take a look.

  • Your answer is perfect, and working. That last doubt would only be a complement

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.