Beginner: Extracting multiple variables when prompted - javascript

I have the following code:
What I want to do is when I enter my prompt, I want to able to enter multiple variables and receive their outputs. How exactly do I go about doing that.
For example, when I enter lh0, lh1 and lh3, I expect to get back 000110100110010111101
var outputRef = document.getElementById('outputArea');
var output = " ";
var areas = prompt("Enter no : ");
var areas1 = {
lh0 : "0001101",
lh1 : "0011001",
lh2 : "0010011",
lh3 : "0111101",
lh4 : "0100011",
lh5 : "0110001",
lh6 : "0101111",
lh7 : "0111011",
lh8 : "0110111",
lh9 : "0001011"
};
if (areas1 [ areas ] !== undefined)
{
areas = areas1[areas];
}
output = areas;
outputRef.innerHTML = output;
Thanks!

You can use Array#split to split the string entered by the user, e.g. lh0, lh1, lh2, then find the corresponding key in the areas1 object and add it's value to the output string. Finally, display it in the DOM.
var outputRef = document.getElementById('outputArea');
var output = "";
var areas = prompt("Enter no : ");
var areas1 = {
lh0: "0001101",
lh1: "0011001",
lh2: "0010011",
lh3: "0111101",
lh4: "0100011",
lh5: "0110001",
lh6: "0101111",
lh7: "0111011",
lh8: "0110111",
lh9: "0001011"
};
areas.split(',').forEach(function(v){
output += areas1[v.replace(' ', '')];
});
outputRef.innerHTML = output;
<p id="outputArea"></p>

try this:
var outputRef = document.getElementById('outputArea');
var output = " ";
var areas = prompt("Enter no : ");
var areas1 = {
lh0 : "0001101",
lh1 : "0011001",
lh2 : "0010011",
lh3 : "0111101",
lh4 : "0100011",
lh5 : "0110001",
lh6 : "0101111",
lh7 : "0111011",
lh8 : "0110111",
lh9 : "0001011"
};
var results = [];
if (areas)
{
areas.split(',').forEach(function(val) {
results.push(areas1[val]);
});
}
outputRef.innerHTML = results.join("");
<div id="outputArea">
</div>

Related

How to pass a JavaScript variable to XML?

