问题
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