Why is my JavaScript code showing different behavior on jsfiddle? [duplicate] - javascript

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 5 years ago.
I am new to javaScript, that's why I am unable to find the real root cause for it.
This simple code is to append the value of a button into a paragraph every time i press it; however if the paragraph contains only a zero then it should replace the value, not append.
This is working fine on all of my browsers and also when running the snippet on stackoverflow .
Not working at all on https://jsfiddle.net/
Can you please tell me why I am facing this problem and what changes should I make to make it work on every platform?
function append(a){
if (document.getElementById('text1').innerHTML == '0')
document.getElementById('text1').innerHTML = document.getElementById(a).value;
else
document.getElementById('text1').innerHTML += document.getElementById(a).value;
};
<div>
<p id='text1' style="border-style: inset;
width:200px;
display:inline-block;">0</p><br>
<button value="1" id='a1' onclick="append(this.id)">1</button></div>

By default JSFiddle wraps your JavaScript in an onload function. This means that function append is only defined in that scope, and is not made global.
Global variables (and functions) are generally considered bad practice, as are inline event handlers.
Try:
document.getElementById('a1').onclick = append;
Then, inside function append, simply refer to this.value.

Related

How to Run two JS functions on one Click? [duplicate]

This question already has answers here:
How to call multiple JavaScript functions in onclick event?
(14 answers)
Closed 7 years ago.
I was trying to run two JS functions in one click using this. Can anybody show me how to do it correctly?
<button onclick="getlocation" onclick="showDiv()">Try It</button>
I tried adding a ; between the two functions but it didnt work too.
"Adding ";" semicolon didn't work, if you could help.."
It works for sure, you have to do it like that: onclick="getLocation();showDiv()"
Was not relevant in this case:
The problem could be, that both functions are setting the content of your div, so the second function will overwrite the content!
Use .innerHTML += "..."; on you second function, this will append the content to the exisitng content.

Difficulties adding onclick to a link with javascript [duplicate]

This question already has answers here:
Onclick event getting called automatically
(3 answers)
Closed 7 years ago.
I have a script that makes that makes a tile for every item in an XML-file. The tile is a div inside an "a" tag created by javascript.
document.getElementById('Body').appendChild(tileLink);
tileLink.appendChild(tile);
tile.appendChild(tileTitle);
tile.appendChild(tileImg);
document.write(" ");
So when tileLink is clicked a javascript function "showDiv(divId)" has to be loaded. divId is a variable in the script needed to load the function.
I've tried these 2 lines but with both the script doesn't work and no objects are loaded.
tileLink.onclick = showDiv(divId);
textLink.addEventListener("click", showDiv(divId));
Where am I wrong?
Event handlers require function references. By invoking the function, you are immediately executing it.
textLink.addEventListener("click", function() {
showDiv(divId);
});

jQuery won't clear form [duplicate]

This question already has answers here:
How to reset a form using jQuery with .reset() method
(16 answers)
Closed 8 years ago.
I KNOW this question has been asked numerous times as I have used this website's solutions to no avail. I currently have this implementation:
$("input:reset").click(function () {
$('#answer_2').html('License number is not long enough');
$('#answer_1').html('');
$('#data_entry').each (function(){
this.reset();
});
});
I know the selector is correct as the two html changes (I put them in to confirm I was selector for the reset button click correctly) occur as they should.
Here is my form declaration:
<form name="data_entry" id="data_entry" method="post" action="">
The problem is I keep getting the error that there is no 'reset' function and the form is never cleared. This is my most recent attempt at following answers to this problem on stackoverflow site. Please help.
Why reset when you want to clear/empty?
this.empty();
might do the trick?
Your each is wrong and it's unnecessary.
$('#data_entry').get(0).reset();
This should work because you got the right element but $() returns a jQuery object, not a DOM element. get will grab your DOM element and then you can use reset() (which is not a jQuery function)

Uncaught ReferenceError: function is not defined [duplicate]

