How to read the dynamic value of a text field using a div id and use that id in another jquery?

I am using below script for dynamic text box.

<script type="text/javascript"> $(function () { $("#btnAdd").bind("click", function () { var div = $("<div />"); div.html(GetDynamicTextBox("")); $("#TextBoxContainer").append(div); }); }); function GetDynamicTextBox() { return 'Item Code : <select name="iuname" id="iuname" class="required">'+ <?php foreach($tItem as $row) : ?> '<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>'+ <?php endforeach;?> '</select>'+ ' Batch : <input id="buname" name="buname" >'+ '<td id="finalResult"></td>'+ '<br/>' } </script> 

When I change the product code, exiting it, it should show a warning. But he does not show any warnings.

 <script> $(document).ready(function(){ $("#iuname").keyup(function(){ alert('TEST'); }); }); </script> 
+4
source share
3 answers

Use Event Delegation to Create Dynamic DOM Elements

 $(document).on('change', '#iuname', function(){ var val = $(this).val(); var text = $(this).find('option:selected').text(); $("#finalResult").text(val); //if you want add text means // $("#finalResult").text(text); }); 
+1
source

Contact In case of an event

 $(document).ready(function(){ $("#iuname").on('change',function(){ alert('TEST'); }); }); 
0
source

The identifier in HTML must be unique . When the btnAdd button is btnAdd , a duplicate element is generated with the identifiers iuname , buname and finalResult . This causes HTML to become invalid. the problem can be solved with a generic class, then the class selector $('.className') can be used.

Script I added a CSS class here

 function GetDynamicTextBox() { return 'Item Code : <select name="iuname" class="iuname required">' + <?php foreach($tItem as $row) : ?> '<option value="<?php echo $row->ProductID;?>"><?php echo $row->ProductID;?></option>' + <?php endforeach;?> '</select>' + ' Batch : <input class="buname" name="buname" >' + '<td class="finalResult"></td>' + '<br/>' } 

Event binding

You are currently using direct event binding, event handlers are only bound to the currently selected elements; they must exist on the page when your code is binding to the event.

Since you are dynamically creating elements, Event Delegation must be used with .on () delegated events.

i.e.

 $(parentStaticSelector).on('event','selector',callback_function) 

Example

 $("#TextBoxContainer").on('change', ".iuname", function(){ //Your code }); 
0
source

All Articles