Carlos
Carlos

Reputation: 11

Jquery - Fill an input text when select option

I have this form's elements:

<form ...>
    <select name="type[]" id="type[]">
        <option value="1">One</option>
        <option value="2">Two</option>
    </select>
    <input type="text" name="tvalue[]" id="tvalue[]" />

    <select name="type[]" id="type[]">
        <option value="1">One</option>
        <option value="2">Two</option>
    </select>
    <input type="text" name="tvalue[]" id="tvalue[]" />
    ...

    <input type="submit" value="send" />
</form>

so, I need fill the input text element when select option element change. (array of elements?) can anybody help me, please?

The markup above is result of this PHP script (I changed the markup above):

<?php
echo "<form name='form1' id='form1' action=\"#\" method='post'>";
for ($i=0; $i<5; $i++){
echo "<select name='type[]' id='type[]'>\n";
echo "<option value ='1'>One</option>\n";
echo "<option value ='2'>Two</option>\n";
echo "</select>\n";
echo "<input type='text' name='tvalue[]' id='tvalue[]' value=''>";
}
echo "<input type='submit' name='submit' id='submit' value='enviar' />";
echo "</form>";
?>

(type[] and tvalue[] because of I ned post this an array)

The problem is that I need fill the input text when I select option. For example, when I select option "One" in the first select, then the first input text must show "One", and so when I select an option in the second select, and the third, and so... So when I submit the form I can get this values.

Thanks you very much! Carlos.

Upvotes: 1

Views: 22928

Answers (2)

karim79
karim79

Reputation: 342635

1 - Remove dupe IDs they are not valid.

2 - Assuming your markup is exactly what you posted, give or take more selects and corresponding textboxes, and no elements in between:

$("select[name='type[]']").change(function() {
    $("input[name='tvalue[]']").eq($(this).index()).val(this.value);
}).change(); // set initial textbox value on page load

Demo: http://jsfiddle.net/NPeJL/2/

Upvotes: 3

Juan Sebastian Totero
Juan Sebastian Totero

Reputation: 505

I write down the example in the case of only one select and one input to modify

$('select#id1').change(function(){ //the event here is change
    if ($(this).val() === "1" ) //check the value into the select
    {
        $('input#id2').val("ONE!"); //change the value into the input
    }
    else
    {
        $('input#id2').val("TWO!"); //change the value into the input
    }
});

Upvotes: 3

Related Questions