Add switches dynamically using JQUERY and then connect the jQuery change event to the generated switches

I am adding a set of radio buttons to my page using jQuery below

$(document).ready(function() { $("#Search").click(function() { var keyword = $('#keyWord').val(); var EntityType = $("#lstEntityTypes :selected").text(); var postData = { type: EntityType, keyWord: keyword }; // alert(postData.VehicleType); $.post('/EntityLink/GetJsonEntitySearchResults', postData, function(GRdata) { var grid = '<table><tr><td>ID</td><td>Name</td><td></td>'; for (var i = 0; i < GRdata.length; i++) { grid += '<tr><td>'; grid += GRdata[i].ID; grid += '</td><td>'; grid += GRdata[i].EntityName; grid += '</td><td>'; grid += '<input type="radio" name="EntitiesRadio" value="' + GRdata[i].ID + '" />'; grid += '</td></tr>'; } grid += '</table>'; alert(grid); $("#EntitySearchResults").html(grid); $("EntitiesRadio").change(function() { alert($("EntitiesRadio :checked").val()); $("EntityID").val($("EntitiesRadio :checked").val()); alert($("EntityID").val()); $("EntityName").val($("#lstEntityTypes :selected").text()); }); }); }); // }); 

therefore, when loading the page, the EntitiesRadio name range is missing, so I tried to register the Radio entity change function within the same search method, but it is not registered. how do I get a change event to trigger an update of my hidden inputs

+4
source share
3 answers

You can use the live event, which will automatically work for any newly created elements on the page.
http://api.jquery.com/live/

Therefore, you just need to add the following code once, and it applies to all newly created elements:

 $(".EntitiesRadio").live('change', function() { alert($(".EntitiesRadio :checked").val()); $("#EntityID").val($(".EntitiesRadio :checked").val()); alert($("#EntityID").val()); $("#EntityName").val($("#lstEntityTypes :selected").text()); }); 

also make sure you add ".". before calling by class name and "#" before calling by identifier, because you missed the seams in your code.

+9
source

$("EntitiesRadio") will not find anything because there is no such tag. Use $ ("# EntitiesRadio") if you want to select by ID or $ (". EntitiesRadio") to select by class.

After adding HTML to the page, you can associate the change event with it. To automatically associate a change event with new matching elements, you can use the live API.

 $(".EntitiesRadio").live('change', function() {} ); 
+1
source

Just an observation, but $ ("EntitiesRadio"). maybe better than $ (". EntitiesRadio")? If they are classes, they must be $ (". EntitiesRadio"), and instead of name = "EntitiesRadio" use class = "EntitiesRadio"

If you want to use name = "EntitiesRadio", you will have to use

$("input[name*='EntitiesRadio']")

0
source

Source: https://habr.com/ru/post/1304148/