1

I'm trying to make a quiz for myself and I want the data values of the selected radio buttons and the data value of them. So I can send them to a php file as an array or object.

This is my code:

let frm = $('#form');

    $('input[value="finished"]').on('click', function (e) {
        e.preventDefault();

        console.log($('input[type=radio]:checked').data('value'));

        $.ajax({
            type: frm.attr('method'),
            url: "ajax/quiz.php",
            data: frm.serialize(),
            success: function (data) {

            },
        }).done(function (data) {

        });
    });

Does anyone know why it only shows one? Because I have been searching for a while and a lot of people recommend this option.

Can't get input radio selected value

I also tried this: How to get the selected radio button’s value?

But it still shows me one data value.

Mark_
  • 113
  • 1
  • 12
  • As it seems, every time you change the page, the previous `input` fields are removed. Is that the case? Make sure they are hidden by CSS and not removed by JS – pouria Mar 13 '21 at 12:30
  • Also pay attention that `$('input[type=radio]:checked')` is a collection. So you should better check its length instead of using `data` method on it, because that `data` method will yield the last one's data – pouria Mar 13 '21 at 12:32
  • They get a display: none; but the elements stays. When i click the previous button the answer I selected is still there and selected, so that doesn't seem to be the problem. – Mark_ Mar 13 '21 at 12:33
  • Youre right, the length value equals 2, but how do i get those values? – Mark_ Mar 13 '21 at 12:36
  • Do your `input` fields have a `name` attribute? If they don't, `frm.serialize()` will not include them. – pouria Mar 13 '21 at 12:49
  • They do have a input and a name, the serialize is not the problem, i need something that replaces serialize because that doesnt give me the data value @pooria – Mark_ Mar 13 '21 at 13:16
  • Do you have to use `data-value` instead of `value`? – pouria Mar 13 '21 at 13:29

2 Answers2

1

You can do this in many ways. I show below two wrong ways and two correct ways:

$(function() {
    let frm = $('#form');

    $('input[value="finished"]').on('click', function (e) {
        e.preventDefault();

        /*console.log($('input[type=radio]:checked').data('value'));

        $.ajax({
            type: frm.attr('method'),
            url: "ajax/quiz.php",
            data: frm.serialize(),
            success: function (data) {

            },
        }).done(function (data) {

        });*/
        let output = document.getElementById("output");
        let val = $('input[type=radio]:checked').val();
        let data = $('input[type=radio]:checked').data('value');
        let serialized = frm.serialize();
        let accumulated = [...document.querySelectorAll('input[type=radio]:checked')].map((item) => `${item.name}=${item.value}`).join("&");
        output.innerHTML += `<p>val(): ${val}</p>`;
        output.innerHTML += `<p>data('value'): ${data}</p>`;
        output.innerHTML += `<p>serialized: ${serialized}</p>`; //works
        output.innerHTML += `<p>accumulated: ${accumulated}</p>`; //works
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
    <input type="radio" name="question1" value="answer1_1">
    <input type="radio" name="question1" value="answer1_2">
    <input type="radio" name="question2" value="answer2_1">
    <input type="radio" name="question2" value="answer2_2">
    <input type="submit" value="finished">
</form>

<div id="output"></div>
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

If you insist on saving the values inside dataset (<input data-value="" />) you can do it this way:

const values = $('input[type=radio]:checked')
  .map(function() {
    return $(this).data('value')
  })
  .get();

Now, values is an array of all data-value values in selected radio boxes.

You can read more about jQuery's map here: https://api.jquery.com/map/

pouria
  • 949
  • 8
  • 21