javascript – getting value from input field-ThrowExceptions

Exception or error:

How can I get the value from the input field in the form.
the idea is to send this value later to the server and display other values ‚Äč‚Äčassociated with it.

<form action="" method="post" autocomplete="off" id="my_form">
   <div class="txtb">{{form.date.label}} {{form.date}}</div>
   <div class="txtb"> <p class="txt"></p></div>
<input type="submit" value="send" class="btn" id="btn">

In the Input field I assigned a class=”pole” and trying to print value.

$('.pole').on('input', function() {
  var val = $('.pole').val();
  $('.txt').html(val);
$('.txt').val(val);
});

but this does not work, how can this be done?

How to solve:

Change$('.pole').val() to $(this).val() You should have to try like

$('.pole').on('input', function() {
  var val = $(this).val();
  $('.txt').html(val);
  $('.txt').val(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>


<input type="text" class="pole" placeholder="type here">
<p class="txt"></p>

###

You need to use $(this) to get the instance of current input with class=pole instead of $('.pole'), see below code

$('.pole').on('input', function() {
  var val = $(this).val();
  $('.txt').text(val);
});

###

As you want to submit value, you need to mention input field in html.
Have a look at this demo

<form id="myForm" action="/action_page.php">
  First name: <input type="text" id="fname" value="Donald"><br>
  Last name: <input type="text" id="lname" value="Duck"><br>
  <input type="button" value="Submit" onclick="submitForm()">
<p id="demo"></p>
</form> 

function submitForm() {
  var firstName = document.getElementById("fname").value;
  var lastName = document.getElementById("lname").value;
  document.getElementById("demo").innerHTML = lastName;
}

###

I think your input is sibling of paragraph. Try this:

$('.pole').on('keyup', function() {
   $(this).parent().find(".txt").html($(this).val());
});

###

Not able to find dom with class txt & pole but you can try this code

$('.pole').on('input', function() {
  // changed here
  var val = $(this).val();
  $('.txt').html(val);
  $('.txt').val(val);
});

Leave a Reply

Your email address will not be published. Required fields are marked *