I have this ul control:
<ul id="AddedWifiList"></ul>
I add a li item using jquery:
$("#AddedWifiList").append('<li><a href="#">' + connectionName +
'</a> <input type="button" onClick="DeleteWifi();" class="btn btn- danger btn-sm btn-sm" value="Delete"></li>');
The markup rendered fron the last attempt is:
<input type="button" onclick="DeleteWifi(Informed);" class="btn btn- danger btn-sm btn-sm" value="Delete">
The error is:
Error: Uncaught ReferenceError: Informed is not defined Script: https://192.168.0.4/Account/Settings Line: 1
My js function:
function DeleteWifi() {
var connectionName = $('#AddedWifiList').val();
alert(connectionName);
}
The alert value is blank.
i had tried doing this:
$("#AddedWifiList").append('<li><a href="#">' + connectionName +
'</a> <input type="button" onClick="DeleteWifi(' + connectionName + ');" class="btn btn- danger btn-sm btn-sm" value="Delete"></li>');
function DeleteWifi(connectionName) {
alert(connectionName);
}
errors with a parse error.
The issue is because ul elements do not have a value attribute to read. From the context of your code it looks like you're trying to get the connectionName value, which should be set on the button instead.
Also note that as you're appending the elements dynamically after the page loads you should use a delegated event handler instead of an inline one, as the latter are outdated and are no longer good practice to use. To read the value of the connectionName related to the button you can then use a data attribute.
With that said, try this:
$('button').on('click', function() {
var connectionName = 'connection_' + new Date().getTime();
$("#AddedWifiList").append('<li><a href="#">' + connectionName + '</a><button type="button" class="btn btn-danger btn-sm btn-sm delete" data-connection-name="' + connectionName + '">Delete</button></li>');
});
$('#AddedWifiList').on('click', '.delete', function() {
console.log('Removing ' + $(this).data('connection-name'));
$(this).closest('li').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<button type="button">Add</button>
<ul id="AddedWifiList"></ul>
Here is your code:- https://jsfiddle.net/obnoxiousnerd/ec9um5qz/10/
$("#AddedWifiList").append('<li><a href="#" id="Wifi">' + 'connectionName' +
'</a> <button>Delete</button></li>');
$("button").click(function(){
var connectionName = document.getElementById("Wifi").textContent;
alert(connectionName);
});
Made some changes, but get it done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With