I want to pass JavaScript variable's value to an XML file. I have already seen this question and answer here but since my XML file is not that small but rather big, I would like to know how to do this without writing whole xml if possible.
I have this JavaScript code
render_receipt: function () {
// this._super();
var self = this;
if (self.pos.config.disable_fiscalization == false) {
var data = self.get_receipt_render_env();
self.$('.pos-receipt-container').html("")
var total_amount = data['receipt']['total_with_tax'];
var vat = self.pos['company']['vat'];
var header_time = data['order']['formatted_validation_date'];
var order_name = data['order']['name'];
var soft_code = self.pos['company']['software_code'];
var business_unit_code = self.pos['config']['business_unit_code'];
var business_unit_address = self.pos.business_unit_address
var tcr_code = self.pos['config']['tcr_code'];
var operator_code = self.pos.get_cashier().operator_code
// create message
message = vat + '|' + header_time + '|' + order_name + '|' + business_unit_code + '|' + tcr_code + '|' + soft_code + '|' + total_amount
var order = self.pos.get_order();
if (!this.pos.config.iface_print_via_proxy) {
var invoiced = new $.Deferred();
// if (self.pos.config.disable_fiscalization == false) {
// console.log("hasEnoughSpeed", hasEnoughSpeed, isAlive)
if (isAlive && hasEnoughSpeed) {
rpc.query({
model: 'pos.order',
method: 'search_read',
domain: [['pos_reference', '=', order['name']]],
fields: ['iic_code', 'header_send_datetime', 'amount_total', 'fic', 'business_unit_code', 'operator_code', 'fiscalization_url', 'partner_id']
})
.then(function (orders) {
var partner = null;
if (orders.length && orders[0]['partner_id'] == false) {
var data = self.get_receipt_render_env();
data['partner_name'] = orders[0]['partner_id'][1];
data['street'] = false;
data['country'] = false;
data['city'] = false;
data['zip'] = false;
data['vat'] = false;
data['nslf'] = orders[0]['iic_code'];
// alert(data['nslf'])
data['nivf'] = orders[0]['fic'];
data['business_unit_code'] = business_unit_code;
data['operator_code'] = operator_code;
data['business_unit_address'] = business_unit_address
self.$('.pos-receipt-container').html(qweb.render('PosTicket', data));
var qr = new QRious({
element: document.getElementById('qr-code'),
size: 200,
});
I'd like to pass data['nsfl'] to this XML div tag. I have already tried as you see and it is failing, I get why it is failing and from the other side I don't know how to make work either. Thanks in advance guys!!!
<div>
<div style="font-weight:bold;font-size:12px;">NSLF: <t t-esc="data['nslf']"/></div>
</div>

Accessing an object not working with a variable

This seems simple but I'm banging against a wall. My code gets weights, accesses an object array to get a value then calculates a result using that value * weight. But accessing the object doesn't work with a variable.
function calc(){
var gender;
if(document.getElementById("male").checked){
gender = "mensList";
} else if (document.getElementById("female").checked){
gender = "womensList";
} else {
alert("Please select a gender");
return false;
}
var kg = parseInt(document.getElementById("bwKg").value);
var grams = parseFloat(document.getElementById("bwGrams").value);
var bw = parseFloat(kg + grams);
var lifted = parseFloat(document.getElementById("liftWeight").value);
var theValue = womensList[bw]; // This works
var theValue = mensList[bw]; // This also works
var theValue = gender[bw]; // This doesn't work
var theValue = gender + "[\"" + bw + "\"]" // Nor this
var result = theValue * lifted;
document.getElementById("result").textContent = result;
}
var womensList = {
40.0: "1.4936",
40.1: "1.4915",
40.2: "1.4894",
40.3: "1.4872",
40.4: "1.4851",
// ......... etc
150.7: "0.7691",
150.8: "0.7691",
150.9: "0.7691"
};
var mensList = {
40.0: "1.3354",
40.1: "1.3311",
40.2: "1.3268",
40.3: "1.3225",
40.9: "1.2975",
// ......... etc
205.7: "0.5318",
205.8: "0.5318",
205.9: "0.5318"
};
In your code you are setting a gender to string not variable.
if(document.getElementById("male").checked){
gender = "mensList";
} else if (document.getElementById("female").checked){
gender = "womensList";
}
Should be
if(document.getElementById("male").checked){
gender = mensList;
} else if (document.getElementById("female").checked){
gender = womensList;
}
Here is your problem :
if(document.getElementById("male").checked){
gender = "mensList"; //gender now contains a string only..
} else if
Since gender contains a mere string, this will not work:
var theValue = gender[bw]; // This doesn't work
What you should be doing instead is :
if(document.getElementById("male").checked){
gender = mensList; //now gender contains an array provided mensList is defined beforehand ..
}

To function to string, search and replace function, execute function

I am trying to do something crazy, I have a JSON object of all sorts of rules for my website. I have a system set up where I can write pseudo code and then it turns it into actual code. I have this working perfectly for strings, however now I need to be able to pass functions, and replace the pseudo code inside of functions, then execute the functions.
I think I am on the right track, however when I turn a function to a string it only turns the output of the functions into a string.
Here's my JSON (part of it)
customValidation: {
//compare: "(<!this!> && <!PrimeTimeDiscount!> == 200) || (<!PrimeTimeDiscount!> == 100)",
compare: function(){
return new Validator()["date"]("<!this!>", 50);
},
overrideDefault: true
}
The commented out "compare" is how I use this system for regular strings.
And below is how I handle turning "<!this!>" and "<!*!>" into values from the JSON object. It is basically the same code twice, but the one below I have started modifying for when a function is detected.
if(typeof customValidationRule != "function")
{
var string = customValidationRule.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRule;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
}
else
{
var customValidationRuleString = customValidationRule().toString();
var string = customValidationRuleString.match(/<!(.*?)!>/g);
var customValidationTerms = new Array();
var execCustomValidationRule = customValidationRuleString;
$.each(string, function(i, v){
var customValidationTerm = v.replace(/<!/g, "").replace(/!>/g, "");
customValidationTerms.push(customValidationTerm);
});
$.each(customValidationTerms, function(i, v){
var RegEx = new RegExp("<!"+v+"!>", "ig");
if(v == "this")
{
var newData = value ? value : "''";
}
else
{
var newData = FormData[parentKey][TermNames[v]] ? FormData[parentKey][TermNames[v]] : "''";
}
newData = dataType == "currency" ? cleanVar(cleanCurrency(newData)) : newData;
newData = newData ? newData : "''";
execCustomValidationRule = execCustomValidationRule.replace(RegEx, newData);
});
var backToFunction = eval('(' + execCustomValidationRule + ')');
//validation = customValidationRule();
}
validation = eval(execCustomValidationRule);

Convert text items to JSON

I have a text that includes mani list items on the next format:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>..."
I'm trying to create JSON on the next format:
{
name: "M3-2200",
Model: "M3-2200"
}
I'm trying using next code, but it doesn't work my problem is on push. anybody can explain me how do it right?
result ={};
while(text.indexOf("<li>")!== -1){
var listi = text.substring(text.indexOf("<li>"), text.indexOf("</li>"));
var model = listi.substring(0, listi.indexOf("(") -1);
var name = listi.substring(listi.indexOf("("), listi.indexOf(")"));
var item = {name: name: model : model};
result.push(item);
var text = text.substring(text.indexOf("</li>"));
}
Other solution for your problem:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var result = JSON.parse('[' +
text.replace(/(<li>|<\/li>| \(|\))/g, function(_, part){
switch (part) {
case '<li>': return '{"name":"';
case '</li>': return '},';
case ' (': return '", "Model":"';
case ')': return '"';
}
}) + '0]').slice(0, -1);
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
JSONStr = text.trim().replace(/<li>/g,"{\"name\":\"").replace(/ \(/g,"\" , \"model\":\"").replace(/\)\<\/li\>/g,"\"},");
JSONStr = "["+JSONStr.substring(0,JSONStr.length-1)+"]";
console.log(JSONStr);
Will the above code work?
I hope I understand your question correctly. If this is the output you want:
[{"name":"M3-2200 ","model":"da2/M3-2200"},{"name":"N3-2200 ","model":"da2/N3-2200"},{"name":"Picasso ","model":"picasso/A500"},{"name":"Picasso ","model":"picasso/A501"},{"name":"Picasso ","model":"ventana/A500"}]
Then this is a way to do it:
var text = "<li>M3-2200 (da2/M3-2200)</li><li>N3-2200 (da2/N3-2200)</li><li>Picasso (picasso/A500)</li><li>Picasso (picasso/A501)</li><li>Picasso (ventana/A500)</li>";
var extractItem = function (item) {
var partsArray = /(.+) ?\((.+)\)\<\/li>/.exec(item)
if(partsArray) return {"name":partsArray[1], "model":partsArray[2]}
}
var result = text.split('<li>')
.map(extractItem)
.filter(function(e){return e != undefined});
console.log(JSON.stringify(result));

javascript regex, split user's full name

I have user's firstname and lastname in one string, with space between
e.g.
John Doe
Peter Smithon
And now I want convert this string to two string - firstname and lastname
John Doe -> first = John, last = Doe
John -> first = John, last = ""
[space]Doe -> first = "", last = Doe.
I am using next code
var fullname = "john Doe"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe
and this works well for two-word fullname. But if fullname has one word, then I have problem
var fullname = "john"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john
http://jsfiddle.net/YyCKx/
any ideas?
Use split + shift methods.
var parts = "Thomas Mann".split(" "),
first = parts.shift(),
last = parts.shift() || "";
So in case of single word name it will give you expected result:
last = "";
Use this code:
You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;}}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
You can use split method
var string = "ad";
var arr = string.split(" ");
var last = arr[0];
var first = arr[1];
if(first == null){
first = "";
}
alert(last + "\n" + first)​;​
If in every situation you have just "first last" you could use:
var string = "john "
var i = string.split(" ");
alert("first: "+i[0]+ "\n"+ "last: " + i[1]);
I know that this has already been replied to and marked as answered but i just want to note that if you do still want to use regex you can change the "last" expression:
var last = string.replace(/^[a-zA-Z]*/, "").toUpperCase().trim();
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#LastName').val(lastname);
});
});
var str='John';
var str2='Peter Smithon';
var str3='Peter';
var words=str.split(/\s+/g,2);
var first=words[0];
var last=words[1]||'';
alert(first+' '+last);

Categories