JavaScript reset populated field in PHP/AJAX - javascript

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.
I might be looking at this the wrong way, if so, please let me know.
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("");
});
I think it's pretty obvious that I'm missing something.

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).

So, I placed the UL tag inside of a DIV, called masterdiv.
I updated my javascript as follows:
$('#pReset').on('click', function ()
{
$('#masterdiv ul').text("");
});
This worked on clearing out the UL field called pNames.

Related

Adding input forms and removing them again get all id's

I'm currently adding some input fields to a div. There is also the option to remove the just added input fields.
Now the problem is, if you add 4 input fields and let's say you removed number 2.
You will get something like this
id=1
id=3
id=4
Now when you will add a new one it will add id=5.
So we end up with:
id=1
id=3
id=4
id=5
JS :
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
console.log(historyVar);
});
HTML :
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
For now it's okay.
Now for the next part I'm trying to get the data from the input fields:
historyVar['artiestNaam_0'] = $('#artiestNaam_0').val();
historyVar['artiestURL_0'] = $('#artiestURL_0').val();
How can I make sure to get the data of all the input fields?
Working version
You could do with a whole lot less code. For example purposes I'm going to keep it more simple than your question, but the priciple remains the same:
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
<input name="artiest_naam[]" />
The bracket at the end make it an array. We do not use any numbers in the name.
When you submit, it will get their index because it´s an array, which returns something like:
$_POST['artiestnaam'] = array(
[0] => "whatever you typed in the first",
[1] => "whatever you typed in the second",
[2] => "whatever you typed in the third"
)
If I would add and delete a hundred inputs, kept 3 random inputs and submit that, it will still be that result. The code will do the counting for you.
Nice bonus: If you add some javascript which enables to change the order of the inputs, it will be in the order the user placed them (e.g. if I had changed nuymber 2 and 3, my result would be "one, third, second").
Working fiddle
You could use each() function to go through all the divs with class js-artist:
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
Hope this helps.
var iArtist = 1,
tArtist = 1;
$(document).on('click', '#js-addArtist', function() {
var artist = $('#js-artist');
var liData = '<div class="js-artist"><input id="artiestNaam_' + iArtist + '"><input id="artiestURL_' + iArtist + '"><span class="js-removeArtist">remove</span></div>';
$(liData).appendTo(artist);
iArtist++;
tArtist++;
});
$(document).on('click', '.js-removeArtist', function() {
if (tArtist > 1) {
$(this).parents('.js-artist').slideUp("normal", function() {
$(this).remove();
tArtist--;
});
}
});
$(document).on('click', '#js-print', function() {
var historyVar = [];
$('.js-artist').each(function(){
var artiestNaam = $('input:eq(0)',this);
var artiestURL = $('input:eq(1)',this);
historyVar[artiestNaam.attr('id')] = artiestNaam.val();
historyVar[artiestURL.attr('id')] = artiestURL.val();
});
console.log(historyVar);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="js-addArtist">add</span>
<div id="js-artist">
<div class="js-artist">
<input id="artiestNaam_0">
<input id="artiestURL_0">
<span class="js-removeArtist">remove</span>
</div>
</div>
<span id="js-print">print</span>
Initialize a count variable. This way if an input field is removed, a new id still gets initialized. To get the data for each of them, jQuery has a convenient each function to iterate over all elements.
Hope this helps
count = 0;
$("#add").on("click", function() {
count++;
$("body").append("<input id='" + count + "'</input>");
});
$("#remove").on("click", function() {
var index = prompt("Enter the index of the input you want to remove");
$("input:eq(" + index + ")").remove();
});
$("#log-data").on("click", function() {
$("input").each(function() {
console.log($(this).val());
});
});
#btn-group {
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="btn-group">
<button id="add">Add Input Fields</button>
<button id="remove">Remove Input Fields</button>
<button id="log-data">Log Data</button>
</div>

Auto complete search is not working properly, do not iterate all elements in $.each ul li shows on time in response

I have implemented auto complete search in my site. The problem is that response is coming properly but it do not iterate all elements in <ul><li> elements.
Always shows one element in HTML but coming multiple from response.
On the top search see if you type only river it comes with river records but do not show all in one ul li means li iteration is not working.
Here is my Jquery code:
<script>
$(document).ready(function(){
$('#keyword').keyup(function() {
var total;
$.ajax({
type: "POST",
url: "http://realtyexecutivesny.com/getRecSet.php?rnd=" + Math.random(),
data:{ key: $(this).val() },
success: function(data){
$.each(data.locations, function( key, value ) {
total = '<li>'+data.locations[0].value+'</li>';
});
$('#lists').html('<ul>'+total+'</ul>');
}
});
});
$('#lists ul li').click(function(){
$('#keyword').val($(this).html());
$('#field').val($(this).parent().data('field'));
});
});
</script>
Here is HTML Code:
<input type="text" name="keyword" id="keyword" />
<input type="hidden" name="field" id="field" value="all" />
<div id="lists"></div>
first Initialize total like
var total = '';
And in your each, Use index to get all records.
$.each(data.locations, function( index ) {
total += '<li>' + data.locations[index].value + '</li>';
});
$('#lists').html('<ul>' + total + '</ul>');
Try using .append() it's a more clean approach.
success: function (data) {
$('#lists').html('<ul></ul>') // initiate clear element
$.each(data.locations, function (key, value) {
$('#lists ul').append('<li>' + data.locations[key].value + '</li>'); // append new elements to the ul element
});
}
Also check this: jquery .html() vs .append()
replace this:
total = '<li>'+data.locations[0].value+'</li>';
with this:
total += '<li>'+data.locations[0].value+'</li>';
and befor the each loop define total like below:
var total = '';
$.each(data.locations, function( key, value ) {
total += '<li>'+data.locations[0].value+'</li>';
});

Search through list items on every input key press using jQuery and hide other item

I have code of list item , I want to search items using textbox how i can perform:-
Pricerange.Append("<ul>");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Pricerange.Append(
"<li><span class='pull-left'><a href='default.aspx?Price=" +
ds.Tables[0].Rows[i]["Max_id"] + "' >" + ds.Tables[0].Rows[i]["Max_Price"] +
"</a></span> <span class='counter-pro pull-right'>12</span></li>");
}
Pricerange.Append("</ul>");
divpricerange.InnerHtml = Pricerange.ToString();
See This Image
- on left hand side in refine search i want to perform autocomplete action and hide other listitem.
You could use jQuery :contains selector to search the list and then show/hide list items based on the search result.
Here is a quick snippet that would give you an idea:
Demo Fiddle: http://jsfiddle.net/mwdune35/1/
/* jQuery code to search and reveal */
$("#txt").on("keyup", function() {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Your HTML -->
<input id="txt" type="text" />
<br />
<ul id="lst">
<li>JM Aroma</li>
<li>Red Square Bonanza</li>
<li>Skylabs Special</li>
<li>Society Someplace</li>
<li>Anywhere</li>
<li>Everywhere</li>
<li>Nowhere</li>
<li>Somewhere</li>
</ul>
Kindly check this post
It uses Tables instead of list, but you can play with it.
$.each($("#table tbody").find("tr"), function() {
if($(this).text().toLowerCase().indexOf($(_this).val().toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
})
In this way this script will executed thanks # abhitalks for valuable suggestion..
$(document).ready(function () {
$("#txt").on("keyup", function () {
var srchTerm = $(this).val(),
$rows = $("#lst").children("li");
if (srchTerm.length > 0) {
$rows.stop().hide();
$("#lst").find("li:contains('" + srchTerm + "')").stop().show();
} else {
$rows.stop().show();
}
});
});

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

Same function for different sections - relative referencing in jquery

By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.

Categories