Populate checkbox from JSON data - javascript

I am having trouble trying to re-populate a form with has come from a JSON object. I have used JSON.stringify(name) and for the value as well and it returns me the type of data format I think might work. But can't seem to get in the $.each method
function fetchOrderFromLocalStorage() {
PROCESS_SAVE = true;
var mcs = localStorage.getItem(REPORTS_KEY);
console.log(mcs);
var jsn = JSON.parse(mcs);
console.log(jsn);
if (mcs.length == 0) {
return false;
}
$.each(jsn, function (name, val) {
var $el = $("input[name='" + name + "']"),
type = $el.attr('type');
console.log(JSON.stringify(name) + ":" + JSON.stringify(val));
switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="' + val + '"]').attr('checked', 'checked');
break;
default:
$el.val(val);
}
});
//console.log(jsn);
//for (var i = 0; i < jsn.length; i++) {
// var formInput = jsn[i];
// $("form input[name='" + formInput.name + "']").val(formInput.value);
//}
}
The commented out code at the bottom works, but I want to populate checkboxs as well so I have tried some code from here that has been checked to work. So I am trying it but my data is not in the correct format. I think I want JSON.Stringify() as the sonsole give me the correct result according to jQuery docs.

try this
function fetchOrderFromLocalStorage() {
PROCESS_SAVE = true;
var mcs = localStorage.getItem(REPORTS_KEY);
console.log(mcs);
var jsn = JSON.parse(mcs);
console.log(jsn);
if (mcs.length == 0) {
return false;
}
for (var i = 0; i < jsn.length; i++) {
var formInput = jsn[i],
$el = $("input[name='" + formInput.name + "']"),
type = $el.attr('type');
switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="'+formInput.value+'"]').attr('checked', 'checked');
break;
default:
$el.val(formInput.value);
}
}
}

Related

want to display duplicate ranks selected along with exactly which ranks are duplicated using javascript/ jquery

Here we added the logic to display which ranks are duplicated but I also want to display exactly which rank is duplicated. Ranks are from 0 to 18.
function validate(sdd_ejrp_form)
{
var duplicateRanksDetected = false;
var validate_rank_str = ",";
jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function (index)
{ var jqThis = jq(this);
var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
jqThis.find("\[data-dom-id=proficiency-level\]").each(function (index2)
{
var btn = jq(this);
if (btn.hasClass("active"))
{
if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1)
{
duplicateRanksDetected = true;
return false;
} else
{
validate_rank_str += prof_lvl_rank + ",";
}
}
});
});
if (duplicateRanksDetected == true)
{
// here I want to display exactly which rank is duplicated
alert("Duplicate ranks detected!");
return false;
}
}
}
It's easy as 3 modifications:
function validate(sdd_ejrp_form) {
var duplicateRanksDetected = []; //create an array here
var validate_rank_str = ",";
jq("\[data-dom-id=gsc-containers\]").find("\[data-dom-id=gsc-container\]").each(function(index) {
var jqThis = jq(this);
var gsc_uri = jqThis.attr("data-gsc-data-gsc-uri");
var prof_lvl_rank = jqThis.find("select\[name='prof-lvl-rank'\]").val();
jqThis.find("\[data-dom-id=proficiency-level\]").each(function(index2) {
var btn = jq(this);
if (btn.hasClass("active")) {
if (validate_rank_str.indexOf("," + prof_lvl_rank + ",") != -1) {
duplicateRanksDetected.push(prof_lvl_rank); // fill the array here
return false;
} else {
validate_rank_str += prof_lvl_rank + ",";
}
}
});
});
if (duplicateRanksDetected.length > 0) {
// here I want to display exactly which rank is duplicated
alert(
"Duplicate ranks detected: " +
duplicateRanksDetected.join(', ') // display the result here
);
return false;
}
}

indexof doesn't change until the variable is empty or a specified value even though it should check on every keyup event

