guys i have a column which contains text and button and what i want is when click on the button the text changed .. here is my code
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText();"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText() {
document.getElementById("txt_" + count).innerHTML = "hey";
}
so why it gives me that exception ? .. plz help .. btw i am beginner
the count inside setText is undefined.
1st change onclick function of button to pass the count variable
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
then accept the count as parameter
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
You can pass count to the function:
var count = 0;
$(document).ready(function() {
$("#jqGrid").jqGrid({
data: data.rows,
datatype: "local",
styleUI: "Bootstrap",
colModel: [
{
label: 'Customer ID',
name: 'CustomerID',
width: 180,
editable: true,
edittype: "custom",
id: "CustomerID",
editoptions: {
custom_element: function(value, options) {
var parts = value.split(' ');
var elemStr = '<div><input size="6" id="txt_"' + count + '" value="' + parts[0] +
'" /><input type="button" size="5" value="..." onclick="setText(' + count + ');"/></div>';
count++;
// return DOM element from jQuery object
return $(elemStr)[0];
},
custom_value: function(elem) {
var inputs = $("input", $(elem)[0]);
var first = inputs[0].value;
return first;
}
}
},
],
});
});
function setText(count) {
document.getElementById("txt_" + count).innerHTML = "hey";
}
Related
I'm using a parsley validator and somehow it affects my form. After submission, it won't clear all the inputs; especially hidden inputs. And when I tried to set some input value from javascript it won't show up.
I think it's because of my <form method="post" id="transaction_form">. I've tried to re-evaluate my HTML but still, it won't work properly.
$(document).ready(function () {
$("#cust_num").val(55555);
var exam_num = 12345;
var prod_num = 88998;
var prod_name = "Hello";
var prod_price = 150000;
var transactionTable = $("#transaction_table");
var trxprodcount = 0;
var subTotal = 0;
var endTotal = 0;
function clearinput() {
$("#transaction_form")[0].reset();
$("#transaction_form").parsley().reset();
//$('#get_productdata').attr('disabled', 'disabled');
$("#subtotal").html(0);
$("#endtotal").html(0);
}
clearinput();
function recount() {
subTotal = transactionTable.DataTable().column(3).data().sum();
$("#subtotal").html(subTotal);
endTotal = subTotal - (subTotal * $("#trx_disc").val()) / 100;
$("#endtotal").html(endTotal);
}
transactionTable.DataTable({
ordering: false,
responsive: true,
searching: false,
paging: false,
info: false,
fnRender: function (Obj) {
return "Rp" + Obj.Data[3];
},
drawCallback: function () {
recount();
},
});
$("#trx_disc").on("change", function () {
recount();
});
trxprodcount = trxprodcount + 1;
var exam_num = $("#cust_num").val() + "S" + trxprodcount;
var col_exam_num =
exam_num +
'<input type="hidden" name="hidden_exam_num[]" id="exam_num' +
trxprodcount +
'" class="exam_num" value="' +
exam_num +
'" />';
var col_exam_prod =
prod_num +
'<input type="hidden" name="hidden_exam_prod[]" id="exam_prod' +
trxprodcount +
'" value="' +
prod_num +
'" />';
var del_btn =
'<button type="button" name="del_prodtrx" id="' +
trxprodcount +
'" class="btn btn-danger btn-sm del_prodtrx" >Delete</button>';
transactionTable
.DataTable()
.row.add([col_exam_num, col_exam_prod, prod_name, prod_price, del_btn])
.draw()
.node();
$("#transaction_table").on("click", ".del_prodtrx", function () {
var row = $(this).parents("tr");
if ($(row).hasClass("child")) {
transactionTable.DataTable().row($(row).prev("tr")).remove().draw();
} else {
transactionTable.DataTable().row($(this).parents("tr")).remove().draw();
}
});
$("#transaction_form").on("submit", function (event) {
event.preventDefault();
if ($("#transaction_form").parsley().isValid()) {
var count_data = 0;
$(".exam_num").each(function () {
count_data = count_data + 1;
});
if (count_data > 0) {
clearinput();
} else {
$("#message").html(
'<div class="alert alert-danger">Customer/Product Kosong'
);
}
setTimeout(function () {
$("#message").html("");
}, 3000);
}
});
});
Live Example: https://jsfiddle.net/azissofyanp/9p7j1d6u/30/
And I'm very confused about it.
i need an help.
I have this code and i have to put a Save button to the end for store the changes or the new entry in DB.
I have the problem that i haven't idea to how put button in the end without change HTML code because i can't, i wuold insert button via javascript,
how can i do?
p.s: The problem is that i can't insert in those function because the function under here is called everytime a press a button, if a press another time is called another, and again.
p.s2: Tell me if the code is ok, in other case tell me how can i improve this
Thank you
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
$().ready(function() {
//Creation of array to simulate data from DB
var obj1 =
{
id: "1",
name: "Bryan",
surname: "Del Bianco"
};
var obj2 =
{
id: "2",
name: "Luca",
surname: "Del Bianco"
};
var exampleOfDatabase = new Array();
exampleOfDatabase.push(obj1);
exampleOfDatabase.push(obj2)
visualizzaModifica(exampleOfDatabase, $("#divTeamLeaderProduzione"))
function visualizzaModifica(array, div)
{
div.html("");
div.append("<br>");
let i = 1;
array.forEach(function(e) {
div.append(
"<div id='div" + i + "' class='input-group'>" +
"<input type='text' id='inputModificaNome" + i + "' class='form-control' value='" + e.name + "'>" +
"<input type='text' id='inputModificaCellulare" + i + "' class='form-control' value='" + e.surname + "'>" +
"</div>"
);
i++;
});
aggiungiInput(i, div);
}
function aggiungiInput(i,div)
{
if($("#div"+i).length == 0)
{
var next = $("<div>",
{
id: 'div'+i,
class: 'input-group'
});
var inputNome = $('<input>',
{
id: 'inputModificaNome'+i,
type: 'text',
class: 'form-control'
});
var inputCellulare = $('<input>',
{
id: "inputModificaCellulare"+i,
type: 'text',
class: 'form-control'
});
next.on('change', function ()
{
aggiungiInput(i+1, div);
});
next.append(inputNome);
next.append(inputCellulare);
div.append(next);
}
$("#btnSave").remove();
div.append("<input type='button' value='Save' id='btnSave' />");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divTeamLeaderProduzione">
</div>
I removed the button and placed it when needed. Hope it helps. Cheers..!!
I'm new in jquery and I found on google that I can do what I want using .clone...
But, it works but not completely. Here I have a row which I need to clone when user click on the add button :
<table id="tableTest">
<tr id="row_element_1" name="row_element">
<td><span id="labelNumber_1" name="labelNumber_1">1</span></td>
<td>
<select id="supplier_1" name="comboA_1" onchange="classTest.loadComboB(this.value, 'ComboB_1')" class="select"></select>
</td>
<td>
<select name="ComboB_1" id="ComboB_1" onchange="classTest.loadComboC(this.value, document.getElementById('comboA_1').value, 'ComboC_1')" class="select"></select>
</td>
<td>
<select name="ComboC_1" id="ComboC_1" onchange="classTest.loadInputA(this.value, 'inputA_1')" class="select"></select>
</td>
<td>
<input type="text" name="inputA_1" id="inputA_1" />
</td>
<td>
<input type="number" min="0" name="inputB_1" id="inputB_1" required="1" value="0" onchange="classTest.calculateTotal('inputA_1', this.value, inputC_1)" />
</td>
<td>
<input type="text" name="inputC_1" id="inputC_1" readonly="readonly" />
</td>
<td>
<button id="remove_btn_1" name="remove_product_btn_1" onclick="classTest.removeElement()">Remove</button>
</td>
<td>
<button id="add_btn_1" name="add_product_btn_1" onclick="classTest.addElement(this)">Add</button>
</td>
</tr>
</table>
I'm able to clone it using this but my problem is that the event (like the "onchange" are not changed with the new dynamic value...
var classTest = {
loadComboB : function (_idComboA_Selected, comboB) {
$.ajax({
method: 'POST',
url: 'phpfilewithquery.php',
data: {
moduleId: 'test',
itemId: _idComboA_Selected,
action: 'loabCb_B',
},
reader: {
type: 'json',
root: 'items'
},
success: function (json_res) {
//console.log(json_res);
var items = jQuery.parseJSON( json_res );
comboBox.replaceOption(comboB, items.items); // custom function which load the combobox "comboB" with items.items
}
});
},
loadComboC : function (_idComboB_Selected, _idComboA_Selected, comboC) {
$.ajax({
method: 'POST',
url: 'phpfilewithquery.php',
data: {
moduleId: 'test',
gammeId: _idComboB_Selected,
supplierId : _idComboA_Selected,
action: 'loadCb_C',
},
reader: {
type: 'json',
root: 'items'
},
success: function (json_res) {
var items = jQuery.parseJSON( json_res );
comboBox.replaceOption(comboC, items.items);
}
});
},
loadInputA : function (_idComboC_Selected, inputA_val) {
$.ajax({
method: 'POST',
url: 'phpfilewithquery.php',
data: {
moduleId: 'test',
productId : _idComboC_Selected,
action: 'loadInp_A',
},
reader: {
type: 'json',
root: 'items'
},
success: function (json_res) {
var res = jQuery.parseJSON( json_res );
$('#' + inputA_1).val( res.price );
// this.calculateTotal();
}
});
},
calculateTotal: function (inputA, inputB, inputC){
var price = $('#' + inputA).val();
var qty = $('#' + inputB).val();
var tmp = price * qty;
var total = tmp.toFixed(2);
$('#' + inputC).val(total + ' $');
},
removeProduct: function (elm){
},
addProduct: function (elm){
console.log(elm.parentNode.parentNode);
var rowToClone = $(elm.parentNode.parentNode).clone(true, true);
//var newRow = document.getElementById('tableProduct').appendChild(rowToClone);
var attrLabel = rowToClone.find('span').attr('name');
var temp = attrLabel.split("_");
var number = parseInt(temp[temp.length-1]);
var newNumber = number+1;
rowToClone.find('input').each(function() {
if(this.name) {
this.name= this.name.replace('_' + number , '_' + newNumber );
this.id= this.id.replace('_' + number , '_' + newNumber );
}
});
rowToClone.find('span').each(function() {
if(this.name){
this.name= this.name.replace('_' + number , '_' + newNumber );
this.id= this.id.replace('_' + number , '_' + newNumber );
this.html(number);
}
});
rowToClone.find('select').each(function() {
if(this.name) {
this.name= this.name.replace('_' + number , '_' + newNumber );
this.id= this.id.replace('_' + number , '_' + newNumber );
$( '#' + this.id.replace('_' + number , '_' + newNumber ) ).empty();
}
});
rowToClone.find('button').each(function() {
if(this.name){
this.name= this.name.replace('_' + number , '_' + newNumber );
this.id= this.id.replace('_' + number , '_' + newNumber );
}
});
$("#tableTest").append(rowToClone);
}
};
So, I can I clone a row and changing the dynamic element in the event?
Also, I need to call "calculateTotal" on success in the "loadInputA" function. Do I need to pass all the arguments to the "loadInputA" ?
I have select list like this:
$.fn.optionTest = function(opts) {
var option = $.extend({}, $.fn.optionTest.defaults, opts);
$(this).change(function() {
option.holderObject = $(this);
if (option.clearOnChange) {
$(option.actionId).empty();
}
var val = $(this).val();
if ($.fn.optionTest.isArray(val)) {
$.fn.optionTest.parseArray(val, option);
} else {
var label = $(this).children("option:selected").eq(0).text();
$.fn.optionTest.parseContent(val, option, label);
}
$('.' + option.removeLinkOptions.class).click(function(event) {
$.fn.optionTest.removeRow(this, option);
event.preventDefault();
});
$("[type=date]").datepicker({
monthNamesShort: $.datepicker.regional["en"].monthNames,
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: "-116:+10",
});
return this;
});
};
$.fn.optionTest.isArray = function(val) {
return Object.prototype.toString.call(val) === '[object Array]';
};
$.fn.optionTest.defaults = {
clearOnChange: false,
actionId: '#action',
indexOptions: {
class: 'field-style field-split25 align-left'
},
rowOptions: {
class: 'certificates',
type: 'text',
name: 'CertificateType[]',
tag: 'ul'
},
CertNoOptions: {
name: 'CertNo[]',
type: 'text',
placeholder: 'Cert No.',
size: 20,
class: 'field-style field-split25 align-left'
},
PlaceofIssueOptions: {
name: 'PlaceofIssueCert[]',
type: 'text',
placeholder: 'Place of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
fromOptions: {
name: 'FromCert[]',
type: 'date',
placeholder: 'Date of Issue',
size: 20,
class: 'field-style field-split25 align-left'
},
toOptions: {
name: 'ToCert[]',
type: 'date',
placeholder: 'Date of Expire',
size: 20,
class: 'field-style field-split25 align-left'
},
labelOptions: {
class: 'field-style field-split25 align-left',
type: 'text'
},
removeLinkOptions: {
class: 'removeRow',
href: 'javascript:;'
}
};
$.fn.optionTest.parseArray = function(vals, options) {
var selectedOptions = options.holderObject.children("option:selected");
console.log(selectedOptions.eq(0).html());
$.each(vals, function(key, val) {
$.fn.optionTest.parseContent(val, options, selectedOptions.eq(key).text());
});
};
$.fn.optionTest.removeRow = function(elem, options) {
var row = $(elem).closest(".certificates");
row.remove();
$.fn.optionTest.updateRowIndex(options);
};
$.fn.optionTest.updateRowIndex = function(options) {
$("." + options.rowOptions.class).each(function(key, value) {
var index = key + 1;
$(value).attr('rowdataid', index);
$(value).children("." + options.indexOptions.class).html(index);
});
};
$.fn.optionTest.createColumn = function(content) {
var li = $('<li>');
return li.append(content);
}
$.fn.optionTest.parseContent = function(val, options, label) {
var index = $('.' + options.rowOptions.class).length + 1;
var rowData = $.extend({}, options.rowOptions);
var indexData = $.extend({}, options.indexOptions);
rowData.rowDataId = index;
var CertNoData = $.extend({}, options.CertNoOptions);
CertNoData.name = CertNoData.name;
var PlaceofIssueData = $.extend({}, options.PlaceofIssueOptions);
PlaceofIssueData.name = PlaceofIssueData.name;
var DateofIssueData = $.extend({}, options.DateofIssueOptions);
DateofIssueData.name = DateofIssueData.name;
var DateofExpireData = $.extend({}, options.DateofExpireOptions);
DateofExpireData.name = DateofExpireData.name;
var fromData = $.extend({}, options.fromOptions);
fromData.name = fromData.name;
var toData = $.extend({}, options.toOptions);
toData.name = toData.name;
var start_by = "<li><ul class='column'><li>";
var end_by = "</li></ul></li>";
var labelData = $.extend({}, options.labelOptions);
if ($('#' + rowData.id).length == 0) {
var tag = "<" + rowData.tag + ">";
delete rowData['tag'];
var row = $(tag, rowData);
var id = $('<li>', indexData).html(index);
//var label = $('<li>', labelData).html(label);
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
var CertNo = $.fn.optionTest.createColumn($("<input>", CertNoData));
CertNo = $(start_by + $(CertNo).html() + end_by);
var PlaceofIssue = $.fn.optionTest.createColumn($("<input>", PlaceofIssueData));
PlaceofIssue = $(start_by + $(PlaceofIssue).html() + end_by);
var DateofIssue = $.fn.optionTest.createColumn($("<input>", DateofIssueData));
DateofIssue = $(start_by + $(DateofIssue).html() + end_by);
var DateofExpire = $.fn.optionTest.createColumn($("<input>", DateofExpireData));
DateofExpire = $(start_by + $(DateofExpire).html() + end_by);
var from = $.fn.optionTest.createColumn($("<input>", fromData));
from = $(start_by + $(from).html() + end_by);
var to = $.fn.optionTest.createColumn($("<input>", toData));
to = $(start_by + $(to).html() + end_by);
var removeRow = $.fn.optionTest.createColumn($("<button>", options.removeLinkOptions).text("X"));
removeRow = $($(removeRow).html());
// row.append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
row.append('<input type="hidden" name="RowCertificateType[]" value="' + val + '" />').append(label).append(CertNo).append(PlaceofIssue).append(from).append(to).append(removeRow);
$(options.actionId).append(row);
}
};
$(document).ready(function() {
$('#options').optionTest({
actionId: '.action2',
clearOnChange: false
});
});
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<fieldset class="fieldset-borders">
<legend>6. Certificates</legend>
<ul class="header">
<li>
<select id='options' name="CertificateType[]" class="field-style div-format align-left">
<option selected disabled value="0">Select certificates</option>
<option value="1">Foo</option>
<option value="2">Bar</option>
<option value="3">OTHER</option>
</select>
</li>
</ul>
<div class="action2" ></div>
</fieldset>
As you see after selecting any option from list It adding some fields. I need to add text field label with value that selected from options.
As in example I have 3 options:
Foo
Bar
OTHER
If I select Foo It should add fields like:
Foo [ ] [ ] [ ] [ ]
If I select Bar It should add fields like:
Bar [ ] [ ] [ ] [ ]
If I select OTHER It should generate only blank fields without value:
[ ] [ ] [ ] [ ] [ ]
For now It adding all blank fields for any selected option.
If I use:
var label = $('<li>', labelData).html(label);
Instead of:
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
It adding label field with value, but not editable, It's not text field and after adding OTHER It can't be changed.
Have you ideas how can I achieve correct syntax with If? Something like:
If (option selected = 'OTHER') {
var label = $.fn.optionTest.createColumn($("<input>", labelData));
label = $(start_by + $(label).html() + end_by);
}
else {
var label = $('<li>', labelData).html(label);
}
I cannot be certain that I understand your question, but I think what you want is for the selected label to display as the value in the first input field, unless the selected label is "OTHER", in which case the field should have no value property.
If this is correct, we could achieve this by extending our labelData object:
var labelData = $.extend({}, options.labelOptions, {
value: ((label === 'OTHER') ? '' : label)
});
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.