How to Convert serializedObject to UL (unordered list)? - javascript

Anyone knows how to convert the output from this code into an unordered list?
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
The code above outputs for example like this:
{"costPerDay":"20","numberOfDays":"20","designCost":"40","cmsIntegration":"64","seoContentStrategy":"75"}
I was hoping if there's a way to make it output into an unordered list?

I guess the code you made does not work, maybe this will help you better figure out what i am aiming for, attached is the full code that I wanted the output as "Unordered List" and the source in CodePen http://jsfiddle.net/JOEHOELLER/217m94fk/2/ If you want to check out the working Range Slider. Thanks
function proRangeSlider(sliderid, outputid, colorclass) {
var x = document.getElementById(sliderid).value;
document.getElementById(outputid).innerHTML = x;
document.getElementById(sliderid).setAttribute('class', colorclass);
updateTotal();
}
var total = 0;
function updateTotal() {
var list= document.getElementsByClassName("range");
[].forEach.call(list, function(el) {
console.log(el.value);
total += parseInt(el.value);
});
document.getElementById("n_total").innerHTML = total;
}
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
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;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});

I'm not sure how your desired result is supposed to look like, but either way you can just iterate over your object:
// let obj = JSON.stringify($('form').serializeObject())
let obj = {"costPerDay":"20","numberOfDays":"20","designCost":"40","cmsIntegration":"64","seoContentStrategy":"75"};
$("#result").empty().append("<ul></ul>");
for (const entry in obj){
$("#result > ul").append(`<li>${entry}: ${obj[entry]}</li>`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
Or if you prefer a single-liner:
$("#result").empty().append(
"<ul>" + Object.entries(obj).map(e => `<li>${e[0]}: ${e[1]}`).join("") + "</ul>"
);
Working demo:
http://jsfiddle.net/7a5xjwbh/

Related

How to put a condition in jQuery's map function?

I am trying to put a condition in jQuery's map function. My issue is that I don't want the same number in the map function value. When it is the same I want to display an alert box. My map function code is like this:
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
return this.value;
}).get();
If I get a value like 1,2,3,4,5 it's ok, but if I get a value like 1,2,3,2,5, I want to display an alert box. Is it possible?
How to put a condition in jQuery's map function?
function change_rank() {
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if() {
} else { }
return this.value;
}).get();
var vals = []
$('input[type=text][class = cate_rank]').each(function(){
if($(this).val() && (typeof vals[$(this).val()] == 'undefined')){
vals[$(this).val()] = 1;
var last_val = $(this).val();
}else if($(this).val() && (typeof last_val != 'undefined') && parseInt(last_val) > parseInt($(this).val())){
alert('Whooah! Something went terribly wrong! Inputs don\'t have values ordered incrementally!');
}else{
alert('Whooah! Something went wrong! We got two inputes with same value!');
}
});
Check this,
var rankbox= $(".test").map(function() {
return this.value;
}).get();
var sorted_arr = rankbox.slice().sort();
var results = [];
for (var i = 0; i < rankbox.length - 1; i++) {
if (sorted_arr[i + 1] == sorted_arr[i]) {
results.push(sorted_arr[i]);
}
}
var rankbox= $(".test").map(function() {
if($.inArray(this.value, results) > -1){
alert(this.value+" is duplicate");
}
return this.value;
}).get();
I took reference of this link
If you are Looking to check dup you can try this:
var x=[1,2,3,2,5]
var has=!x.every(function(v,i) {
return x.indexOf(v) == i;
});
console.log(has);//true means dup found else not found.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can try with a object. check this:
function change_rank() {
var temp = {};
var rankbox= $('input[type=text][class = cate_rank]').map(function() {
if(temp[this.value]==undefined) {
temp[this.value] = this.value;
} else {
alert('the same value');
}
return this.value;
}).get();

jQuery if condition text contains

I wrote a simple if condition, but not quite working.
if text is 123 change to hi, if text is 456 change it to hi2
Could someone please give me a hand.
<h1>123</h1>
<h1>456</h1>
<h1>789</h1>​
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text();
if (text == changeText) {
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
​
http://jsfiddle.net/8P2ma/
There are multiple things wrong with your code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
var text = $(h1).text(); //aside from having to iterate through, the jquery
//selector needs to be enclosed in quotes: $('h1')
if (text == changeText) { //The variable 'changeText' does not exist.
$(this).text('hi');
} else if (text == changeText2 ) {
$(this).text('hi2');
}
});
//working code:
$(document).ready(function() {
var changeText1 = '123';
var changeText2 = '456';
$('h1').each(function() {
var text = $(this).text();
if (text == changeText1) {
$(this).text('hi');
} else if (text == changeText2) {
$(this).text('hi2');
}
});
});​
$(function() {
$('h1:contains("123")').text('hi');
$('h1:contains("456")').text('hi2');
});​
FIDDLE
Do it like this:
$(document).ready(function() {
var change = {
'123': 'hi',
'456': 'hi2'
};
$('h1').text(function(i, txt) {
return change[$.trim(txt)];
});
});
DEMO: http://jsfiddle.net/By4Ra/

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

