获得最接近的选择

时间:2013-11-22 09:52:51

标签: jquery select option

我无法在多个表单(具有多个提交按钮)的提交按钮附近找到最接近的选定选项(文本)。 但我没有得到任何解决方法?

代码:

$(document).ready(function() {
    $("form").submit(function() {
        var x = $(this).closest('form').find('input[type=submit]');
        var y = $(x).closest('select option:selected').text();
        alert(y);
        });
    });

<form action="<?php echo site_url('manage/deleteVendor'); ?>" method="POST">
    <table cellspacing='10'>
        <tr>
            <td>Delete Vendor</td>
        </tr>
        <tr>
        <td>Vendor</td>
        <td><select name="vendor" class="vendor">
            <?php foreach ($vendors as $vendor) { ?>
            <option value="<?php echo $vendor->ID; ?>" ><?php echo $vendor->NAME; ?></option>
            <?php } ?>
        </select></td>
        <td><input type="submit" name ="submit" value="Delete Vendor"/></td>
        </tr>
    </table>
</form>

<form action="<?php echo site_url('manage/deleteVendor'); ?>" method="POST">
    <table cellspacing='10'>
        <tr>
            <td>Delete Vendor 2</td>
        </tr>
        <tr>
            <td>Vendor</td>
            <td><select name="vendor" class="vendor">
                <?php foreach ($vendors as $vendor) { ?>
                <option value="<?php echo $vendor->ID; ?>" ><?php echo $vendor->NAME; ?></option>
                <?php } ?>
                </select>
            </td>
            <td><input type="submit" name ="submit" value="Delete Vendor"/></td>
        </tr>
    </table>
</form>             

1 个答案:

答案 0 :(得分:2)

找到距离最近的select并在其中找到所选的option,然后.html()获取文字。

var y=$('selector').closest('select').find(':selected').html(); //find the text
var x=$('selector').closest('select').find(':selected').val(); //find the value

alert(y);
alert(x);

编辑:查看HTML后

var SelectedOptionText=$('.vendor').find(':selected').html();
alert(SelectedOptionText);

修改:根据您的提交

$(document).ready(function() {
    $("form").submit(function() {
         var x =$(this).find('.vendor :selected').html();
         alert(x);
    });
});