David Gard
David Gard

Reputation: 12047

Get the value of the <select> directly above a clicked button

I'm trying to get the value of a <select> when a button is clicked. The <select> is directly about the button in the DOM, and I'm trying to use .closest()

My source is -

<div class="alignleft actions">
    <select id='bulk-action-selection' name='bulk-action'>
        <option value='-1' selected='selected'>Bulk Actions</option>
        <option value="delete" >Delete</option>
        <option value="open" >Open Polls</option>
        <option value="close" >Close Polls</option>
        <option value="recast_allow" >Allow Recasting</option>
        <option value="recast_deny" >Prevent Recasting</option>
        <option value="votes_show" >Show Votes</option>
        <option value="votes_hide" >Hide Votes</option>
    </select>
    <input type="submit" name="Submit" id="doaction" class="button-secondary action" value="Apply"  />
</div>

and the code that I am attempting to use is (returnin 'undefined' -

$('#doaction').click(function(e){
    action = $(e).closest('select').val();
});

Please help in getting the code to work (or suggesting better ways to go about it). Thank.

Upvotes: 0

Views: 97

Answers (4)

Clyde Lobo
Clyde Lobo

Reputation: 9174

$(function() { 
  $('#doaction2').click(function(e){
    action = $('#doaction2').prev().val();
    console.log(action);

  });
});

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

change your function like so:

$('#doaction2').click(function(e){
    action = $(this).prev('select').val();
    // or action = $('#bulk-action-selection2').val();
})

e is the event, not the reference to the element you clicked (and your button id is #doaction2)

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

I think

$('#doaction')

should be

$('#doaction2')

Full Code

$('#doaction2').click(function(e){
    action = $(e.target).prev('select').val();
});

Upvotes: 1

Andreas Wong
Andreas Wong

Reputation: 60574

e inside click is referring to event object, I think you mean $(this). Also, you are targetting wrong button, the id you are looking for is doaction2

Also, not sure if this is a typo, but you need an extra ) after $('#doaction').click():

$('#doaction2').click(function(e){
    action = $(this).prev('select').val();
}); // <-- this

But since you have already assigned an ID to the select element, might I suggest you to just target it directly:

$('#doaction2').click(function(e){
    action = $('#bulk-action-selection2').val();
}); 

This way whenever your HTML changes, you still get correct behavior.

Upvotes: 1

Related Questions