javascript - alerting an input value onclicking a label with for='' attribute -


if have following code

    $('.ale').click(function(){        var val = $('.val').val();        alert(val);      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>        <label class='ale' for='hello'>      <input class='val' type='text' id='hello' value='hello'>            <label class='ale' for='world'>      <input class='val' type='text' id='world' value='world'>
in code, i'm trying make script alert value of input clicking on label

but won't work since gets first value = 'hello'

how can define onclick value of input id attr = attr?

just value of for attribute of label , use find input same id value.

    $('.ale').click(function(){        var val = $(this).attr('for');        alert($('#'+val).val());      })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>        <label class='ale' for='hello'>label 1</label>      <input class='val' type='text' id='hello' value='hello'>            <label class='ale' for='world'>label 2</label>      <input class='val' type='text' id='world' value='world'>


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -