call another function in a main function of javascript - javascript

<script>
function checkName(){
var tmpName = document.getElementById("name");
if( tmpName.value.length == 0 ){
alert( "Name cannot be empty" );
return false;
}
else
return true;
}
function confirmForm( formObj ){
var nameBool = new Boolean();
var errorName = "";
nameBool = checkName();
if( nameBool == false )
errorName = "Invalid data in input name !";
return window.alert( "You have this error : \n " + errorName + "\n" + errorID );
}
</script>
<form name=reviewform onsubmit="return confirmForm(reviewForm)" method=POST >
<p>Name : <input type="text" id="name" ></p>
<p>ID : <input type="text" id="id" ></p>
<input type="submit" value="Click here!">
</form>
my problem is why my function cannot run ??? isn't something wrong? can any senior teach me where the place i wrong at??
i already editited and plus that form name and the function how it's work
i don't know isn't my implementation wrong or what

Both functions, though they need some work, and you clearly need to brush up on your JS knowledge, can run, you just have to call them. As it stands, you've just defined 2 functions. Nothing else.
Other issues, line/line:
//second line:
var tmpName = document.getElementById("name");
Here, you can't be sure this element is already leaded, perhaps the DOM isn't ready yet, so be careful, just wrap your entire code in a handler:
window.onload = function()
{
//your code here, this gets executed after the page is fully loaded
};
Next, don't think of JS as some sort of Java-for-browsers, it's a completely different animal. Stuff like:
var nameBool = new Boolean();
var errorName = "";
Is best written as declaring variables, but not assigning anything:
var nameBool, errorName;
If you want to be sure the nameBool is a boolean, just assign like so:
nameBool = !!checkName();//double bang
It also looks like you're trying to validate a form or handle a submit event of sorts. Why not use addEventListener for that? or, if you insist:
document.getElementById('formId').onsubmit = function(e)
{
//get event object:
e = e || window.event;
//this references form, as does (e.target || e.srcElement), you can access the elements it contains, and check them one by one
};

Related

Calculation on vTiger field before save handler on Javascript Side (code inside)

