How to fill multiple input fields from one a HREF - javascript

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.

Related

Trying to add new form fields for additional data and getting weird return

I have a jquery script that is supposed to create new table and input fields with a _1 for the new data field. The code does add the table and the fields however the input fields have this when doing a view source of the code.
I am not sure why I am getting [object Object]1 for the form fields.
Also if I add an additional table the other fields get this.
visitor_first_name_NaN where this should be 2 or 3
I am sure I am missing something just not sure what. If anyone has an idea or a fix it would be great.
<script type='text/javascript'>//<![CDATA[
jQuery(document).ready(function(){
jQuery("##visitorRegFrm").validate({
errorElement : "div",
errorPlacement: function(error, element) {
error.appendTo( element.parent("td") );
}
});
});
var arr = new Array();
arr[#qrStaff.currentrow#] = new Array();
arr[#qrStaff.currentrow#][1] = '#qrStaff.Staff_Last_Name#';
arr[#qrStaff.currentrow#][2] = '#qrStaff.Staff_Email#';
arr[#qrStaff.currentrow#][3] = '#qrStaff.Staff_First_Name#';
function changeEmp(obj){
//console.log(jQuery(obj).val());
jQuery('##employee_last_name').val(arr[jQuery(obj).val()][1]);
jQuery('##employee_email').val(arr[jQuery(obj).val()][2]);
jQuery('##employee_first_name_text').val(arr[jQuery(obj).val()][3]);
}
jQuery.format = function(source, params) {
if ( arguments.length == 1 )
return function() {
var args = jQuery.makeArray(arguments);
args.unshift(source);
return jQuery.validator.format.apply( this, args );
};
if ( arguments.length > 2 && params.constructor != Array ) {
params = jQuery.makeArray(arguments).slice(1);
}
if ( params.constructor != Array ) {
params = [ params ];
}
jQuery.each(params, function(i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
};
jQuery(window).on('load',function(){
incdecVar = 1;
jQuery(function() {
var scntDiv = jQuery('##addTable');
var i = jQuery('##addTable table').size + 1;
jQuery('##addNewVistor').on('click', function() {
jQuery('<table class="newTbl" width="100%" border="0" cellpadding="4" cellspacing="5"><tr><td colspan="4"><h3>Visitor Information</h3>Remove</td></tr><tr><td width="25%">First Name:<span class="verror"></span></td><td width="25%"><input type="text" name="visitor_first_name_' + i +'" value="" class="required"/></td><td width="20%">Last Name:<span class="verror"></span></td><td width="30%"><input type="text" name="visitor_last_name_' + i +'" value="" class="required"/></td></tr><tr><td>Title:<span class="verror"></span> </td><td><input type="text" name="visitor_title_' + i +'" value="" class="required"/></td><td>Company:<span class="verror"></span> </td><td><input type="text" name="visitor_company_' + i +'" value="" class="required"/></td></tr><tr><td>Phone:</td><td><input type="text" name="visitor_phone_' + i +'" value=""/></td><td>Email:<span class="verror"></span> </td><td><input type="text" name="visitor_email_' + i +'" value="" class="email"/></td></tr></table>').appendTo(scntDiv);
jQuery('input##Counter').replaceWith('<input type="hidden" name="Counter" id="Counter" value="'+ i +'" />');
newValue = parseInt(jQuery('input##Counter').val())+1;
jQuery('input##Counter').val(newValue);
incdecVar += newValue;
i++;
return false;
});
jQuery('##remNewVisitor').on('click', function() {
if( i > 2 ) {
jQuery(this).parents('.newTbl').remove();
newValue = parseInt(jQuery('input##Counter').val())-1;
jQuery('input##Counter').val(newValue);
incdecVar -= newValue;
i--;
}
return false;
});
});
});//]]>
</script>

How to search and retrieve data from json file in Jquery?

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.

Cannot set property 'innerHTML' of null in javascript

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";
}

Embedding values using for loop

As I m having incremental values of attributes so i am ´following this method as you can see I hardcoded my attributes butI want to embed them in a loop..please tell how can i do that.. I am not able to achieve that...Thank you..
I m getting values in my dropdown from a json file in which i m having 20 attributes...When i click on particular value from dropdown ...the attributes related to that value are shown inside a list box..
My html
form name="myform" id="myForm">
<select id="dropdown1"></select>
<select id="listbox"></select>
<!-- <input type="checkbox">-->
<br>
(document).ready(function() {
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
/* $('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#dropdown1');
*/
$.each(usedNames, function(index, value) {
$('<option>', {
text: value['name'],
value: index
}).appendTo('#dropdown1');
});
/* $('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox'); */
$('#dropdown1').change(function() {
$('#listbox').empty();
$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');
var selection = $('#dropdown1 :selected').text();
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
});
});
}
});
});
You can use a for loop to generate the option elements as all the attributes are incremental. Try this:
var selection = $('#dropdown1 :selected').text();
$.each(jsObject, function(index, value) {
if (value['name'] === selection) {
var optionHtml = '';
for (var i = 1; i <= 20; i++) {
var attr = 'attr' + ('000' + i).substr(-3);
optionHtml += '<option value="' + attr + '">' + value[attr] + '</option>';
}
$('#listbox').append(optionHtml);
}
});
Working example
Note that this also builds the HTML as a single string and appends it to the DOM once for better performance.

How to get the values of all textfields in add/remove textfields and form JSON

I'm using a plugin to duplicate textfields on add and remove buttons. Now, after getting the fields added and removed, I want to form JSON out of all the textfields and POST it on submit.
Below is the code -
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
JSFiddle can be referred to.
I want to get the values of all textfields and form JSON.
Iterate through the input fields, grab their values, and push them through JSON.stringify to create your desired JSON.
function serializeAndPost() {
var values = [];
$( '#p_scents input[id^=p_scnt_]' ).each( function ( index, element ) {
values.push( element.value );
} );
var json = JSON.stringify( { "welcomesList": values } );
// Do your POSTing here
}
Updated fiddle:
https://jsfiddle.net/tZPg4/11019/
I don't know if this is the best solution as I am building a string rather than an JSON object but here is my solution:
HTML
<input type="button" id="btnSubmit" value="Submit"></input>
JS:
$(function () {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 1;
$('#addScnt').live('click', function () {
$('<p><label for="p_scnts"><input type="text" id="p_scnt_' + i + '" size="20" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> Remove</p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function () {
if (i > 2) {
$(this).parents('p').remove();
i--;
}
return false;
});
$('#btnSubmit').click(function(e) {
e.preventDefault();
var str = [];
$.each($('input[type=text]'), function(i, val) {
var el = $(this);
str.push('"' + el.attr("id") + '":"' + el.val() +'"');
});
var json_string = "{" + str + "}";
});
});

Categories

Resources