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 ..
}
Related
I decided to build a high/low game in javascript and am running into an issue where the numbers displayed are ahead of what the variables have stored or the exact opposite. I can't seem to get them to match.
EDIT: I figured it out, the code ran before ajax was done causing an offset.
It helps me more when I find answers with the old code to compare with the new so I'll leave the broken code. Updated with working code at the end.
Page that helped me figure out a fix:
Wait for AJAX before continuing through separate function
Original JavaScript:
var y = "0";
var z = "0";
var output_div = document.getElementById("outcome");
var last_ = document.getElementById("val");
var cardVal;
function higher(x) {
var new_ = last_.innerHTML; //getting new value
y = last_.getAttribute("data-old"); //getting old value
console.log("data_old " + y);
z = ajx(); //calling function return the value from which need to compare
console.log("data_new " + z);
if (x === 1) {
if (z > y) {
output_div.innerHTML = "Winner!";
} else {
output_div.innerHTML = "Loser!";
}
} else {
if (z < y) {
output_div.innerHTML = "Winner!";
} else {
output_div.innerHTML = "Loser!";
}
}
last_.setAttribute("data-old", new_); //setting old value with current value of div
}
function ajx() {
$.ajax({
url: "./getfacecard.php",
success: function(response) {
var result = $.parseJSON(response);
var img = result[0];
cardVal = result[1];
document.getElementById(\'card\').src = img;
document.getElementById(\'val\').innerHTML = cardVal;
}
});
return cardVal; // return current card value in calling function
}
Updated Working JavaScript:
var lastVal = document.getElementById("lastVal"); //Last played cars value
var wl = document.getElementById("outcome"); //Shows win or lose
var newVal = document.getElementById("currentVal"); //Current face up card
var iSrc = document.getElementById("card"); //Card img
var lVal; //Last cards value from post
var iLink; //Image link from post
var nVal; //Gets new html to be sent to post.
function start(x){
// console.log("Start:");
ajx(function(){ //Runs ajax before continuing
iSrc.src = iLink; //Set new card image src
newVal.innerHTML = nVal; //Sets Current card value in div
lastVal.innerHTML = lVal; //Sets Last card value in div
// console.log("-slgn"); //Consoles to track code launch order.
// console.log("-Last Value: "+lVal);
// console.log("-Current Value: "+nVal);
// console.log("-Link: "+iLink);
// console.log(x);
if(x===1){ //If clicked higher
if(nVal>lVal){ //If new card is higher than old card
wl.innerHTML = "Winner!";
}else{
wl.innerHTML = "Loser!"
}
}
if(x===2){
if(nVal<lVal){ //If new card is lower than old card
wl.innerHTML = "Winner!";
}else{
wl.innerHTML = "Loser!"
}
}
});
}
function ajx(callback) {
$.ajax({
type: "POST",
data: {data:newVal.innerHTML}, //Post new card value to be returned as last card.
url: "./getfacecard.php",
success: function(response) {
var result = $.parseJSON(response);
iLink = result[0]; //img
lVal = result[2]; //Last card
nVal = result[1]; //New Card
// console.log("ajax");
callback(); //Go back and the code
}
});
}
You can use custom attribute in your div to save your current value as old value and vice versa so only one div required here i.e: Your div look like below :
<div data-old="0" id="val">0</div>
And js code will look like below:
var y = "0";
var z = "0";
var output_div = document.getElementById("outcome");
var last_ = document.getElementById("val");
function higher(x) {
var new_ = last_.innerHTML; //getting new value
y = last_.getAttribute("data-old"); //getting old value
console.log("data_old " + y);
z = ajx(); //calling function return the value from which need to compare
console.log("data_new " + z);
if (x === 1) {
if (z > y) {
output_div.innerHTML = "Winner!";
} else {
output_div.innerHTML = "Loser!";
}
} else {
if (z < y) {
output_div.innerHTML = "Winner!";
} else {
output_div.innerHTML = "Loser!";
}
}
last_.setAttribute("data-old", new_); //setting old value with current value of div
}
function ajx() {
$.ajax({
url: "./getfacecard.php",
success: function(response) {
var result = $.parseJSON(response);
var img = result[0];
var cardVal = result[1];
document.getElementById('card').src = img;
document.getElementById('val').innerHTML = cardVal;
}
});
return cardVal; // return current card value in calling function
}
In above js code what i done is after ajax call finishes execution it will return cardVal which will get pass in variable z and then we will compare it with y i.e : old value and print required output.Also, i have return value from ajax called because when you do document.getElementById(\'val\').innerHTML = cardVal; still this value is not available with us in our function higher so to overcome this i have return that value to your calling function.
(This code is already tested and working as excepted )
I'm running an A/B test to see if showing more items is better for conversion. But it seems that the code sometimes causes errors.. But I can't find any errors and don't know when they occur.
In my test I check whether the url param IC exists and if it doesn't exists I will add this.
This is my code:
function checkIfAlreadyPaginated()
{
var field = 'IC';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1)
return true;
else if(url.indexOf('&' + field + '=') != -1)
return true;
return false;
}
function insertParam(key, value) {
key = encodeURIComponent (key); value = encodeURIComponent (value);
var kvp = document.location.search.substr(1).split('&');
if (kvp == '') {
return '?' + key + '=' + value;
}
else {
var i = kvp.length; var x; while (i--) {
x = kvp[i].split('=');
if (x[0] == key) {
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
return '?'+kvp.join('&');
}
}
var itemsPerPage = 48;
if(!checkIfAlreadyPaginated())
{
document.location.search = insertParam('IC', itemsPerPage);
}
Does someone spot possible issues? I'm running the test via VWO.com.
If there is a Javascript error you should see it in the browser console and share it with us.
In any case, I would do it by creating a JS Object first. I find it easier to work with.
In the following code I added the option to do the checking for multiple params of the querystring. If you only need to check the IC you can simplify it a bit. I tested it on a blank test.html.
<script type="text/javascript">
// get the current params of the querystring
var querystringItems = document.location.search.substr(1).split('&');
// create an object
var querystringObject = {};
for(i=0;i<querystringItems.length;++i) {
param = querystringItems[i].split('=');
querystringObject[param[0]] = param[1];
}
// Define the keys to be searched for and their default value when they are not present
var requiredKeys = {"IC":48, "test": "me"};
// Do the checking on the querystringObject for each requiredKeys
var doreload = false;
for (var key in requiredKeys) {
if (typeof querystringObject[key] == 'undefined') {
doreload = true;
// Create the missing parameter and assign the default value
querystringObject[key] = requiredKeys[key];
}
}
// If any of the requiredKeys was missing ...
if (doreload) {
// rebuild the querystring
var querystring = '?';
for (var key in querystringObject) {
querystring+=key+'='+querystringObject[key]+'&';
}
querystring=querystring.substr(0,querystring.length-1);
// reload page
document.location.search = querystring;
}
// assign the values to javascript variables (assuming you had it like this because you needed it)
var itemsPerPage = querystringObject.IC;
</script>
Here is an example to check this:
//get URL params into string:
paramStr = window.location.substring(window.location.indexOf('?'), window.location.length;
//turn string into array
paramArray = paramStr.split('&');
//prepare final array of params
params = {};
//prepare the index of IC parameter
icLoc = -1; //this is negative 1 so that you know if it was found or not
//for each item in array
for(var i in paramArray){
//push its name and value to the final array
params.push(paramArray[i].split('='));
//if the parameter name is IC, output its location in array
if(params[i][0] === 'IC'){
icLoc = i;
}
}
If IC is not found, icLoc will be -1.
If it is found, the value of IC in the URL parameters is params[icLoc][1]
Example result for query string ?foo=bar&code=cool&IC=HelloWorld:
params = {'foo': 'bar', 'code': 'cool', 'IC': 'HelloWorld'}
icLoc = 2
Example for query string ?foo=bar&code=cool:
params = {'foo': 'bar', 'code': 'cool'}
icLoc = -1
Here id is the param I'm using for a test. Pass the argument which you want to check whether it exists or not.
function queryParamExistUrl(param = '') {
if (new URLSearchParams(window.location.search).get(param) != null)
return true
return false
}
console.log(queryParamExistUrl('id'))
I am trying to collect the unique json data, I mean if the key exists the update its value. But not succeed to update the value of existing key.
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},
{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},
{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"},
{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
if( coll[data.raw_id] == data.raw_id ) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
});
console.log(coll);
In fpr_data there is raw_id that i want to collect unique ids and if the raw_id found in object then update its qty and wastage with raw_qty and raw_wastage. I got Unique JSON data but quantity and wastage are not getting update. What wrong i have done? You can find the same codes in fiddle and check the result in console.
Expected: The value of qty in 3 should be 80
JSFIDDLE
Below condition will not give you correct comparison, when object already exists in array.
if( coll[data.raw_id] == data.raw_id ) {
I think you should just do:
if(coll[data.raw_id]) {
If I understand you correctly try this example
if(coll[data.raw_id]) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
You use jQuery, so enjoy the jQuery.extend() function :
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"}, {"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
console.log(fpr_data);
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
var currentObj = coll[data.raw_id]; // Try not to repeat yourself ;-)
if( currentObj == data.raw_id ) {
var q = currentObj.qty + _qty;
var w = currentObj.wastage + _wastage;
console.log(data);
coll[data.raw_id] = $.extend(data, {"qty":q, "wastage":w});
}
else {
coll[data.raw_id] = $.extend(data, {"qty":_qty, "wastage":_wastage});
}
});
console.log(coll);
I hope this is what you were looking for.
I want to get this (four keys & values in one object):
[{"sms":"Y","email":"Y","phone":"Y","oto":"Y"},{"sms":"N","email":"N","phone":"N","oto":"N"}]
but this is result :
[{"sms":"Y"},{"email":"Y"},{"phone":"Y"},{"oto":"Y"},{"sms":"N"},{"email":"N"},{"phone":"N"},{"oto":"N"}]
here is my code:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk = 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
Can you please show us the form as well? This gives a limited scope to answer.
But If i guess right, you have a form wherein you have the following fields sms, email, phone, and then oto, right?
So what you have to do is, instead of doing it for each input, you have to do it once for the four inputs.
Meaning that you have to set chkObj['sms'], chkObj['email'], chkObj['phone'], and then chkObj['oto'] and then do chkArray.push(chkObj).
You missed the second equals sign in this expression:
if(cntchk = 4){, so instead of comparison there is an assignment. Change this to if(cntchk == 4){
You have missed one "=" sign in if condition.
try this:
var chkObj = {};
var chkArray = [];
var cntchk = 1;
$("tbody input").each(function(idx){
var Nm = $(this).attr("name");
this.checked ? chkObj[Nm] = 'Y' : chkObj[Nm] = 'N';
cntchk++;
if(cntchk **==** 4){
chkArray.push(chkObj);
chkObj = {};
cntchk = 1;
}
});
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);