Reputation:
I currently have two input fields which toggle the value "value" to either true or false.
What I would like to happen is that when the user hits the submit button, I can run an if/then statement for each input field and pass a different variable for each field, then combine those two variable into one variable.
For example.
if ($('input#one').is('[value="true"]')) {
var one = 'opt-in-one'
}
else {
var one = 'opt-out-one'
}
if ($('input#two').is('[value="true"]')) {
var two = 'opt-in-two'
}
else {
var two = 'opt-out-two'
}
var result = one + two;
This is the best that I can explain it. Any ideas how to write this to one click function?
Edit: Here is the HTML
<form>
<input type="hidden" name="optin1" id="optin1holder" value="true" />
<input type="hidden" name="optin2" id="optin2holder" value="true" />
<input type="submit" class="button" value="Submit">
</form>
Upvotes: 1
Views: 317
Reputation: 630389
There are several ways to cackle this, for instance you can do it like this:
$(":submit").click(function() {
var result = ($('input#one').val() == 'true' ? 'opt-in-one' : 'opt-out-one')
+ ($('input#two').val() == 'true' ? 'opt-in-two' : 'opt-out-two');
//do something with result
});
Of if you wanted say a format like "out-in-one,opt-out-two"
, you could use .map()
, like this:
$(":submit").click(function() {
var result = $('input#one, input#two').map(function() {
return (this.value == 'true' ? 'opt-in-' : 'opt-out-') + this.id;
}).get().join(',');
//do something with result
});
The second approach works for any number of inputs, it would be a bit cleaner if you gave them a class, then instead of 'input#one, input#two'
you could do 'input.optinout'
for example. You can also change .join(',')
to be any separator you want.
Upvotes: 2