Search code examples
jqueryformsradio-buttonhover

Get the value of the related input on hovering a label using jQuery


I am trying to get the value of the input when a mouse hovers on a label. How can I deal with this?

HTML

       <label class="target">
         <input type="radio" name="hello" value="hi" class="greeting">
         <span>Hi</span>
       </label>
      <label class="target">
         <input type="radio" name="hello" value="hello" class="greeting">
         <span>Hello</span>
       </label> 

Radio buttons are hidden, so when the mouse is over the label, it is hovering the span element.

I am only getting the first element, 'hi' in jQuery.

$('.target').hover(function() {
   alert('hovering: ' + $('.greeting').val());
})

I want to show the each value.


Solution

  • $('label').hover(function(){
    alert($(this).find('input').val())
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label class="target">
      <input type="radio" name="hello" value="hi" class="greeting">
      <span>Hi</span>
    </label>
    <label class="target">
      <input type="radio" name="hello" value="hello" class="greeting">
      <span>Hello</span>
    </label>

    use .find()