I have 2 input fields inside a div within a form element like this
<form>
<div id="si-goal-section">
<div class="si-goal-container">
<input type="text" class="si-input goal-icon" name="goal-icon">
<input type="text" class="si-input goal-title" name="goal-title">
</div>
</div>
<div>
<button type="button" id="goal-btn">Add goal</button>
</div>
</form>
When i click on the button "Add goal" i am appending a new "si-goal-container" div. This is the script for that
$('form #goal-btn').click(function() {
$('form #si-goal-section').append('<div class="si-goal-container"><input type="text" class="si-input goal-icon" name="goal-icon"><input type="text" class="si-input goal-title" name="goal-title"></div>')
})
i then create an array variable in JS and collect and pass the form data into it like this
var data_to_send = []
$('form').find('.si-input').each(function() {
if($(this).hasClass('goal-icon')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
if($(this).hasClass('goal-title')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
})
So this approach will not work because the name fields are the same and the values just get over written. What else could be done here so i could store the appended data in the array and access it later in the php side ?
i tried something like this
var data_to_send = {}
data_to_send.goal = []
$('form').find('.si-input').each(function() {
if($(this).attr('name') != undefined) {
data_to_send.goal.push({
'goalIcon': $(this).find('.goal-icon').val()
'goalTitle': $(this).find('goal-title').val()
})
}
})
But this too doesn't give me the required o/p i am looking for. I need my data_to_send array to look something like this in the ajax call.
...
data_to_send['bannerImage']:
data_to_send['goalName']:
data_to_send['goalIcon'][0]:
data_to_send['goalTitle'][0]:
data_to_send['goalIcon'][1]:
data_to_send['goalTitle'][1]:
...
What would be the right way to append the fields and store it into the array ? I i am using serialize() then how do i use it only for particular fields ?