remove onclick function and change to onload or document.ready

What would be the easiest way to remove the onclick event from this script?
The script below uses google translate to translate from one language to another.
I want to be able to set the language to a
Request.Form("language")
so when I submit a form it will set the language. (I can do this so it is not a problem, however once this language is set I want the script to automatically translate the text.
something like
<body onload="">
or
document.ready or
translate.ready
However I am not 100% sure how to do this:
<script type='text/javascript'>
google.load("language", "1");
var translator = false;
function init(){
var str = $("source").innerHTML;
var triggerCollection = $("langSelect").select("li");
triggerCollection.invoke("observe", "click", handleTriggerClick);
translator = new Translator("source", "p,ul");
translator.addEventListener("complete", function(obj){
//console.log("The translation has finished %o", obj);
{
document.form1.g_content_text.value = $("source").innerHTML;
}{
//document.form1.submit();
}
});
translator.addEventListener("begin", function(obj){
//console.log("Translation has begun! %o", obj);
});
//console.log(translator.textNodeCollection);
}
function handleTriggerClick(e){
var lang = e.element().getAttribute("lang"); // This is the language to translate to!
var str = $("source").innerHTML;
translator.translate(lang);
}
function insertToForeign(obj){
$("display").innerHTML = obj.translation;
}
google.setOnLoadCallback(init);
var Translator = Class.create(EventDispatcher, {
initialize : function(element, selector, config){
this.element = $(element);
this.preservedHTML = this.element.innerHTML;
this.config = Object.extend(this.getDefaultConfig(), config);
this.textNodeCollection = this.collectChildren(selector);
this.preservedParentHash = {};
this.placeHolderHash = {};
this.entityWasher = new Element("div");
this.textNodeCollection = this.textNodeCollection.findAll(this.purifyTextNode);
},
purifyTextNode : function(node){
try{
if(!node)
return false;
return node.nodeType == 3;
}
catch(e){
return false;
}
},
getDefaultConfig : function(){
return { maxLength : 1000, srcLang : "en", recursive : true, type : "text" };
},
collectChildren : function(selector){
return this.element.select(selector).collect(this.collectTextNodes.bind(this)).flatten();
},
collectTextNodes : function(element){
var self = this;
var stack = $A(element.childNodes).collect(function(child){
if(child.nodeType == 3 && child.nodeValue.length < self.config.maxLength && child.nodeValue.search(/^\s+$/g) == -1)
return child;
else if(child.nodeType == 3 && child.nodeValue.length > self.config.maxLength)
return self.splitTextNode(child);
else if(child.nodeType == 1 && self.config.recursive)
return self.collectTextNodes(child);
});
return stack;
},
splitStringByMax : function(text){
var offset = 0;
var textArr = [];
while(text.length > this.config.maxLength){
var tmp = text.substr(0, this.config.maxLength);
offset = tmp.lastIndexOf(" ");
var subText = text.substr(0, offset);
text = text.substr(offset);
textArr.push(subText);
}
textArr.push(text);
return textArr;
},
splitTextNode : function(node){
var nodeStack = [];
var textArr = this.splitStringByMax(node.nodeValue);
var prevNode = false;
textArr.each(function(text, itr){
var newNode = document.createTextNode(text);
nodeStack.push(newNode);
if(node.nextSibling != null && !prevNode)
node.parentNode.insertBefore(newNode, node.nextSibling);
else if(prevNode && prevNode.nextSibling != null)
node.parentNode.insertBefore(newNode, prevNode.nextSibling);
else
node.parentNode.appendChild(newNode);
prevNode = newNode;
});
node.parentNode.removeChild(node);
return nodeStack;
},
getEventBeginObject : function(destLang){
return {
destLang : destLang,
srcLang : this.config.srcLang,
srcLangNodes : this.textNodeCollection,
srcHTML : this.preservedHTML
}
},
getEventCompleteObject : function(result){
return {
srcLangNodes : this.textNodeCollection,
destLangNodes : this.translationStack,
destLangHTML : this.element.innerHTML,
srcLangHTML : this.preservedHTML,
result : result,
resultStack : this.resultStack
}
},
finishTranslation : function(result){
this.translating = false;
this.dispatchEvent("complete", this.getEventCompleteObject(result));
},
translate : function(destLang){
if(this.translating)
return false;
var self = this;
this.dispatchEvent("begin", this.getEventBeginObject(destLang));
this.textNodeCount = this.textNodeCollection.length;
this.translationStack = [];
this.resultStack = [];
this.textNodeCollection.each(function(node, index){
self.translating = true;
google.language.translate(node.nodeValue, self.config.srcLang, destLang, self.handleTranslation.bind(self, node, index));
});
return true;
},
getPreservedParent : function(node, index){
if(this.preservedParentHash[index])
return this.preservedParentHash[index];
return this.preservedParentHash[index] = node.parentNode;
},
getPlaceHolder : function(index){
return this.placeHolderHash[index] || false;
},
setPlaceHolder : function(node, index){
this.placeHolderHash[index] = node;
},
handleTranslation : function(node, index, obj){
try{
var parent = this.getPreservedParent(node, index);
this.entityWasher.innerHTML = obj.translation;
var translatedText = this.entityWasher.innerHTML;
if(node.nodeValue.search(/^\s/) > -1)
translatedText = " " + translatedText;
if(node.nodeValue.search(/\s$/) > -1)
translatedText = translatedText + " ";
var newText = document.createTextNode(translatedText);
if(this.getPlaceHolder(index))
parent.replaceChild(newText, this.getPlaceHolder(index));
else
parent.replaceChild(newText, node);
this.setPlaceHolder(newText, index);
this.translationStack.push(newText);
this.resultStack.push(obj);
this.textNodeCount--;
if(this.textNodeCount <= 0)
this.finishTranslation(obj);
}
catch(e){
console.log("Error has occured with handling translation error = %o arguments = %o", e, arguments);
}
}
});
</script>
if you click on the li it sets the language and start the function:
<ul id="langSelect">
<li lang="de">German</li></ul>
another solution might be to similate a user click on the li command, but I am also not sure how to do this!
Any help would be appreciated.
Any help would be appreciated
I think part of the problem lies here:
triggerCollection.invoke("observe", "click", handleTriggerClick);
It sounds like you are interested in the dom:loaded event.
document.observe("dom:loaded", function() {
translator.translate($('langselect').getAttribute('lang'));
});
Or if you know the language code you can feed it in directly. For the german example:
translator.translate('de');

special case of serializing form to a javascript object

building upon the $.fn.serializeObject() function from this question, i'd like to be able to support "dot notation" in my form names, like so:
<form>
<input name="Property.Items[0].Text" value="item 1" />
<input name="Property.Items[0].Value" value="1" />
<input name="Property.Items[1].Text" value="item 2" />
<input name="Property.Items[1].Value" value="2" />
</form>
given that $('form').serializeArray() produces the following:
[{"name":"Property.Items[0].Text","value":"item 1"},
{"name":"Property.Items[0].Value","value":"1"},
{"name":"Property.Items[1].Text","value":"item 2"},
{"name":"Property.Items[1].Value","value":"2"}]
how could i achieve the desired result below:
{Property: {Items: [{Text: 'item 1', Value: '1'},
{Text: 'item 2', Value: '2'}]} }
any help would be appreciated.
EDIT:
to be specific, the desired code would be added to the serializeObject extension so that in addition to the way it works now, it would also support the above convention. here's the existing method for convenience.
$.fn.serializeObject = 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;
};
EDIT 2:
feeding off the answer provided, here's my current implementation:
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
var regArray = /^([^\[\]]+)\[(\d+)\]$/;
$.each(a, function(i) {
var name = this.name;
var value = this.value;
// let's also allow for "dot notation" in the input names
var props = name.split('.');
var position = o;
while (props.length) {
var key = props.shift();
var matches;
if (matches = regArray.exec(key)) {
var p = matches[1];
var n = matches[2];
if (!position[p]) position[p] = [];
if (!position[p][n]) position[p][n] = {};
position = position[p][n];
} else {
if (!props.length) {
if (!position[key]) position[key] = value || '';
else if (position[key]) {
if (!position[key].push) position[key] = [position[key]];
position[key].push(value || '');
}
} else {
if (!position[key]) position[key] = {};
position = position[key];
}
}
}
});
return o;
};
you can see it in action here
This solution is a bit static. But it should do the trick:
var serialized = $.fn.serializeObject(),
properties = {},
property = [],
position = {},
key = '',
n = 0,
matchName = '',
i = 0;
for (i = 0; i < serialized.length; i += 1) {
property = serialized[i].name.split('.');
position = properties;
while (property.length) {
key = property.shift();
if (key.match(/\[\d+\]/) && key.match(/\[\d+\]/).join().match(/\d+/g) ) {
matchName = key.match(/\w+/)[0]
n = parseInt(key.match(/\[\d+\]/).join().match(/\d+/g), 10);
if (!position[matchName]) {
position[matchName] = [];
}
if (!position[matchName][n]) {
position[matchName][n] = {}
}
position = position[matchName][n]
} else {
if (!property.length) {
position[key] = serialized[i].value
} else {
if (!position[key]) {
position[key] = {};
}
position = position[key]
}
}
}
}
console.log(properties);

Categories

Resources