Syafiq Azwan
Syafiq Azwan

Reputation: 178

get element id on form change

I'm having a form looks like this:

<form method="POST">
    <input type="text" name="htdate" id="htdate">
    <br/>
    <input type="text" name="pgdate" name="pgdate">
    <br/>
    <input type="submit" name="submit" value="submit">
</form>

I would like get the textbox id when on form change. My js code looks like this:

$('form :input').change(function()
{
    var eleID = $(this).id;
    console.log("changeID: ", eleID);
});

Console output :

changeID:  undefined

Is there any ways to get the id of the element during value change.?

Upvotes: 2

Views: 126

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115272

id is the property of dom object and jQuery object doesn't have any id property, so it will always return undefined


Use this.id or $(this).attr('id') to get id of the element

$('form :input').change(function() {
  var eleID = this.id;
  // var eleID = $(this).attr('id');
  console.log("changeID: ", eleID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="POST">
  <input type="text" name="htdate" id="htdate">
  <br/>
  <input type="text" name="pgdate" name="pgdate">
  <br/>
  <input type="submit" name="submit" value="submit">
</form>

If you want to listen inputting value then use keypress , keyup or input event

$('form :input').on('input', function() {
  var eleID = this.id;
  // var eleID = $(this).attr('id');
  console.log("changeID: ", eleID);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="POST">
  <input type="text" name="htdate" id="htdate">
  <br/>
  <input type="text" name="pgdate" name="pgdate">
  <br/>
  <input type="submit" name="submit" value="submit">
</form>

Upvotes: 4

Jai
Jai

Reputation: 74738

Is there any ways to get the id of the element during value change.?

For this you can use input event which is introduced in the html5. so this can be done:

$('form :input').on('input', function()
{
    var eleID = this.id; // <----this.id; || $(this).attr('id');
    console.log("changeID: ", eleID);
});

change event only gets invoked when you loose focus from the input so if you are looking for immediate effect while typing/cut-copy-paste then input would be beneficial for you.

Upvotes: 0

Azad
Azad

Reputation: 5272

use $().attr();

$('form :input').change(function()
{
    var eleID = $(this).attr("id");
    console.log("changeID: ", eleID);
});

Upvotes: 1

Related Questions