I can't update my compatibilityIndex boolean value on every keyup, because the value of indexof on which it depends updates itself only when one of the search values is emptied or has specified value, like "rice" or "red wine". Does anyone know, why is it happening even though it should check it on every keyup event?
<div class="row">
<h1 class="big col-xs-12">Prepare your dinner according to the reference of mixing rules to attain the optimum harmony of taste.</h1>
</div>
<hr />
<h2 class="searchQ">Main ingredient</h2>
<input type="text" name="ingredient1" class="search search1" value="">
<hr />
<h2 class="searchQ">Complementary ingredient</h2>
<input type="text" name="ingredient2" class="search search2" value="">
<hr />
<h1>You <span class="can">can</span> mix <span class="searchVal1"></span> <span class="and"></span> <span class="searchVal2"></span> with:</h1>
<ul class="list1"></ul>
<ul class="list2"></ul>
<script>
var redWine = ['Red Wine','Cheese','Cured Meats','Red Meat'];
var rice = ['Rice','White Wine','Chicken'];
var whiteWine = ['White Wine','Chicken','Oyster','Rice'];
var notFound = "Nope, don't think you can eat that";
var search = $('.search');
var search1 = $('.search1');
var search2 = $('.search2');
var search1conv = [];
var search2conv = [];
var compatibilityIndex = false;
var can = $('.can');
var searchVal1 = $('.searchVal1');
var and = $('.and');
var searchVal2 = $('.searchVal2');
var list1 = $('.list1');
var list2 = $('.list2');
function checking(checkedVal, searchConv, list) {
switch ( checkedVal.toLowerCase() ) {
case 'red wine':
case 'wine red':
case 'wine, red':
list.empty();
searchConv = redWine;
for (var i = 1; i < redWine.length; i++) {
list.append('<li>' + redWine[i] + '</li>');
}
break;
case 'rice':
list.empty();
searchConv = rice;
for (var i = 1; i < rice.length; i++) {
list.append('<li>' + rice[i] + '</li>');
}
break;
case 'white wine':
case 'wine white':
case 'wine, white':
list.empty();
searchConv = whiteWine;
for (var i = 1; i < whiteWine.length; i++) {
list.append('<li>' + whiteWine[i] + '</li>');
}
break;
default:
list.empty().append('<h2>' + notFound + '</h2>');
break;
}
}
var compatible = function(ing1, ing2) {
if ( ing1.indexOf(ing2[0]) > -1 && ing2.indexOf(ing1[0]) > -1 ) {
compatibilityIndex = true;
} else {
compatibilityIndex = false;
}
}
var main = function() {
search.keyup(function() {
if (search1.val() != 0 || search2.val() != 0) {
if (search1.val() != 0) {
checking( search1.val() , search1conv , list1 );
} else {
list1.empty();
}
if (search2.val() != 0) {
checking( search2.val() , search2conv , list2 );
} else {
list2.empty();
}
} else {
searchVal1.empty();
searchVal2.empty();
list1.empty();
list2.empty();
}
if (search1.val() != 0 && search2.val() != 0) {
compatible(search1conv, search2conv);
if (compatibilityIndex) {
can.text('can').removeClass('red').addClass('green');
} else {
can.text('can\'t').removeClass('green').addClass('red');
}
searchVal1.text( search1.val() );
and.text('and' + " " + search1conv.indexOf(search2conv[0]) + " " + search2conv.indexOf(search1conv[0]));
searchVal2.text( search2.val() );
} else {
if (search1.val() == 0) {
can.text('can').removeClass('red').removeClass('green');
searchVal1.empty();
and.empty();
} else {
searchVal1.text( search1.val() );
}
if (search2.val() == 0) {
can.text('can').removeClass('red').removeClass('green');
searchVal2.empty();
and.empty();
} else {
searchVal2.text( search2.val() );
}
}
});
}
$(document).ready(main);
</script>
First, let me apologize in that this isn't an answer to your question, but as I started to go through your code, I see tremendous amounts of redundancy in variables and functions. This makes your code more complex and more difficult to debug. I would start by simplifying the code. For example, you don't need a checking1 and checking2 function - they both do the same thing, they just operate on different data. By passing more data to the function, you can have one function for both sets of data:
function checking(checkedVal, searchConv, list) {
switch ( checkedVal.toLowerCase() ) {
case 'red wine':
case 'wine red':
case 'wine, red':
list.empty();
searchConv = redWine;
for (var i = 1; i < redWine.length; i++) {
list.append('<li>' + redWine[i] + '</li>');
}
break;
case 'rice':
list.empty();
searchConv = rice;
for (var i = 1; i < rice.length; i++) {
list.append('<li>' + rice[i] + '</li>');
}
break;
case 'white wine':
case 'wine white':
case 'wine, white':
list.empty();
searchConv = whiteWine;
for (var i = 1; i < whiteWine.length; i++) {
list.append('<li>' + whiteWine[i] + '</li>');
}
break;
default:
list.empty().append('<h2>' + notFound + '</h2>');
break;
}
}
I see lots of other examples of redundancy in your code. Again, my apologies - I know you didn't ask for this advice, but I believe that it will help you in the long run to find any problems you are encountering.

JSON return value to global variable

Simply my code looks like this:
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.
here it my real code if you need to take a look:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});
in a loop block, before one ajax complete other one will be run and this's javascript natural treatment. For your case you can call a function at the end of success event. Do something like this:
var i = 0;
doSt();
function doSt() {
var orderinvoice = 0;
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g, '')).replace(/Qty /g, '');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g, '');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', { 'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink }, function(e) {
console.log();
document.getElementById("result").innerText = document.getElementById("result").innerText + "Order #" + e.result + " Created Successfully ";
document.getElementById("invoker").innerText = "" + e.invoice;
orderinvoice = e.invoice;
if (i + 1 == table.rows.length) {
document.getElementById("result").innerText = document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
i++;
if (i < table.rows.length) doSt();
});
}
I think you need a recursive function that always deals with the first element in your rows array and then splices it off and calls itself. For example, something like this:
function getStuff(rows, results) {
if (rows.length > 0) {
var ordername = rows[0].cells[5].innerText;
$.getJSON('orderprocess.php', { 'ord_name': ordername }, function (e) {
// do some stuff
results.push('aggregate some things here?');
rows.splice(0, 1);
return getStuff(rows, results);
});
} else {
return results;
}
}
When the array is spent, results will be returned with whatever aggregate you wanted at the end of the cycle. Then, you can do as you please with the results. I think you can also manipulate the DOM inside the function as you see fit if that makes more sense. Hope this helps.

