Receive select fill in jQuery

Asked

Viewed 391 times

0

I made a table where each row has a select and update button. The problem is that when I click on the update of a certain line I want to update only that line and therefore I need to receive by jQuery only the number that is in the select of that line. The way I did I get the numbers that are in the select of all lines.

HTML:

<table border="0">

    <tr>

        <td class="td">
            Número
        </td>

    </tr>

    <?
    for($i = 0; $i < 10; $i++){
    ?>

        <tr class="tr">

            <td class="td">
                <select id="num">
                    <?php 
                    for($k = 1; $k < 5; $k++){
                        echo "<option> $k </option>";
                    }
                    ?>
                </select>

            </td>


            <td class="td">
                <form id="formulario" action="javascript:func()" method="post">
                    <input type="submit" value="Atualizar" />
                </form>
            </td>
        </tr>
    <?
    }
    ?>

</table>

jQuery:

<script type="text/javascript" language="javascript">

    $(document).ready(function(){
        $("form").submit(function(){
            var num = $("#num option:selected").text();
            alert(num);
        });
    });


</script>

Upshot: result

I would like it to appear only 1 or 4 or 3... depending on the line that is the "Update".

  • If you leave the id="form" in the loop you will have duplicated id in your HTML which is not recommended.

1 answer

2


Your problem lies in the selector as you are generating several <select> no for and they all have the id, which is unique, it can identify as only one,if you use class or even the tag to select will work.

Example:

$(document).ready(function() {
  $("form").submit(function() {
    num = $(this).find('.num option:selected').text();
    alert(num);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
  <select class="num">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
  <input type="submit" value="Atualizar">
</form>

<form>
  <select class="num">
    <option>4</option>
    <option>5</option>
    <option>6</option>
  </select>
  <input type="submit" value="Atualizar">
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.