views:

31

answers:

1

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>
+3  A: 

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.

Nick Craver
@Nick - I actually have a value called "value" so I dont think that .val() will work as it always returns false. Thats why I currently had it like [value="true"]
Bruno
@Bruno - `.val()` should return a string, not true/false...can you post the HTML markup?
Nick Craver
@Nick - Added Above.
Bruno
@Bruno - `.val()` will return the string `"true"` for those, you can view/play with a test of my code above and your markup: http://jsfiddle.net/sExuE/
Nick Craver
@Nick - Changing the value to "false" will still return opt-in
Bruno
@Bruno - I'm not seeing that behavior...here's a version of with them set to false, getting `opt-out`: http://jsfiddle.net/sExuE/1/
Nick Craver
@Nick - Ahh.. I see it now. Thank you very much!
Bruno
@Bruno - Welcome! :)
Nick Craver