I have some jQuery that uses AJAX and JSON to populate a UL tag with data.
This is the jQuery code:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pName').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li>' + item.datestamp + ' - ' + item.comment + ' - ' + item.username + '</li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
The code above populates a UL field called pNames. It fills LI tags with parsed JSON data retrieved from a PHP script.
What I need to do now is clear the pNames field.
In the search window that prints the data, I have an HTML RESET button.
<input type="reset" class="btn btn-sm btn-default" id="pReset" name="pReset" value="reset" />
Please note the TYPE in the input field, which I have set to 'reset', will clear out the FORM field, but it will not clear out the UL field that populated the data.
Here is the JavaScript I attempted to use to clear out the field:
$('#pReset').on('click', function ()
{
document.getElementById('#pName').val("");
});
What can I try next?
Update
Since you didn't post your code, let's go with this simplified example:
HTML:
<h3><code>pNames</code></h3>
<ul id="pNames">
</ul>
<div>
<button id="get-pnames">Get pNames</button>
<input type="reset" id="pReset" value="Reset pNames" />
<input type="reset" id="pClear" value="Clear pNames" />
</div>
JS
var yourOriginalAjaxCallbackLogic = function (obj) {
var htmlToInsert = obj.map(function (item) {
//console.log(
return '<li>' + item.datestamp + ' - ' + item.comment + ' - ' + item.username + '</li>';
}).join('');
$('#pNames').html(htmlToInsert);
};
$('#get-pnames').on('click', function (e) {
e.preventDefault();
// your additional logic for grabbing
// the pName and what not would go here
// note the last argument to $.post - this allows us to let jQuery
// take care of converting the json response
$.post('api/pNameSearch.php', {partnername: partnername}, function (data) {
yourOriginalAjaxCallbackLogic(data);
}, 'json');
});
// This version just removes the content of the LI items.
$('#pReset').on('click', function (e) {
e.preventDefault();
$('#pNames li').html('');
});
// This version removes all the LI items
$('#pClear').on('click', function (e) {
e.preventDefault();
$('#pNames').empty();
});
You can see a working fiddle here: http://jsfiddle.net/qhrmh3o1/1/
.val
is only for form inputs. These are li
elements so you would use $('li').html('');
$('#pReset').on('click', function () {
$('#pName li').html('');
});
You may need to modify that selector because I'm not 100% positive what the selector should be for the li
items you want to clear (or if you really want to remove them or their ul
from the DOM).