I have some dynamic form elements that should get value from some calculation based on the text fields. While serializing the calculated fields are not serialized.
The below code represents the exact scenario
Scenario:1 while i click add button it will create the new entry but the value is (cgst_val) not placed on the text box
Scenario:2 Json serialize is not take the value which calculated using the tax_val and tax_per
$(document).ready(function() {
$("#add").click(function() {
var $clone = $('#container .group:first').clone();
$clone.find('input').val('');
$clone.find('select').val('2');
$clone.append('<a href="#" class="remove">X</a>');
$clone.appendTo('#container');
});
$("#container").on('click', '.remove', function() {
$(this).parent('.group').remove();
});
$('#container').on('input, change', ".P_tax_per", ".P_state", function() {
var $group = $(this).closest('.group');
var num1 = parseInt($group.find(".P_tax_val").val(), 10) || 0;
var num2 = parseInt($group.find(".P_tax_per").val(), 10) || 0;
var num3 = num1 / num2 * 100;
$group.find(".P_cgst_val").attr('value', num3);
});
});
$("form").submit(function() {
var result = {};
$.each($('form').serializeArray(), function() {
result[this.name] = this.value;
});
var jsonData1 = {
tax_val: result.tax_val,
tax_per: result.tax_per,
cgst_val: result.cgst_val
};
var myJSON = JSON.stringify(jsonData1);
alert(myJSON);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="button" id="add" value="ADD" />
<div id="container">
<div class="group">
<input type="text" name="tax_val" class="P_tax_val" />
<select name="tax_per" class="P_tax_per">
<option disabled selected value>GST %</option>
<option value="5">5</option>
<option value="12">12</option>
</select>
<input type="text" name="cgst_val" class="P_cgst_val" size="3" placeholder="cs" value="" disabled />
</div>
</div>
<input type="submit" name="SUBMIT" />
</form>