how to refresh the list in jquery javascript - javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html

You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.

You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Related

how to show list items separately in output using javascript

I have created one html which contains search box. After searching, I'm getting the data in list. But when I click on that I'm getting the value of all list item by using this
var text = $(this).text(); method
In my app, if I click on one item only it should give me only that value of list item not other. I'm making a mistake somewhere, but I don't know where.
Here is my code:
HTML
<ul data-role="listview" class="ui-li-icon">
<li id="list"></li>
</ul>
And here is my JavaScript code:
function successCallback(responseObj)
{
// alert(JSON.stringify(responseObj));
form.reset();
dataj=JSON.stringify(responseObj);
len=dataj.length;
for(i=0;i<len;i++)
{
var output = "<ul>" + responseObj.merchants[i].imageFileName+ " " + "<font size=3 color=green>" + responseObj.merchants[i].merchantName + "</font>" +"</ul>";
$('#list').append(output);
}
$('#list').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
}
So when I'm searching for some a item. I'm getting list of:
ab
abc
But when I clicked on it. I get value of both ab and abc. I just want only one value where I have clicked.
//replace your click event by below code
$('.ui-li-icon li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
$('#list').append(output);
I believer list is the id you are giving to list items i.e.
Now, this will confuse the browser because id should be UNIQUE and here you are giving this id to all the list items.
If you fix this, your problem should be resolved!
Or you could simply attach click event using this
$('.ui-li-icon li').click //Your click event handler
It's very difficult to understand what you are asking. From what I can tell you're looking for something like this:
$('#list li').on('click', function(){
alert("index: "+$(this).index() + " value: "+ $(this).text());
});
Here's a fiddle http://jsfiddle.net/Jw8qz/

Jquery reading input field that was created from JSON loop

I cannot figure out for the life of me why this will not work. I am trying to pull the value of a textfield that was created with a loop from a json file.
In this code, at the very bottom I just do a simple click(function() {alert()} just to see if I can pull a value and its returning undefined. But if I remove '#name' and put in 'input' it captures it, but only for the first of several input fields.
Any help is really appreciated
JSON
{
"Controls": [{
"Button":[{ "Name":"Button", "x": "1","y": "2","width": "3","height": "4","Transition":"" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12","Rows":""}]
}]
}
The Code(there is soome getJSON stuff above this)
//Slide In Attributes Panel Based on Selected Object
$(document).on('click', '#code li', function () {
var index = $('#code li').index(this);
var selected = $(this).text();
switch (selected) {
case selected:
$('#options').hide();
hidePanels();
$('#temp').remove();
$('#objectAttributes').show("slide", 200);
break;
//If it does work show what variable is being used
default:
alert(selected);
break;
}
//Shows Selected LI Index
$('#codeIndex').text("That was div index #" + index);
//Pull list of Attributes for selected Object
$.getJSON('controls.json', function (data) {
//Build Attributes List
var attributeList = '<div id="temp">';
//Target based on selected object
var target = selected;
attributeList += '<div>' + target + '<div>';
$.each(data.Controls[0][target][0], function (kk, vv) {
attributeList += '<div style="float:right">' + kk + ':' + '<input type="text" id='+ kk + '>' + '</input>' + '</div>';
});
attributeList += '</div></div>';
attributeList += '</div>';
$('#objectAttributes').append(attributeList);
$('#temp').append('<div id="editIndex">'+"Modifying index" + " " +index+'</div>');
$(document).on('click', '#saveAttributes', function () {
var $x = $('#name').val();
alert($x);
})
});
});
Ok, so after a little hacking around with a jsfiddle the answer turned out to be a lot simpler than I first thought. Ever since HTML 4.01 class names and IDs have been case sensitive (reference), which means that your selector $('#name') wasn't matching the JSON Name.
So a simple change, such as in this simplified jsfiddle seems to work as desired. Hopefully this helps!

How to redirect to another page with jQuery Autocomplete item click

I'm stumped with this one, I've been at it hours, trying to get jQuery autocomplete to go to another page on the site when an item is clicked in the suggestions list.
Anyone know how to do this? Here is my code :
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, item) {
//window.location.replace("http://www.example.com/Profile/Details/1");// Works but totally unacceptable, browser history lost etc..
//alert("Item Clicked"); //Fires Ok
}
}).data("autocomplete")._renderItem = function (ul, item) {
var MyHtml = '<a id="ItemUrl" href="/Profile/Details/' + item.PartyId + '"' + ">" +
"<div class='ac' >" +
"<div class='ac_img_wrap' >" +
'<img src="../../uploads/' + item.imageUrl + '.jpg"' + 'width="40" height="40" />' +
"</div>" +
"<div class='ac_mid' >" +
"<div class='ac_name' >" + item.value + "</div>" +
"<div class='ac_info' >" + item.info + " PartyId :" + item.PartyId + "</div>" +
"</div>" +
"</div>" +
"</a>";
return $("<li></li>").data("item.autocomplete", item).append(MyHtml).appendTo(ul);
};
As you can see I have used custom HTML in the _renderItem event, my custom HTML creates an anchor tag with the id passed in from the source, this looks ok, the link is formed correctly in the browser bottom left corner (I'm using Chrome)
<a href='/Profile/Details/id' >some other divs & stuff</a>
The problem is that when I click the link nothing happens, I have tried using the select event but item is null so can't get item.PartyId to force a manual jump.
How can I get the click event working?
It might late to answer it, but I have done this with the following code:
$(document).ready(function() {
$('#txtSearch').autocomplete({
minLength: 3,
source: "handlers/SearchAutoComplete.ashx?loc=" + $('#hfLocation').val(),
select: function(event, ui) {
doSearch(ui.item.label, ui.item.city);
}
});
});
function doSearch(term, location) {
window.location.href = 'Search.aspx?q=' + term + '&loc=' + location;
}
After a few days of head banging (not moshing kind) I've come up with the following:
$(':input[data-autocomplete]').autocomplete({
source: $(':input[data-autocomplete]').attr("data-autocomplete"),
delay: 0,
select: function (event, ui) {
var q = ui.item.PartyId;
if (q != "") {
$('#hidPID').val(q);
$('#ac_submit').trigger('click');
}
}).data("autocomplete")._renderItem // -->>> the rest of the code same as above
The issue was (event, item) should have been (event, ui) and to get the value of the item you use ui.item.PartyId (in my case PartyId is declared in the source : above)
So on my original form I had two html inputs 1-hidden ID, 2-Submit & as you can see in the select : function above I set the ID & trigger the submit (so now the user just picks an item and off they go to the controller which performs the RedirectToView & NOT this code as it doesn't seem correct to use location in this instance)
I Hope this saves someone some time as the jQuery autocomplete docs dont make it too clear.

JQuery list, prevent a link to be clicked more than once

I've been trying to figure this one out for a while now. I have a JQuery list populated using a JSon array.
Every item in the list is clickable and brings to a page called details with specific details for the item clicked.
Everything works fine, but if the user clicks several times on an item link, the page will be correctly loaded but it's gonna take several clicks on the back button to get back to the original page. Let's say the user clicks 3 times an item, when he wants to go back, he will have to hit back 3 times.
So I'm looking for a way to disable the link after it's been clicked once.
How could I accomplish that ?
Large code sample below, please tell me if my question is unclear. Thanks !
var items = [];
$.each(catalog.products,
function(index, value) {
if (
((!filterValue ) || value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
&& ((!brand) || value.brand.toUpperCase().indexOf(brand.toUpperCase()) != -1)
&& ((!category) || value.category.toUpperCase().indexOf(category.toUpperCase()) != -1)
&& ((!sport) || value.sport.toUpperCase().indexOf(sport.toUpperCase()) != -1)
) {
var priceInfo;
if(value.salePrice === '') {
priceInfo = '<h4 style="margin-top:3px;margin-bottom:0px;color:#75a8db "> $' + value.price + '</h4></a></li>';
} else {
priceInfo = '<h4 style="margin-top:3px;margin-bottom:0px; "><span style="text-decoration: line-through;font-size:small;">$' + value.price +
'</span><span style="color:#75a8db;"> $' + value.salePrice + '</span></h4></a></li>';
}
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p style="margin-bottom:0px;margin-top:0px;">' + value.brand + '</p>' +
'<h3 style="margin-top:0px;margin-bottom:0px;">' + value.name + '</h3>' +
priceInfo);
}}
);
if (items.length === 0) {
items.push('<p style="text-align: left;margin-left: 10px">No results found.</p>');
}
productListView.html(items.join(''));
productListView.listview('refresh');
}
If you build your link as an object instead of just text, you can then bind to the click handler as you build it like this:
// here's the click handler you need
itemLink.click(function(e) {
console.log("item clicked");
if ($(this).data("clickCount") > 0) {
console.log("click count reached");
return false;
}
console.log("following the link");
// set a click counter
$(this).data("clickCount", 1);
// store the original href in case you need it
$(this).data("ogHref", $(this).attr("href"));
$(this).attr("href", "javascript://");
});
JSFiddle
In the fiddle I have used your code as much as I can, but instead created the markup using jQuery objects.
You can use jQuery's one() to implement this once-only action, for example:
$('a').one('click',
function(){
alert('hi!');
return false;
});
JS Fiddle demo.
Or, without using one(), you could simply unbind the click() event from the element:
$('a').click(
function(){
alert('hi!');
$(this).unbind('click');
return false;
});
JS Fiddle demo.
References:
one().
unbind().
var currentValue="";
$('a').click(function(event) {
event.preventDefault();
if(currentValue != $(this).attr("href")){
currentValue = $(this).attr("href");
// Your actions here
}
});
Thus, the link just dies when its action is the latest, but can be reused. jsFiddle test.

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources