anon
anon

Reputation: 77

Dynamically pass in values to the data object

Currently, I get the value of an id and pass it in my data object to be sent to the server.

const field_value = $('#id_field').val();
const scores_value = $('#id_scores').val();
$.ajax({
    data: {'Fields':field_value, 'Scores': scores_value},
});

I want to achieve this dynamically in case I add more forms so it can automatically update without me having to change any code.

I tried using the jquery each method to access the class.

$(".class").each(function() {
    const get_updated_value = $(this).val();
});

This dynamically gets the values, but I am having trouble passing the returned values to the data object.

Upvotes: 2

Views: 335

Answers (1)

biberman
biberman

Reputation: 5767

If each element with '.class' has still an own id you could take these id's as the keys of the data object:

var updated_values = {};

$(".class").each(function() {
    updated_values[$(this).attr('id')] = $(this).val();
});

$.ajax({
    data: updated_values,
});

Working example:

function update() {
    var updated_values = {};
  
    $(".input").each(function() {
        updated_values[$(this).attr('id')] = $(this).val();
    });
  
    console.log(updated_values);
}
input {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
    <input type="text" placeholder="My task" id="field" class="input">
    <input type="text" placeholder="My date" id="scores" class="input">
    <input type="text" placeholder="My time" id="something_new" class="input">
    <input type="button" value="Update" onclick=update() id="save">
</div>

Upvotes: 2

Related Questions