Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .val() not getting value

let data = $(".language").attr('value');
let data2 = $('.language').val();
let data3 = $('.language').value;
let data4 = $(".language").attr('class');

$("button#test").click(function() {
  console.log(data);
  console.log(data2);
  console.log(data3)
  console.log(data4)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <p class="label">Language</p>
  <input type="text" class="language" name="language" placeholder="">
</div> 
<div class="button-wrapper text-center">
  <button type="button" class="button next" id="test" >Go to step 2</button>
</div>

I am working on this simple project with jQuery, and when the val() function is called or attr('value') is called it gives returns undefined. But when the attr() function is called with other attributes it works fine.

Please what should I do

like image 723
Maxwell Avatar asked Jan 29 '23 08:01

Maxwell


1 Answers

To get the value you should define those data variables inside the click event like so:

 // outside here is the <input>'s initial value (empty)
console.log('I am the initial empty value: ' + $('.language').val());
$("button#test").click(function() {
    // inside here is the <input>'s value at the time the button is clicked (not empty)
    var data = $('.language').val();
    console.log('I am the current value: ' + data);
});
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
   <p class="label">Language</p>
   <input type="text" class="language" name="language" placeholder="">
</div> 
<div class="button-wrapper text-center">
    <button type="button" class="button next" id="test" >Go to step 2</button>
</div>
like image 87
d-_-b Avatar answered Jan 31 '23 23:01

d-_-b