DDDD
DDDD

Reputation: 3940

Get name value and put value to another name

I want to get the value of my several select options by name and take the one with a value (only one will have a value) then give the value to a name for the form.

So this is the form options, I'm leaving out all but the part with the name:

<select class="form-control input-lg" id="question_product_id" name="red"><option value="">Select a product</option>...
<select class="form-control input-lg" id="question_product_id" name="blue"><option value="">Select a product</option>
<select class="form-control input-lg" id="question_product_id" name="green"><option value="">Select a product</option>

The form looks for the value of this name, question[product_id] not green or red or blue. I am new to javascript and jquery. This is what I tried, but doesn't work:

$(document).ready(function() {
    if ($('#red').val())
    {
        $('#question[product_id]').val() == $('#test').val()
    }
});

Is there a way to check the red blue and green selects for a value and if it does give it to question[product_id] for the server to grab?

So say for example out of the three selects I have the user selects a value in the one with name="red". The value can be "1". Before the form submits I want to pass the value of "1" to another hidden non used select with the name "question[product_id]". So the select with the name question[product_id] would now have the value of "1" and the server would take it.

Upvotes: 0

Views: 162

Answers (1)

Patrick Q
Patrick Q

Reputation: 6393

My guess is that you'll actually want to fire this on some event like a click or change, instead of on document ready like you're currently doing.

$('select').each(function(){
    if($(this).val())
    {
        $("[name='question[product_id]']").val($(this).val());
        return;
    }
});

DEMO

Upvotes: 1

Related Questions