Reputation: 12933
I have a rather unique issue in jquery to solve. I have a div wrapper:
<div class="formWrapper"></div>
This contains a set of elements that should, when they change (doesn't matter which element changes) - should (for example) be stored in a data object, and that object logged to the console - for now.
So:
<div class="formWrapper">
<div class="floatRight">
<div>
<label>Select a Project Manager</label>
<select class="projectManager">
<?php foreach($projectManagers as $name){ ?>
<option><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Select a Division</label>
<select class="division">
<?php foreach($divisions as $division){ ?>
<option><?php echo $division['division_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="floatLeft">
<div>
<label>Select a Client</label>
<select class="client">
<?php foreach($clients as $client){ ?>
<option><?php echo $client['client_company_name']; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Choose a Date</label>
<input type="text" class="date" placeholder="Click to choose a date"/>
</div>
</div>
</div>
Pretty simple to see whats going on. But what if projectManager
changes or divison
or ... both, or all the elements, a simple change()
might work for one element but I need to watch all the element and dynamically update a data object such that each time an element changes, the console spits out a different data object.
The end goal
Have a data object, for example data = {pm : pm_selected_value}
for if the user JUST selects pm and then, if they change division - the data object should update to should: data = {pm : pm_selected_value, divsion: division_selected_value}
and so on ...
I know how to get the value of each element, I don't know how to create a dynamic data object like this while watching each element.
The catch, and I think change()
from reading the docs does this, is that even if I have a data object like this:
data = {pm : pm_selected_value, divsion: division_selected_value}
and I go an update the pm (so selecting a different pm), the data object should instantly update to reflect that change:
data = {pm : pm_selected_NEW_value, divsion: division_selected_value}
Now I can apply .change()
to each element - but is there no way to apply it to a div to say - "excuse me mr JavaScript - please watch all form elements inside here for change, k thanks."
Upvotes: 1
Views: 499
Reputation: 20747
What you are looking to do it listen for any select value to get changed within the <div class="formWrapper"></div>
so you should target the <div>
and attach the change event to child <select>
s
var choices = new Object();
$('.formwrapper').on('change', 'select', function(){
choices[$(this).attr('name')] = $(this).val();
console.log(choices);
});
One thing you should do is provide a unique name=""
for each <select>
so that you know what you are dealing with inside of the anonymous function()
Upvotes: 1