Custom JQuery dynamic link creation

I'm pretty new to js and having a hard time figuring out the best way to generate a custom url depending on what links are selected. You can view what I have done here. http://jsfiddle.net/1fz50z1y/26/ I will also paste my info here.
var products = [];
var quantity = [];
qstring = '';
$('input.product-radio, select.products-howmany').change(function() {
var $this = $(this)
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
var qid = $select.val();
var pid = $radio.val();
currentStatus = $radio.prop('checked'),
theString = '';
qString = '';
pString = '';
if (currentStatus) {
products.push(pid);
quantity.push(qid);
if ($product.find('div.quantity').removeClass('q-hidden')) {
//code
}
} else {
products.splice(products.indexOf(pid), 1);
quantity.splice(quantity.indexOf(qid), 1);
$product.find('div.quantity').addClass('q-hidden');
}
if ((products.length > -1) || (quantity.length > -1)) {
if ((products.length === 0) || (quantity.length === 0)) {
console.log("Q Length: " + quantity.length);
pString += products[0];
qString += quantity[0];
console.log("qString = " + quantity);
} else {
pString = products.join('-p');
qString = quantity.join('_q');
if (quantity.length > 1) {
qString = quantity.splice(quantity.indexOf(qid), 1);
pString = products.splice(products.indexOf(pid), 1);
}
console.log("+ Q Length: " + quantity.length);
console.log("ADDING " + "p" + pString + "_q" + qString);
}
if ((qString == 'undefined') || (pString == 'undefined')) {
$('a.options-cart').prop("href", "#");
} else {
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "_q" + qstring + "?destination=/cart");
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "?destination=/cart");
$('a.options-cart').prop("href", "/cart/add/p" + pString + "_q" + qString + "?destination=/cart");
}
}
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});
When you click on the add link icon it displays a drop down where you can select the quantity. So changing the quantity should also update the link and how it is created. I am trying to figure out how to create the link so the end result looks like so.
cart/add/p123_q1?destination=/cart this is how it would look with a single item. Where p = the product ID and q = the quantity. Unclicking the add to cart should remove those items and changing the drop down should update the quantity. If there is more than one item it should append to the link like so. cart/add/p123_q1-p234_q2-p232_q4?destination=/cart and then unclicking or changing quantity on any of those items should reflect the change in the link. I am not sure if I am going about this all wrong but I have been trying forever and many different routes to go about trying to achieve this effect. If anyone could please help me figure this out I would be greatly appreciated!
I was able to get this to work properly using this piece of code. Hope this maybe helps someone.
$('input.product-radio, select.products-howmany').change(function () {
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
$product.find('div.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
$product.find('label.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
var string = $('.product-radio')
.filter(':checked')
.map(function(){
return $(this)
.closest('.product-options-left')
.find('.products-howmany')
.val();
})
.get()
.join('-');
$('a.options-cart').prop("href", "/cart/add/" + string + "?destination=/cart");
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});

escaped URL parameters statements if else switch

There is a little problem with this code:
function getParameters() {
var searchString = document.getElementById('input1').value,
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
console.log(hash);
//return hash;
if(val[0] == "class"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.setAttribute(attribute,value);
});
}
else if(val[0] == "color"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.style[attribute]=value;
});
}
monitor_test_div.innerText = ccc.innerHTML;
}
Depending by the order in which the parameters are inserted, they are repeated or dont work...
style a div using escaped URL parameters
Demo: JSFiddle 1
Demo: JSFiddle 2
I would like to obtain this:
Example 1:
input:
opacity=0&src=link1&color=red&color=green&src=link2&height=200
output:
<div src="link2" style="color: green;"></div>
Example 2:
input:
src=link1&color=red or color=red&src=link1
output:
<div src="link1" style="color: red;"></div>
in your line
if(val[0] == "class")
you are only checking the first element in your val array.
what you would want to do, is iterate through all the hash objects and simply check the attribute like this:
function getParameters() {
var searchString = document.getElementById('input1').value,
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
console.log(hash);
//return hash;
$.each(hash, function( attribute, value ) {
if(attribute=="color"){
test_div.style[attribute]=value;
}
else if(attribute=="src"){
alert(attribute);
test_div.setAttribute(attribute,value);
}
});
}
here is a working FIDDLE
Maybe you want something like this:
var test_div = $('#test_divs_id');
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
var key = unescape(val[0]);
var val = unescape(val[1]);
switch(key) {
case 'class': // treat 'class' key by ...
test_div.addClass(val); // ... adding the value as a class
break;
case 'src': // treat 'src' key,
case 'href': // treat 'href' key, maybe more ...
test_div.attr(key, val); //... by adding as an attribute with value
break;
default: // all other keys...
test_div.css(key, val); // ... are assumed css style names with value
break;
}
EDIT: Extended the switch with the examples + possibly more attributes

Categories

Resources