OnBlur Assignment to Function in Javascript - javascript

I have a code like this;
<script type="text/javascript">
var ID= document.getElementById('customfield_10033');
var IDNumber= document.getElementById('customfield_10033').value;
ID.onblur=function(IDNumber)
{
if ((IDNumber!="") && (IDNumber.length!=11)){
alert("Your ID number should 11 digits.");
}
But when i enter ID number with 11 digits, shows me alert function. But it shouldn't.
I think i doing wrong assign Onblur property to function.. ID.onblur=function(IDNumber)
How can i fix this code?

You define IDNumber when you assign the event handler (so it will probably be holding whatever you set the default value of the field to be), but you almost certainly want to define it when the blur event occurs.
Move
var IDNumber= document.getElementById('customfield_10033').value;
Inside your event handler function.
(Since you already have a reference to the element it would be more efficient to do var IDNumber = ID.value; too)

You should have something like this instead:
ID.onblur = function(IDNumber)
{
var IDNumber = ID.value;
if (IDNumber !== "" && IDNumber.length !== 11)
{
alert("Your ID number should 11 digits.");
}
}
By assigning the value into variable, you place static data, not a pointer to the value so you have to read the "live" value every time.

You forgot to close the if-statement. Try this:
if ((IDNumber!="") && (IDNumber.length!=11)) {
alert("Your ID number should 11 digits.");
}
Regards,
Thomas

Related

check if array has the user inputted value

I am using an input field to put user inputs in an array.
I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.
Here is my attempt.
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
var oks = [];
// set num
// check if num is in the oks array
if( oks[num]==num ){
alert("It is already there.");
}
else{
oks[num.value]=num.value;
}
console.log(oks.value);
}
With the above code it says undefined in the console log.
Please help me find where I am wrong in this.
Thanks a lot :)
Your code has lots of mistakes, such as :
var oks = [];
The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.
oks[num]
The above is not the value, it's the element in the array whose index is the value, which are very different.
num.value
The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.
And here's the solution to your problem :
if( oks.indexOf(num)>-1 ){
alert("It is already there.");
}
else{
oks.push(num);
}
you can do
if(oks.indexOf(num) != -1)
to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient
var oks = [];
is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use
var oks = {};
// at a parent scope
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
// set num
// check if num is in the oks array
if( oks{num} != undefined ){
alert("It is already there.");
}
else{
oks[num]=true;
}
console.log(oks.num);
}

JavaScript "if" statement wont run