I need to understand how to do real time calculation on Edit.js
By searching and looking around i came up with this code in Edit.js of the Contact Module.
calculate_amount: function (){
var units = $("input[name='cf_852']");
var value = $("input[name='cf_854']");
$(units, value).on('keyup', function(){
if (units.val() != '' && value.val() != ''){
var currentamount = units.val() * value.val();
$("input[name='cf_856']").val(currentamount);
}
});
}
Have i done something wrong? Because it doesn't work..
Thanks for all the help!
I should write your keyup function like this:
I tested, it's OK
calculateAmount: function (){
var units = $("input[name='cf_1512']");
var value = $("input[name='cf_1514']");
$(document).on('keyup',"input[name='cf_1512'], input[name='cf_1514']", function(){
if (units.val() != '' && value.val() != ''){
var currentamount = units.val() * value.val();
$("input[name='cf_1518']").val(currentamount);
}
})
},
You must call you function into the function registerBasicEvents.
If the registerBasicEvents function is not available in Edit.js of Contacts module so add it.
registerBasicEvents: function (container) {
this._super(container);
this.calculate_amount();
}
You should pass id's of element instead reference of element for Keyup function. Please find below code snippet and modify your code in vTiger. As I checked all syntax and function written correctly in your script. Just pass the comma separated id's and execute the code. Thanks!
var units = $('#Contacts_editView_fieldName_cf_1512');
var value = $('#Contacts_editView_fieldName_cf_1514');
$('#Contacts_editView_fieldName_cf_1512, #Contacts_editView_fieldName_cf_1514').on('keyup', function(){
if (units.val() != '' && value.val() != ''){
var currentamount = parseFloat(units.val()) * parseFloat(value.val());
$("#Contacts_editView_fieldName_cf_1516").val(currentamount);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Input1: <input type="text" id="Contacts_editView_fieldName_cf_1512"/><br/>
Input2: <input type="text" id="Contacts_editView_fieldName_cf_1514" /><br/>
Result: <input type="text" id="Contacts_editView_fieldName_cf_1516"/>

A function that is not a function?

I'm still new to coding and I'm trying to make a cookie clicker type game. I get
upgradecursor is not a function
when I run it on Chrome. I don't really understand the problem as I have a function called upgradecursor.
Pls help! :(
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<script>
//List of variables
var cookie = 0;
var cursor = 1;
var cursorupgradecost = 10;
function addcookie(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie + cursor;
// Add one
currentValue = currentValue + cursor;
// Put it back with the new +1'd value
textField.value = currentValue;}
function upgradecursor(){
var textField = document.getElementById( "textField" );
var currentValue = parseInt(textField.value);
cookie = cookie - cursorupgradecost;
// Minus one
currentValue = currentValue - cursorupgradecost;
// Put it back with the new -10'd value
textField.value = currentValue;
//change the cost of the upgrade
cursorupgradecost = cursorupgradecost * 1.5;
//Upgrade the cursor
cursor = cursor + 1;
}
</script>
</head>
<body>
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
<button type ="button" onClick = "upgradecursor()"/>Upgrade Cursor </button>
<input type="text" value="0" disabled name="lvl">
<br>
<button type="button" onClick="addcookie()"/>Add Cookie</button>
<input type="button" value="Cookies" disabled name="clicker">
<input type="text" value="0" id="textField" readonly/>
</body>
</html>
You are overwriting upgradecursor with a global variable after you include the JavaScript.
<script>
if (cursorupgradecost > cookie) {
upgradecursor = false;
} else {
upgradecursor = true;
}
</script>
This is the offending code. You need to rename this variable to something else to avoid overwriting the function.
Additionally, you should definitely avoid declaring global variables like this and look at making your code more encapsulated/modular.
--
Update based on your objective: If you want to only upgrade the cursor given a certain use case, then it might be useful to have a specific click handler that will run this check inside itself before calling upgradecursor. For example: -
function onCursorClick() {
if (cursorCost > cookie) {
// do something
} else {
upgradeCursor();
}
}
Notice how I have used camel casing to declare my functions and variables? Make sure you update your variable declarations to match my casing. This is common practice. You can read more on coding conventions here: W3Schools JavaScript Style Guide
I'd like to point out listeners should be attached via JavaScript (see DOM Event Listeners), but make sure you update the click handler to match our update, like so: -
<button type="button" onClick="onCursorClick()"/>Upgrade Cursor</button>
You have this:
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
So while you started out by defining upgradecursor as a function, you overwrote it with a boolean before you ever called it.
The problem is here:
<script>
if (cursorupgradecost > cookie){
upgradecursor = false;}
else{
upgradecursor = true;}
</script>
What on earth is that supposed to even do?
Remove it and it should work.

HTML button not functioning

I am working on a project in JavaScript, which prints out some names pulled from an XML file. I also have 3 textboxes and an update button so that if anyone types in a name in any of the textboxes, they will see the updated names when they hit the button. For example, if I originally have:
George
Mary
John
If the user types in Jane, it should change the output to:
Jane
Mary
John
However, the update button doesn't do anything when it is clicked on. Here is the code for my 3 textboxes and the button:
<div id = "Names">
<input type = "text" id = "nameOne" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "text" id="nameTwo" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type ="text" id = "nameThree" value = "Enter a name" onClick = "if(this.value == value){this.value = '';}" />
<input type = "button" id = "btnUpdate" value = "Update Names" onClick = "printNames()" /></div>
And here are the functions I am using:
function getXML(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","Names.xml",false);
xmlhttp.send();
return(xmlhttp.responseXML);
}
function printNames() {
var xml = getXML();
var txt = "";
$(xml).find("person").each(function () {
txt += "<div>" + $(this).text() + "</div>";
});
$("body").append(txt);
insertNames(name1, name2, name3);
}
function insertNames(name1, name2, name3) {
var xmlRequest = getXML();
var nameOneTxt = document.getElementById('nameOne').value;
var nameTwoTxt = document.getElementById('nameTwo').value;
var nameThreeTxt = document.getElementById('nameThree').value;
if (nameOneTxt != null || nameTwoTxt != null || nameThreeTxt != null) {
var x = xmlRequest.getElementsByTagName("person")[0].childNodes[0];
x.nodeValue = nameOneTxt;
var y = xmlRequest.getElementsByTagName("person")[0].childNodes[1];
y.nodeValue = nameTwoTxt;
var z = xmlRequest.getElementsByTagName("person")[0].childNodes[2];
z.nodeValue = nameThreeTxt;
}
printNames();
}
printNames();
</script>
The printNames() function reads the names from an XML file and outputs those names using jQuery. It then calls the insertNames() function which takes in 3 parameters (for the three textboxes I have.)
The insertNames function opens an XML connection, and then gets the values for each textbox. If the textbox is not null, then that means the user input a value, in which case, a call to the XML tag is made and updates the existing content to the user input. It then calls the printNames() function which outputs the new contents.
When I test this, I get the original names output, but the update button doesn't do anything. I tried adding a print statement to the insertNames function to find that the function never runs. What am I missing? Any help would be appreciated. Thanks.
I think it is when the function is being loaded. Check this
Fiddle.
I have reduced your printNames call to this
function printNames(){
alert(1);
}
If you leave it to run at default onLoad it doesn't work. If you change the load time to No wrap -in Body it works fine.
Haven't seen your code, but check where you are loading the function in relation to the onclick. The manual printNames() call at the bottom of the script will work whereas the onclick printNames() call will not.

i have code that can be use for subtract the textbox values using javascript?

i have code that can be use for subtract and additional textbox values using javascript and it is working but problem is that javascript again and again executed function whenever onfocus textbox i want only one time javascript should be executed function?
javascript function again and again additional onMouseOver="return B(0);"
javascript function again and again subtraction onfocus="return C();"
javascript function again and again additional onfocus="return D();"
function getObj(objID){
return document.getElementById(objID);
}
function B(){
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
}
function C() {
getObj("balance").value=parseFloat(getObj("total").value || 0)-
(parseFloat(getObj("advance").value || 0)) ;
getObj("balance").value=parseFloat(getObj("balance").value || 0)-
(parseFloat(getObj("discount").value)||0) ;
return false;
}
function D() {
getObj("total").value=parseFloat(getObj("total").value || 0)+
(parseFloat(getObj("openbal").value || 0)) ;
return false;
}
Opening Balance:<input class="input_field2"
type="text" name="openbal" id="openbal"><br />
Total:<input class="input_field2" type="text"
readonly name="total" id="total" value="5000"><br />
Advance:<input class="input_field2" type="text"
readonly name="advance" id="advance" value="500"
onMouseOver="return B(0);"><br />
Balance:<input class="input_field2" readonly type="text"
name="balance" id="balance" onfocus="return C();"><br />
Rem Amount:<input class="input_field2" type="text"
name="recamt" id="recamt"><br />
Discount: <input class="input_field2"
style="background-color:#FFF !important;"
type="text" name="discount" id="discount" >
You could have:
var executedAlready = false;
An inside functions B and C have:
if(executedAlready != true){ executedAlready = true; }
else { return; }
Or maybe you could detach the events instead? I guess there are a few different ways to do this.
What the other answers tell you that the "quickest" way to get results is to make your functions only execute once.
You can do that like this:
Make a flag (just a variable that knows if your function has been triggered already).
When executing your functions, first check on this flag.
Here's an example how to do it with function B():
(Note: I didn't change your function, don't wanna get into that now)
// setup fired as false
var hasBFired = false;
function B(){
// if B is true, we do nothing
if (hasBFired) {
return;
// else if it is not true, basically only the first time you call this, flip the flag and execute the rest of the code.
} else {
hasBFired = true;
}
var advanceBox = document.getElementById('advance');
var originalValue = advanceBox.value;
advanceBox.onfocus = function() {
this.value = parseFloat(originalValue, 10) +
parseFloat(document.getElementById('recamt').value, 10);
return false;
};
Now, repeat the same with C and D functions (setup two more flags).
This is not the best way - it's not good to setup global objects and stuff, but since you probably aren't getting any side library in, it will help you solve your issue for now. For long term solution, you should use an Event library (like YUI Event) and have it handle attaching and detaching actions to onfocus events for you.
you can use one or more flag(s) :
in the begenning of the page :
<script>
var flag = false;
</script>
and on your element:
<div .... onMouseOver="if(!flag) { flag = true; return B(0);}" > .... </div>
same for onFocus...

How to validate form fields with javascript objects?

I am trying to do some simple form validation using javascript object values. I know it's not "ideal", but I'm just working with a simple form that doesn't need to be iron-clad.
Please see my fiddle example: http://jsfiddle.net/6dXd7/3/
I am trying to make sure that each form field has a value. If so, set the value for myObj.fieldID to yes.
Then, when the form is submitted, check every existing myObj.XXX and be sure all their values are yes.
In my example, I am having trouble creating the object, and I don't know how to cycle through all the objects when the submit button is pressed without specifying each one by name.
Here's the code in the jsfiddle example linked to above:
<script>
$(document).ready(function () {
var myObj = {};
$("input.checkblank").blur(function () {
var inputID = $(this).attr("id");
var contents = $("input#" + inputID).val();
if (contents == "") {
$(myObj).data(inputID, "no");
} else {
$(myObj).data(inputID, "yes");
}
});
$("#verify").click(function () {
if (myObj.first && myObj.second == "yes") {
// ***** Trying to get it to scan through ALL existing myObj's and make sure all their values are "yes" *****
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
});
</script>
<input type="text" name="first" id="first" class="checkblank"><br />
<input type="text" name="second" id="second" class="checkblank">
check<br />
<p class="results"> </p>
​
​
You were storing field info in jQuery DATA and trying to check them later not in the same place...
var obj = {}
$(obj).data('a','1');
console.log(obj.a); //this will log null, cause there's no attribute 'a' in 'obj'
console.log($(obj).data('a')); //this will log '1' :]
instead do this, you should store you data in attributes from native object like this:
var obj = {}
obj['a'] = '1'; //obj.a = '1' work's too
console.log(obj.a); //now it log '1' :]
Also, your verification function is wrong.. it only check if first exists inside myObj and if second exists and is equal to "yes". So your verification function should be something like this:
$("#verify").click(function() {
var allFieldsOK = false;
for ( var field in checkedFields ) {
if ( !(allFieldsOK = checkedFields[field] ) ) break;
}
$('.results').text( allFieldsOK ? 'all good' : 'not good' );
});
Here is an update to you jsFiddle, it is working for you purpose and should work if you add more input fields with the class checkblank :]
http://jsfiddle.net/6dXd7/5/
replace this
$("#verify").click(.........});
with this
$("#verify").click(function() {
var flag=true;
$('.checkblank').each(function(){ //check all elements with class checkblank
if($(this).val().length==0) //set flag false if anyone of them is blank
flag=false;
})
if (flag) {
$('.results').text('all good');
} else {
$('.results').text('not good');
}
});
...it should work

Categories