1

Receiving value from static field when keyup based on input field class(.inputclass) method, but once add field dynamically its not get the value.

Below the sample code, Please help.

$(function(){
	$(document).ready(function(){
		$(".inputclass").keyup(function() {
					alert($(this).val());
		});
	});
});
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
  <tr>
    <td>Field 1</td>
    <td><input type="text" class="inputclass" /></td>
  </tr>
  <script>
	var counter =1;
	$(function(){
		$('#addNew').click(function(){
			counter += 1;
			$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
		});
	});
</script>
</table><br/>
<input type="button" id="addNew" value=" &plusmn; Add New Field"/>
</form>

2
  • $(function(){ is a shorthand for $(document).ready(function(){. Use only once. Commented Jun 7, 2017 at 11:51
  • $(function(){}) is not shorthand for $(document).ready. its Immediately-invoked function expression (IIFE). Commented Jun 7, 2017 at 11:58

2 Answers 2

7

This is because when you assigned the event handler, it only assigned to the existing elements at the time.

Delegate to the document:

$(document).on('keyup', '.inputclass', function(){
   alert($(this).val())
});

When you delegate to a parent or the document, you are using the event that bubbles up and so it doesn't matter if there are dynamic elements.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your Swift response MrCode, I checked and Its working perfectly. thanks once again. _/_
0

$(function(){
	$(document).ready(function(){
    $(document).on('keyup', '.inputclass', function(){
					alert($(this).val());
		});
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<table width="250" border="0" cellspacing="0" cellpadding="0" id="dataTable">
  <tr>
    <td>Field 1</td>
    <td><input type="text" class="inputclass" /></td>
  </tr>
  <script>
	var counter =1;
	$(function(){
		$('#addNew').click(function(){
			counter += 1;
			$('#dataTable').append('<tr><td>Field ' + counter + '</td><td><input type="text" class="inputclass"/></td></tr>');
		});
	});
</script>
</table><br/>
<input type="button" id="addNew" value=" &plusmn; Add New Field"/>
</form>

1 Comment

Thanks SilverSurfer for your response, its working. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.