(Using Javascript)
If I enter text in the textbox or not, the alert will not come up.
I know this is a simple fix but I can not figure it out!
(This is for learning purposes.)
Workout Log Test
<script type="text/javascript">
function myResults() {
myExercise();
myWeight();
mySets();
myReps();
myFunction();
}
function myExercise() {
var txtExercise = document.getElementById("txtExercise");
var txtOutput = document.getElementById("txtOutput1");
var name = txtExercise.value;
txtOutput1.value = "You destroyed, " + name + "!"
if (txtExercise.length === 0) {
alert ('Do you even lift?');
return;
First off, you're checking the "length" property of the element rather than the value of the input.
Second of all, you're checking against an integer value. If you were to simply read the value of the element, you're going to get text.
I'm guessing, what you want is something like:
var exercise = parseInt(txtExercise.value, 10);
if(exercise === 0) {
alert('Do you even lift?');
return;
}
But that's assuming txtExercise is an input element. Without seeing your markup, it's hard to be sure that any given answer will work.
Here you go, all fixed. You need an event handler, and this is a better if/else use case.
http://codepen.io/davidwickman/pen/vOKjqV
// Check the .value.length instead of just the .length
if (txtExercise.value.length === 0) {
alert('Bro, do you even lift?');
} else {
txtOutput1.value = "You destroyed, " + name + "!";
}
Assuming you have closed the function and if statement properly, you are missing a semi colon just before the if statement.
txtOutput1.value = "You destroyed, " + name + "!"; <---- here

How to increment div id name and localStorage content name using for loop?

I'm trying to run a for loop and increment a number of things here but can't get my head around it
jQuery code
var counter1 = localStorage.getItem('counter1item');
if (counter1 == null){
$("#i1").html('Zero');
} else {
$("#i1").html(counter1);
}
$("#i1").on("click", function(){
counter1++;
$("#i1").html(counter1);
localStorage.setItem('counter1item', $("#i1").html());
});
When I'm use for loop and try to increment everything then it doesn't work:
var i = 0;
for(i=0;i<100;i++){
var counter+"i" = localStorage.getItem('counter+"i"+item');
if (counter+"i" == null){
$("#i"+i).html('Zero');
} else {
$("#i"+i).html(counter+"i");
}
$("#i"+i).on("click", function(){
counter+"i"++;
$("#i"+i).html(counter1);
localStorage.setItem('counter+"i"+item', $("#i"+i).html());
});
}
What am I doing wrong? Any help would appreciated, Thanks.
The problem of your variable definitions has been already explained.
Another problem - When setting click event inside loop, the counter and i variables are overridden each iteration, so that each button will return variable which was set at the end of the loop.
F.ex:
If the loop is: i=0; i<100; i++ , then at the end of the loop i for each button will be always equal to 100. And counter will be always equal to the last set counter +1, because these variables loses their uniqueness outside the loop.
You have to store the i variable somewhere, so that it won't get updated while loop lasts, and is always unique for each button.
I'd store the i in a data-id attribute of the button and set click event on class selector, outside for loop.
Also, since the data is a simple string, you can use .text() instead of .html().
HTML:
<button class="counter" id="i0"></button>
<button class="counter" id="i1"></button>
...
Script:
// no need for this:
//var i = 0;
for(/* i is defined here: */ var i=0; i<10; i++){
var c = localStorage.getItem('counter'+ i +'item');
// add data-id to the element:
$("#i"+i).text(c == null ? 'Zero' : c).data('id',i);
}
// listen for click event on 'counter' class:
$(document).on("click",".counter", function(){
// parse number from text of the button:
var c = $(this).text(parseInt($(this).text())+1 || 1).text();
// grab the id from data-id attribute:
localStorage.setItem('counter'+ $(this).data('id') +'item', c);
});
DEMO
Remove all quotes around the use of variables. Putting them in quotes makes them a string, not your variable (multiple instances of this problem)...
Like this:
'counter+"i"+item'
Literally translates to this string:
counteriitem
Say i = 2, you would write it like so:
'counter'+i+'item'
to result in this string:
counter2item
Also, I don't see the variable counter defined in the second snippet correctly.

even.data is not change

here is my own practice demo, it works well as i expect. but when i use line 8 ( comment on my demo code ) instead of line 7 ,the input text values all change to 0 which is different than the result of demo i giving out.
i look at the jquery website it only gives me this
Description: An optional object of data passed to an event method when the current executing handler is bound.
i think the result of using line 8 or line 7 should be the same because of i is assigned to count object, but it is not. Could someone explain me about this question. by the way, if someone could refactor my code will be even more nicer THANKS!!
here is my code
var i = 0;
$("#aa").on("click", {
count : i
},
function(event) {
var div = $('<div/>');
var input = $('<input />').attr("value", event.data.count);
event.data.count++;
//i++;
var bt = $('<input />').attr({
type : "button",
value : "remove",
});
div.append(input);
div.append(bt);
var index = $("div").length;
if (index == 0) {
$("#aa").after(div);
} else {
$("div").last().after(div);
}
bt.on('click', function(event) {
$(this).parent().remove();
});
});
when the current executing handler is bound.
this is important thing in the section. So, the object will be created only once, during the time of binding the function with the click event. So, changing i will not change the value of event.data.
When you do
event.data.count++;
you are actually mutating the object and the state of the object will be retained. That is why it works.

keep add the value without overwrite the function

function checkData() {
var temp = 0;
var totalMarks = countMark(temp);
if (totalMarks != 100)
window.alert("Marks must total 100");
}
function countMark(mark) {
var totalMark = 0;
totalMark += parseInt(mark)
return totalMark;
}
function doAdd() {
var taskid = document.getElementById("taskid").value;
var taskname = document.getElementById("taskname").value;
var taskmark = document.getElementById("taskmark").value;
if (taskid.length === 0)
window.alert("Task Id cannot be empty!");
if (taskname.length === 0)
window.alert("Task name cannot be empty!");
if (taskmark.length === 0)
window.alert("Task Mark cannot be empty!");
else if (!markpattern.test(taskmark))
window.alert("Invalid data in mark field");
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
}
My question is when i keep call the doAdd() function. my marks will keep adding . want to do like passing reference like in C++ . my function countMark(...) will keep adding .
after that, when my form submitted, my form will call the function checkData()
If my totalmark is not 100 . will prompt out the alert and error.
but my code is not working . I guess that my countMark function wrong somewhere
If I understand you correctly, you're looking for the equivalent of a static variable - something that gets initialized the first time the function is called, and keeps it's value for subsequent calls.
Take a look at this related question: https://stackoverflow.com/a/1535650/2444111
The top answer (by CMS) is talking about class-based static variables, which are not quite the same thing.
The second answer (by Pascal MARTIN) is what you're looking for. It takes advantage of the fact that JS functions are also objects, and stores the variable as a property of the function object. This is a better solution than using a global variable (or a property of window, which is what a global actually is)
There are several issues in your code and it's really hard to say what your intention was. But I will address what I found.
In the following piece of code you are requesting a DOM Element and try to parse it as an Integer. The result of that type convertion is always NaN. Maybe wanted to get the value attribute of your element, like you did before. (Also, don't request the same element multiple times. Request it once, save the result in a variable and use that variable from that on).
var marks = parseInt(document.getElementById("taskmark"));
if (marks < 0 || marks > 100)
window.alert("Marks out of range. Please re-enter");
countMark(marks);
Your function countMark is pretty useless, because it will always return whatever Number you pass to it (see comments in your code).
function countMark(mark) {
var totalMark = 0; //create a new variable with value 0
totalMark += parseInt(mark) //add "mark" to that variable
return totalMark; //return that variable => 0 + mark = mark (and if mark = NaN => 0 + mark = NaN)
}
Maybe you wanted to make totalMark a global variable, than you would need to define it outside of your function:
var totalMark = 0;
function countMark(mark) {
totalMark += parseInt(mark);
return totalMark;
}
Last but not least, lets analyse your function checkData:
function checkData() {
var temp = 0; //create a local variable with value 0
var totalMarks = countMark(temp); //pass 0 to countMark => return 0 => totalMarks = 0
if (totalMarks != 100) //always true since totalMarks is always 0
window.alert("Marks must total 100"); //will always alert
}

Categories

Resources