I have a json file with below data.
{"student1":[{"id":1,"name":"Test Data1","email":"test1#g.com"}]}
{"student2":[{"id":2,"name":"Test Data2","email":"test2#g.com"}]}
{"student3":[{"id":3,"name":"Test Data3","email":"test3#g.com"}]}
{"student4":[{"id":4,"name":"Test Data4","email":"test4#g.com"}]}
And I use $.getJSON method to retrieve but data won't output. And I want to search data with Key like student3, then the data of student3 will have to output.
Here is my JQuery code.
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Here is my Full Source Code.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Test Json</title>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="button" name="submit" id="submit" value="Submit" onclick="submitForm()">
<input type="button" name="edit" id="edit" value="Edit" onclick="Edit()">
<br><br>
<div></div>
</body>
<script type="text/javascript">
function submitForm(){
var name = $("#name").val();
var email = $("#email").val();
var obj = {
table: []
};
obj.table.push({id: 1, name:name, email:email});
var json = JSON.stringify(obj);
$.ajax
({
type: "GET",
dataType : 'json',
url: 'save_json.php',
data: { data: json },
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});
$("#name").val('');
$("#email").val('');
}
function Edit(){
$.getJSON( "general.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
</script>
</html>
You can try this code/syntax may not be correct....
searchParam would be 'Student3'..
$.getJSON( "test.json", function( data , searchParam ) {
var items = [];
var filterObj =data[searchParam];
if(filterObj != undefined)
{
var parsedData = Json.Parse(filterObj);
$.each( parsedData , function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
Please add below mentioned code.
$(document).ready(function(){
$.getJSON( "test.json", function(data) {
var items = [];
$.each( data, function( key, val ) {
$.each( val, function( key2, val2 ) {
items.push( "<li id='" + key2 + "'>" +val2[0].name + "</li>" );
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
});
also remove student1,student2 and use only student and find value
using key.
Your json data will be something like below.
[{"student":[{"id":1,"name":"Shyam","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Niraj","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Mehul","email":"test#g.com"}]},
{"student":[{"id":1,"name":"Ritesh","email":"test#g.com"}]}]
Let me know if it not works.
Related
I am facing an issue that has baffled and actually exhausted me for hours.
I have tried so many different things, have done and still doing various debugging techniques but I am very tired and would seek for some help of any kind.
I will post the very basics for start, in case someone has any helpful idea/suggestion to unstack me, and I might be adding further information or more code as we go if needed.
I am working on a Joomla site and on a custom component view I place an inline jQuery script at some point of my html output.
The problem is that while everything works well on my localhost, when I upload it online the javascript breaks in whatever point I try to create variables that contain html. Then the browser will auto-close the script tag with </script> and the rest of the js code will be output as html.
So for example, the following script:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader"><div>';
});
})(jQuery);
</script>
will end up to something like below:
<script>
(function($)
{
$(document).ready(function()
{
var loader = '<div id="loader">';
</div></script>
});
})(jQuery);
</script>
*Another clue that I just got is that the issue seems to be when I upload this on Litespeed server.
I tested this on 2 different servers with Litespeed and then on 1 Apache.
The one on the Apache server works fine (like on my localhost).
This is my complete inline script, just in case anyone is in place to catch anything that I am missing.
(function($)
{
$(document).ready(function()
{
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var obj = <?php echo json_encode($availableTags); ?>;
var searchForm = $('#adminForm');
var predefinedTags = $('.tags-cloud.popular-tags .li-item');
var searchTermId = '';
var oldSearchTermId = '';
var categories = <?php echo json_encode( $search_categories ); ?>;
var categoriesAction = '<?php echo (int)$sel_categories_option; ?>';
var list_limit = '<?php echo (int)$list_limit; ?>';
var list_limitstart = 0;
var list_order_by = '<?php echo $list_order_by; ?>';
var list_order_dir = '<?php echo $list_order_dir; ?>';
var menuItem = '<?php echo (int)$menuItem; ?>';
var show_image = '<?php echo (int)$show_image; ?>';
var show_date = '<?php echo (int)$show_date; ?>';
var which_date = '<?php echo $which_date; ?>';
var show_category = '<?php echo (int)$show_category; ?>';
var searchResults;
var loadMore = false;
var loader = "";
// Form submit
$(searchForm).on('submit', function(e) {
searchTermId = $('#sm-search-term-id').val();
e.preventDefault();
ajaxSearchArticles();
});
$('.search-order-selects').on('change', function(e) {
searchTermId = $('#sm-search-term-id').val();
list_order_by = $('#search-order').val();
list_order_dir = $('#search-order-dir').val();
list_limitstart = 0;
ajaxSearchArticles();
});
$(predefinedTags).on('click', function(e) {
searchTermId = $(this).attr('data-tagid');
$( "#sm-search" ).val( $(this).text() );
$( "#sm-search-term-id" ).val( searchTermId );
$( "#sm-search-description" ).html( '(' + $(this).attr('total_articles') + ' Total Articles)');
ajaxSearchArticles();
return false;
});
$('#search-results').on('click','#load-more-div', function() {
searchTermId = $('#sm-search-term-id').val();
list_limitstart = parseInt(list_limitstart) + parseInt(list_limit);
loadMore = true;
ajaxSearchArticles();
});
function appendResults() {
var html = '';
oldSearchTermId = searchTermId;
var l = parseInt(list_limit);
$(searchResults).each(function(i, e) {
var itemi = list_limitstart + i;
if (i < l) {
html += '<div id="artid-'+e.id+'" class="sm-search-result g-block s-item-'+itemi+'">';
html += '<div class="sm-search-result-content">';
if (show_image == '1') {
html += '<a href="'+ e.url +'" title="'+e.title+'" target="_blank">';
html += '<div class="smrc-image-holder"><img src="' + e.images + '" alt="'+e.title+'" /></div></a>';
}
html += '<div class="smrc-text-block"><h3>'+e.title+'</h3><p>'+e.introtext+'</p>';
if (show_date || show_category) {
html += '<div class="item-meta">';
if (show_date) {
var date = e.modified;
if (which_date === 'created') {
var date = e.created;
}
html += '<span class="item-date"><i class="fa fa-calendar-o" aria-hidden="true"></i> '+ date +'</span>';
}
if (show_category) {
html += '<span class="item-cat">in '+e.category +'</span>';
}
html += '</div>';
}
html += '</div></div></div>';
}
if (i === l) {
html += '<div id="load-more-div" class="sm-search-result load-more g-block">';
html += '<div class="sm-search-result-content" style="display: flex;align-items: flex-end;justify-content: center;height: 100%;">';
html += '<div class="load-more-results flex-item"><span>Load More...</span></div>';
html += '</div></div>';
}
});
html += '<div class="clear clearfix"></div>';
if (loadMore) {
$('#search-results').append(html);
} else {
$('#search-results').html(html);
}
loadMore = false;
}
// Autocomplete
$( function() {
var results = true;
$( "#sm-search" ).autocomplete({
minLength: 3,
source: obj,
focus: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
}
event.preventDefault();
return false;
},
select: function( event, ui ) {
if (results) {
$( "#sm-search" ).val( ui.item.label );
$( "#sm-search-term-id" ).val( ui.item.value );
$( "#sm-search-description" ).html( '(' + ui.item.total_articles + ' Total Articles)');
}
event.preventDefault();
$(searchForm).submit();
return false;
},
response: function(event, ui) {
if (ui.content.length === 0) {
results = false;
var res = { label: "no results", value: 0 };
ui.content.push(res);
} else {
results = true;
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
if (results) {
return $( "<li>" )
.append( "<div><strong>" + capitalizeFirstLetter(item.label) + "</strong> <small>(" + item.total_articles + " articles)</small></div>" )
.appendTo( ul );
} else {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
}
};
});
// Ajax call
function ajaxSearchArticles() {
if (!searchTermId) {
$('#empty-message').text('No Tags Defined!');
setTimeout(function() {
$('#empty-message').text('');
}, 3000);
return false;
}
$('body').append(loader);
if (searchTermId !== oldSearchTermId) {
list_limitstart = 0;
}
var xhrRequest = {
'option' : 'com_rabattdatabase',
'task' : 'RabattAjax.ajaxReceiver',
'action' : 'customSearch',
'tagid' : searchTermId,
'orderby' : list_order_by,
'orderdir': list_order_dir,
'limit' : list_limit,
'limitstart' : list_limitstart,
'cats' : categories,
'itemid' : menuItem,
'catswhat': categoriesAction,
'<?php echo JSession::getFormToken();?>' : 1,
};
$.ajax({
context : this,
type : 'POST',
data : xhrRequest,
success : function(response) {
var response = $.parseJSON(response);
searchResults = response.data;
if (response.success == true) {
appendResults();
} else {
$('#search-results').html("<h4>We couldn't process your request!</h4>");
}
}
}); // End Ajax
}
})
})(jQuery);
I have a form:
// 10 times
<input type="text" name="cityname" class="autocompletecity">
<input type="text" name="cityID" class="autocompletecityID">
When I enter the city name, it autocompletes the city name and the cityID from database with this code:
<?php for ($i = 0; $i < 10; $i++) { /*in the field class add $i */ ?>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 1 );
}
$( ".autocompletecity<?php echo $i ?>" ).autocomplete({
source: "/*path to json*/",
select: function( event, ui ) {
var item = ui.item;
if(item) {
$(".autocompletecityID<?php echo $i ?>").val(item.cityID);
$(this).val(item.value +' ' + item.country);
return false;
}
}
//code from J.D.
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index, element) {
var $element = $(element);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" +item.value + " " +item.country + "</a>" )
.appendTo( ul );
};
});
<?php } ?>
After it autocompletes the cityID, I would like to show an alert box if same cityID has alredy been entered: Click OK to confirm or Cancel to clear the cityname and cityID with repeated entry.
I tried to search in the jqueryui, but no luck...
Thanks!!
Try this:
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index) {
var $element = $(this);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
I have this two ajax jquery function to add ,display and delete data from table the table ,delete works fine ut while adding the data gets saved but only gets displayed when i refresh ,how do i fix this?
<script type="text/javascript">
$(document).ready(function() {
(function ($) {z
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
console.log(JSON.stringify(data));
$.ajax({
type: "POST",
contentType: "application/json",
url: "createajaxuser",
data:JSON.stringify(data),
dataType: "json",
success: function(result) {
a
}
});
});
$.ajax({
url: 'listusersjson',
type: 'GET',
success: function(response) {
var trHTML = '';
var count =0;
$.each(response, function(i, item) {
console.debug("i is"+i);
var success="success";
var danger="danger";
var info="info";
var color ;
if(count==0)
{
color =success;
count++;
}else if(count==1){
color =danger;
count++;
}else{
color =info;
count=0;
}
trHTML += '<tr class="'+color+'" ><td>' + item.name + '</td><td>' + item.id + '</td><td>' + item.password + '</td><td>' + item.email+
'</td><td>' + '<button type="button" class="btn btn-danger" id="' + item.id + '" >Delete</button>'
'</td></tr>';
});
$('#delTable').append(trHTML);
$('button').click(function() {
var val = $(this).attr("id");
console.debug("saurabh userid", val);
var rowElement = $(this).parent().parent();
$.ajax({
type: "DELETE",
url: "ajaxuserr/"+val,
success: function(result) {
rowElement.find('td').fadeOut('3000',
function() {
rowElement.remove();
}
);
}
});
});
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<div>
<label for="name">Name</label> <input type="text" name="name"
id="name" />
</div>
<div>
<label for="email">Email</label> <input type="text" name="email"
id="email" />
</div>
<div>
<label for="password">Password</label> <input type="password"
name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" />
</p>
</form>
<div class="container">
<table class="table table-bordered table-hover" id="delTable">
<thead>
<tr>
<th width="100">Name</th>
<th width="100">ID</th>
<th width="100">Password</th>
<th width="100">Email</th>
<th width="100">Delete</th>
</tr>
</thead>
</tbody>
</table>
</div>
I am posting this answer because you are getting confused when I am tring to explain in comments,
So initially put your ajax call that builds the table tbody into a new Function like below.
function GetListOfUsers(){
$.ajax({
url: 'listusersjson',
type: 'GET',
success: function(response) {
var trHTML = '';
var count =0;
$.each(response, function(i, item) {
console.debug("i is"+i);
var success="success";
var danger="danger";
var info="info";
var color ;
if(count==0)
{
color =success;
count++;
}else if(count==1){
color =danger;
count++;
}else{
color =info;
count=0;
}
trHTML += '<tr class="'+color+'" ><td>' + item.name + '</td><td>' + item.id + '</td><td>' + item.password + '</td><td>' + item.email+
'</td><td>' + '<button type="button" class="btn btn-danger" id="' + item.id + '" >Delete</button>'
'</td></tr>';
});
$('#delTable tbody').append(trHTML); //Note I am trying to append into tbody you were directly appending to table without tbody
$('button').click(function() {
var val = $(this).attr("id");
console.debug("saurabh userid", val);
var rowElement = $(this).parent().parent();
$.ajax({
type: "DELETE",
url: "ajaxuserr/"+val,
success: function(result) {
rowElement.find('td').fadeOut('3000',
function() {
rowElement.remove();
}
);
}
});
});
}
});
});
}
And then you can call this method in the success method of the form submit ajax call. like below
$('form').submit(function (e) {
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
console.log(JSON.stringify(data));
$.ajax({
type: "POST",
contentType: "application/json",
url: "createajaxuser",
data:JSON.stringify(data),
dataType: "json",
success: function(result) {
$('#delTable tbody').html(''); //empty the tbody
GetListOfUsers(); // call this function so that it rebuilds the tbody
}
});
});
Also since now we moved the ajax call that builds the tbody into a new function, you have to call this once in your initial script load. So that it builds up the tbody. So you can place this line of code after your form submit event handler
GetListOfUsers();
I've got list of products for my autocomplete and different pictures for them. How can I put the radiobuttons with pictures under each product? This is my code for autocomplete so far
function create_rbuttons(item){
var str = $();
if(item.PicId !=null){
for(i=0;i<item.PicId.length;i++){
debugger;
str = str + $('<input type="radio" name="rbtnCount" />');
}
}
return str;
}
$('.SliderBox').on("focus",function () {
$(this).autocomplete({
delay: 500,
minLength: #(Model.SearchTermMinimumLength.ToString()),
source: '#(Url.RouteUrl("ProductSearch"))',
select: function( event, ui ) {
$(this).val(ui.item.label);
var box_id = $(this).closest('.search-box').attr('value');
$('.Picture'+box_id+' img').attr('src',ui.item.productpictureurl).width(100).height(100);
$('#Picture'+box_id+'Id').attr('value',ui.item.PicId[0])
$('.Text'+box_id+' input').attr('value',ui.item.label)
$('.Link'+box_id+' input').attr('value',ui.item.producturl);
return false;
}
})
.data("ui-autocomplete")._renderItem = function( ul, item ) {
var t = item.label;
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>#(true ? Html.Raw("<img src='\" + item.UrlsArr[0] + \"'>") : null)" + t + "</a>")
.append("<a>" + t + "</a>")
.append(create_rbuttons(item))
.appendTo(ul);
};
PicId is an array, where I keep id of pictures. UrlsArr — where I keep paths to them
I tried something. The radio button doesn't really do anything, it just sits there.
But you can see the icon.
See if it helps
index.php
<style>
img.icon {
height: 20px;
}
.highlight {
color: red;
}
</style>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
var searchbox = $("#search");
searchbox.autocomplete({
source: "autocomplete.php",
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var li_item = highlight(searchbox.val(), item.value); // highlight
if(li_item.length) {
return $('<li></li>')
.data('item.autocomplete', item)
.append(' <input type="radio" name="rbtnCount"> <img class="icon" src="' + item.icon + '"> ' + li_item )
.appendTo(ul);
}
else {
return $('<li></li>');
}
};
// based on #see http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript
function highlight(needle, haystack) {
var result = haystack;
var index = haystack.toLowerCase().indexOf(needle.toLowerCase());
if ( index >= 0 ) {
result = haystack.substring(0, index) + "<span class='highlight'>" + haystack.substring(index, index+needle.length) + "</span>" + haystack.substring(index + needle.length);
}
else {
// no match
return '';
}
return result;
}
});
</script>
<input id="search">
autocomplete.php
[
{"value": "ActionScript", "icon": "http://blog.istorm.ca/wp-content/uploads/2011/05/64px-ActionScript_icon.png"},
{"value": "Boostrap", "icon": "http://qph.is.quoracdn.net/main-thumb-t-407834-50-bcwisowdvdkeethoagubojbfeljzwjwy.jpeg"},
{"value": "C++", "icon": "http://imag.malavida.com/mvimgbig/download-s/turbo-c-4955-0.jpg"},
{"value": "Jquery", "icon": "https://pbs.twimg.com/profile_images/59268975/jquery_avatar_normal.png"},
{"value": "Java", "icon": "https://pbs.twimg.com/profile_images/426420605945004032/K85ZWV2F_normal.png"},
{"value": "JavaScript", "icon": "http://www.kalmstrom.com/images/logos/Icons/JavaScript128.png"}
]
Try this
function create_rbuttons(item){
if(item.PicId !=null){
for(i=0;i<item.PicId.length;i++){
var radioBtn = $('<input type="radio" name="rbtnCount" />');
radioBtn.appendTo(ul);
}
}
}
update
I need to be able to reference the XML from my actual XML document, i dont want it just var'd into jQuery...
How do i get the following behaviour to occur...
Searching the label input searches for both label and value, however, only omits results from each to their respective input field so typing Alabama shows Alabama - AL but only gives me Alabama in state and AL in value
also using
$.ajax({
type: "GET",
url: "states.xml", // change to full path of file on server
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function(data) {
alert("XML File could not be found");
}
});
instead of the var myXML
var myXml = '<?xml version="1.0" encoding="UTF-8"?><states><state label=Alabama value=AL country="US"><state label=Alaska value=AK country="US"></states>';
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
</script>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
We have to follow this logic: After autocomplete selects value, we have to to check if values for other two fields are unique in their scope. For example, selecting country-code CA (xml value attribute) has unique label California, as well as unique country US. If the values is not unique, than we erase that input value. The checking function name is fillIfUnique(), take a look at this Fiddle.
HTML used:
<h3>jQuery Autocomplete using XML as Data Source Example</h3>
<form name="search_form" id="searchForm" method="GET">
<p><label for="labelBox">Label Search</label>
<input type="text" id="labelBox" name="labelBox" /></p>
<p><label for="valueBox">Value Search</label> <input type="text" id="valueBox" name="valueBox" /></p>
<p><label for="countryBox">Country Search</label> <input type="text" id="countryBox" name="countryBox" /></p>
<p><label></label> <button name="searchKeyword" id="searchKeyword">Submit</button></p>
</form>
Script:
$(document).ready(function() {
var myArrLabel = [];
var myArrValue = [];
var myArrCountry = [];
function parseXml(xml){
$(xml).find("state").each(function(){
var a1=[], a2=[], a3=[];
a1.push($(this).attr("label"));
a2.push($(this).attr("value"));
a3.push($(this).attr("country"));
$.each(a1, function(i, el){
if($.inArray(el, myArrLabel) === -1) myArrLabel.push(el);
});
$.each(a2, function(i, el){
if($.inArray(el, myArrValue) === -1) myArrValue.push(el);
});
$.each(a3, function(i, el){
if($.inArray(el, myArrCountry) === -1) myArrCountry.push(el);
});
});
};
parseXml( myXml );
function fillIfUnique(box1, box2, attr1, attr2) {
var value1 = box1.val();
var valueItemsForLabel = $(myXml).find('state[' + attr1 + '="' + value1 + '"]');
if ( valueItemsForLabel.length ) {
var value2 = valueItemsForLabel.eq(0).attr( attr2 );
console.log( 'value2: ' + value2 );
var totalSame = $(myXml).find('state[' + attr1 + '="' + value1 + '"][' + attr2 + '="' + value2 + '"]');
if( valueItemsForLabel.length==totalSame.length ) {
box2.val( value2 );
} else {
box2.val( '' );
};
};
};
function setupAC() {
$("input#labelBox").autocomplete({
source: myArrLabel,
minLength: 1,
select: function(event, ui) {
$("input#labelBox").val(ui.item.value);
fillIfUnique($('#labelBox'), $('#valueBox'), 'label', 'value');
fillIfUnique($('#labelBox'), $('#countryBox'), 'label', 'country');
}
});
$("input#valueBox").autocomplete({
source: myArrValue,
minLength: 1,
select: function(event, ui) {
$("input#valueBox").val(ui.item.value);
fillIfUnique($('#valueBox'), $('#labelBox'), 'value', 'label');
fillIfUnique($('#valueBox'), $('#countryBox'), 'value', 'country');
}
});
$("input#countryBox").autocomplete({
source: myArrCountry,
minLength: 1,
select: function(event, ui) {
$("input#countryBox").val(ui.item.value);
fillIfUnique($('#countryBox'), $('#labelBox'), 'country', 'label');
fillIfUnique($('#countryBox'), $('#valueBox'), 'country', 'value');
}
});
};
setupAC();
});
Notes: I had to compress and insert XML into script. I removed duplicate entries in arrays.