This question already has answers here:
Why isn't my JavaScript working in JSFiddle?
(7 answers)
Closed 9 years ago.
Im doing a simple jquery function using rangy script but im not being able to get it work, it says the error above.
<div onclick="cmon('cenas');"> cenas </div>
<textarea class="guides_chapters_textarea" id="textarea" name="gmessage" rows="7" cols="25"> Insert starting items here</textarea>
Javascript:
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
Jsfiddle: http://jsfiddle.net/VmhMM/
To get your example working, there is a few things you can do. Strictly speaking, there is actually nothing wrong with your code. The fault lies in how your code is being used/added to the page.
Here is one method of getting your code to work, by setting the function on the window object directly.
window.cmon = function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
Another method mentioned by #elclanrs in the comment on the question (which is a better option in this case) points to the setting in the left panel of the JSFiddle to do with where your function is being run. By default, it adds it to the onLoad event which makes the function out of scope as it is being defined inside the event. Here is exactly what JSFiddle did to your code:
$(window).load(function(){
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
});
The concept that is going on is known as closures. So when you define a function, any variables or other functions defined inside of that are not accessible externally. If you set the variable on a global object or any other object outside the scope of your newly defined function (like I did in the example I linked), you can access what you defined outside of the closure.
You must use (no wrap in head) at the left side. This means you must load this script between tags. But If you still want to use it onload then:
<div id="cmon"> cenas </div>
<textarea class="guides_chapters_textarea" id="textarea" name="gmessage" rows="7" cols="25"> Insert starting items here</textarea>
<script>
$("#cmon").click(function(){
cmon($(this).text());
});
function cmon(text){
$("#textarea").insertText(text, 0, "collapseToEnd");
}
</script>
Here is the solution : http://jsfiddle.net/VmhMM/2/

Why is using "javascript: <code>" bad? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Do you ever need to specify javascript: in an onclick?
To execute JavaScript on a DOM event, you could use something like this:
<div onclick="alert('Alert');">Alert</div>​
Something like this seems to work as well:
<div onclick="javascript: alert('Alert');">Alert</div>​
However, I've heard that the second example is "bad" and that the first example should be used over the second.
Is this bad? If so, why is this bad? What is the difference between alert('Alert') and javascript: alert('Alert')?
What about using it in <a> tags (if it is any different)?
Alert
Edit: To clarify, I am asking about the javascript: part specifically, and not how I have inline JavaScript mixed in with my markup. Sorry about the confusion.
Oh the wonderful confusing world of JavaScript. The code you posted probably doesn't do what most programmers think it's doing.
There is a difference between each of the following lines:
<a onclick="alert('Hello World!')"...>example</a> //V1
<a href="javascript: alert('Hello World!')"...>example</a> //V2
<a onclick="javascript: alert('Hello World')"...>example</a> //V3
although they all will alert Hello World!.
The first (V1) has an inline click event bound via the [onclick] attribute. It may also contain an [href] attribute that navigates to another location after the [onclick] attribute has executed, or any number of other click events bound in the code, assuming the default behavior hasn't been prevented.
The second (V2) has an executable javascript: url set as the [href] attribute. It might also contain an [onclick] attribute or other click events bound in external scripts.
The first and second examples (V1 & V2) have identical code executed, which is:
alert('Hello World!')
The third example (V3) has an inline click event bound via the [onclick] attribute, just like V1, however the code being executed is different. The executed code is:
javascript: alert('Hello World')
Although it looks like a javascript: url, it's actually just using a label in javascript.
Labels in JavaScript are useful for skipping out of nested loops, as in the following example code:
label: for (i = 0; i < 5; i++) { //labeled line
for (j = 0; j < 5; j++) {
console.log(i, j);
if (i === 2 && j === 3) {
break label; //this jumps out of both for loops
}
}
}
In most inline JavaScript, it's misused because the author doesn't understand the difference between the three formats.
Why is using javascript: <code> bad?
That's a leading question. It assumes that using javascript: <code> is bad.
javascript: <code> isn't bad. It's a tool. Tools aren't inherently good or bad, only the people using the tools are. You wouldn't call a hammer "bad", even if someone used it as a weapon.
javascript: <code> has some nice uses. You shouldn't use it for most cases because it's the wrong tool for the job, however if you're writing a bookmarklet, you'd be required to use the javascript: <code> format.
Additionally, there are a few niche contexts where it could make sense to leave javascript inline. An example of this would be to add a simple print button to the page:
Print
Although even this example could be easily replaced by a class and externalizing the javascript:
Print
<script>
//jQuery used for brevity
$(document).on('click', '.print', function () {
window.print();
return false;
});
</script>
There's no real problem with using the javascript: labels. It's just considered bad style most of the time.
an onclick-handler already is JavaScript, so repeating that is just senseless, redundant information (in fact, it's chaging the code thats executed by adding a label named javascript - but in most cases this shouldn't have any effect).
JavaScript code in a href attribute would be placed more appropriately in an onclick handler, so you can use the href to provide a link for users that have JavaScript disabled. This is called Progressive Enhancement.
For more detailed information, you may want to take a look at this great blog-post about "The useless javascript: pseudo-protocol"

Categories

Resources