Get closest selected option

余生长醉 提交于 2019-12-25 04:35:11

问题


I am having trouble finding the closest selected option (text) near a submit button in multiple forms (with multiple submit buttons). But I don't get anything how to fix this?

Code :

$(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:


Find the closest select and find the selected option in it followed by .html() to get the text.

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);

Edit: After viewing you HTML

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

Edit: Based on your commment

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


来源:https://stackoverflow.com/questions/20141801/get-closest-selected-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!