How to use function declaration with jsfiddle - javascript

I have some html/javascript that works in my .cshtml file.
When I try to move it in to jsfiddle to experiment with, it does not work.
Not sure if if it's my lack of javascript experience, jsfiddle experience, probably both....
html:
<div>
<button name="startBtn" id="startBtn" onclick="startTimer">Start</button>
</div>
(I have also tried "startTimer()" for the onclick attribute; same result.)
javascript:
function startTimer() { alert("startTimer"); }
When I click the button, I see this in the Console:
Uncaught ReferenceError: startTimer is not defined
What am I overlooking?
(jsfiddle: http://bit.ly/1buQx9t)

jsFiddle Demo
First you have to set the Framework to No wrap - in <head>, instead of onLoad.
Description
onLoad is the same as window.onload=function(){[YOU ARE TYPING HERE]} in JavaScript or $(function(){[YOU ARE TYPING HERE]}); in jQuery.
No wrap - in <head> is the same as <head><script type="text/javascript">[YOU ARE TYPING HERE]</script</head>
No wrap - in <body> is the same as <body>[HTML CODE HERE]<script type="text/javascript">[YOU ARE TYPING HERE]</script></head>
I hope this clears up the settings in jsFiddle, they can be somewhat confusing.
Second your HTML is slightly wrong:
HTML
<div>
<input type="button' value='"Start" onclick="startTimer()"/>
</div>
Description
onclick="startTimer" was changed to onclick="startTimer()" this will execute the function.

First issue: You have the jsfiddle to set on onload so the function is not in global scope.
Second issue, you are not calling the function. You are missing ()
onclick="startTimer()"

You have some weird quotes going on there (in your fiddle) plus you forgot the () after the name of the function. Use:
<input type="button" value=" Start " onclick="startTimer()" />
jsFiddle example

If you're using pure JavaScript in jsfiddle (ie - no jquery, etc), then change the second dropdown to "No wrap - in <head>"

You had some extra misplaced quotes and were not calling the function. Needed to add the () to call it. Finally you needed to change the "onload" to "no wrap - in "
<div>
<input type="button" value="Start" onclick="startTimer()"/>
</div>

The answers above are all right; I just wanted to clarify what/where to change with this picture to solve the issue:
Here is the jsfiddle demo
<button onclick="doThat()">
Click
</button>
function doThat() {
console.log("click happened");
}

Related

Trying to change value of Textarea (using Skulpt)

Okay, so I'm using Skulpt to program Python on a webpage.
I would like the text in the interpreter change once a button is clicked.
But no matter how I try, the code in the text area doesn't change.
However, if I 'alert' the value of the text area, it brings up the changed version, indicating that the button works.
I've also found this question:
Set value of textarea in jQuery
but nothing in here helped in my case :(
Here is how I try it:
<textarea id="theTextArea">print 'Hello World!'</textarea>
<div id="controls">
<button type="button" onclick="replaceCode()">Replace</button>
<button type="button" onclick="testAlert()">Alert Me</button>
</div>
<script>
function replaceCode(){
document.getElementById('theTextArea').value = "print 'Thats new code'";
};
function testAlert(){
alert(document.getElementById('theTextArea').value);
};
</script>
Also I've tried changing .innerHTML, .text and nothing actually replaced the text in the textarea.
If anyone thinks it could help, I could add the full HTML document with the whole Skulpt setup for online python interpreter, in case it somehow doesn't let me change the value of the textarea in a regular way. But I prefer not to have a wall of code for now if it's not needed for now.
You forgot brackets in your onclicks. You should use HTMLTextAreaElement.innerHTML to change the textarea's content
function replaceCode(){
document.getElementById('theTextArea').innerHTML = "print 'Thats new code'";
};
function testAlert(){
alert(document.getElementById('theTextArea').innerHTML);
};
<textarea id="theTextArea">print 'Hello World!'</textarea>
<div id="controls">
<button type="button" onclick="replaceCode()">Replace</button>
<button type="button" onclick="testAlert()">Alert Me</button>
</div>
So it turns out Skulpt was getting in my way of modifying python code on a button click. I needed to use a function which was defined probably in one of the imported documents which come with Skulpt. The function looks like this:
editor.setValue("print 'Thats new code'");
And then it actually changes in the textarea :)

why I cant access to value of hidden input element by javascript?

I have an page that I cant use value of hidden input in if clause.
and dont print anything in page.
I use this javascript command past days and worke but dont work here.
my code is:
<script type="text/javascript">
function ch()
{
alert();
document.write(" brnd = ");
var c=document.getElementById("brnd").value;
document.write(document.getElementById("brnd").value);
document.write(document.forms["br"]["brnd"].value);
}
window.onload=ch();
</script>
</head>
<body >
<form id="br">
<input type="hidden" id="brnd" value="0000pp" />
</form>
<p>Page Description.
</p>
<div id="brands" style="" >
<ul style="height:20% !important;width:90% !important;">
<li>y.t</li>
<li>ez</li>
<li>am</li>
<li> group iks</li>
<li>frtc</li>
<li>armco</li>
</ul>
</div>
</body>
Where is the problem in your opinion?
=============================================
#Rocket Hazmat: thanks for your note.one problem was place of ch.i move ch to after input and work.but have another problem that i dont know how solved. anyway code work now.thanks all.
window.onload=ch();
This line will run the ch() function and set window.onload to its return value. ch() returns undefined, so you will not be setting onload to anything.
You want to do:
window.onload = ch;
In JavaScript, functions are like other variables. You can just pass them around normally. You use () to call them.
NOTE: document.write should never be used. Using it is most likely your other issue here. Once the page is fully loaded, document.write will destroy your page. It will erase it all and replace it with whatever you passed.
Because of this, your hidden element would be deleted and therefore you can no longer get its value.

Changing input value with javascript - what went wrong?

I have a text with an input field. I want the field to start as blank, and when clicked upon, set the input's text to its correct value (saved in the "name" field, for instance).
If I do it this way, it works fine:
Buy <input type="text" name="eggs" onclick="this.value=this.name;"> tomorrow.
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working:
HTML:
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
JS:
function showname(el) {
el.value = el.name;
}
function showname(el){
el.value = el.name;
}
.closeform{
width: 70px;
}
.closeform input {
width: 70px;
}
.closeform button {
width: 70px;
}
Buy
<span class="closeform">
<input type="text" name="eggs" onclick="showname(this);">
</span>
tomorrow.
I'm very new to Javascript - what am I missing here?
You say in your question:
However, if I try to clean the DOM and move the function to a separate javascript file, it stops working
Let's say you have 2 actual files in the same folder:
myscript.js contents:
function showname(el) { el.value = el.name; }
index.html contents:
<!DOCTYPE html>
<html><head><title>Demo</title>
<script src="myscript.js"></script>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
</body></html>
OR
<!DOCTYPE html>
<html><head><title>Demo</title>
</head><body>
Buy <input type="text" name="eggs" onclick="showname(this);"> tomorrow.
<script src="myscript.js"></script>
</body></html>
That should work perfectly...
However, in the comments you say:
I tried it with Fiddle - maybe the problem is in Fiddle interface.
That is where your problem was....
There is no separate javascript-file in jsfiddle.
The three code-blocks (html, js, css) get merged into one file.
Right-click the result-window in jsfiddle and look at the generated file.
Then notice the options (top right corner) from jsfiddle: by default the code is wrapped in an onload-method (suiting to the library you selected or window.onload if you are not using a library).
You can however place the script in the head or body, thereby not wrapping your code inside a function's scope (which then closes over the containing identifiers).
See http://jsfiddle.net/wf55a5qb/ for a working example.
The reason your example stack-snippet worked here on StackOverflow is that it's snippet-editor does not wrap the javascript codeblock in a (onload-like) function (when it combines the three code-blocks).
Having said and explained this, I do encourage you to set your events (Using obj.addEventListener/obj.attachEvent or the direct elm.onevent) from the/a script once the elements (that your script manipulates, place script as last element of the html-body) or page (using window.onload/etc) has loaded.
I posted this to clear up what actually went wrong so you don't make false models in your head about how javascript works (like "an external script runs in it's own scope" which no-one claimed but might be an assumption you might make) whilst still learning it!
Everything in JavaScript has a scope. Where you are defining your function, it is not visible to the input so the input doesn't know that function even exists. You can use window to make the function visible to it:
<input type="text" name="eggs" onclick="window.showname(this);"/>
window.showname = function (el)
Fiddle
I don't recommend global functions though. So then what else?
You can use the onclick function in JavaScript. To find elements in JavaScript, you use selectors. I'm using getElementById() this will get an element by it's id. A list of selectors are here
<input id="my_input" type="text" name="eggs"/>
Then in JavaScript:
document.getElementById('my_input').onclick = function () {
//Use this to refer to the element
this.value = this.name;
};
Fiddle
When doing this. Make sure all your code is wrapped in a window.onload. This will make sure the code is run at the right time:
window.onload = function () {
//Your code
};
JSFiddle automatically puts your code in this.

How to trigger jquery input file?

I am trying to trigger input tag to select a file by a button click though jquery. code example like the following
<input type="file" id="input_file"/>
<button onclick="select_file()"/>
function select_file() {
${'input_file').select("http://www.someimage.com/image.gif");
}
After hours of research, I still have not got the solution how I could make this happen.
Appreciate for any suggestion or solution
Thanks you
I was going to suggest:
$("#input-file").trigger("click");
but then I remembered there are security restrictions which prevent triggering and setting the values of file input dialogs.
There are some ways around it though, take a look at this question: https://stackoverflow.com/a/3030174/992435
You have typos in your codes... correct as follows;
<input type="file" id="input_file"/>
<button onclick="select_file()"/>
function select_file() {
$('#input_file').val("http://www.someimage.com/image.gif");
}
Use Val in place of Select
You missed a # sign in the function
You missed a quote in the file input tag
You used a curly brace instead of a bracket
There were a couple of things wrong with your snippet. You were not using script tags, you had forgotten the '#' before ID selectors and you had a curly bracket after the dollar sign.
<input type="file" id="input_file/>
<button onclick="select_file()"/>
<script>
function select_file() {
$('#input_file').select("http://www.someimage.com/image.gif");
}
</script>
Although the way you are approaching your problem technically works, I would never recommend it since it can lead to unmaintainable code. A better approach would be something like:
<input type="file" id="input_file/>
<button class="changeInputButton" />
<script>
$('.changeInputButton').on('click', function () {
$('#input_file').val("http://www.someimage.com/image.gif");
});
</script>
You should use
<input type="hidden" id="input_file"/>
<button onclick="select_file()"/>
function select_file() {
$('input_file').val("http://www.someimage.com/image.gif");
}
The input type of file is used mainly for local file system files.
EDIT: Sorry about the typos

dynamic window.find not working with jQuery

I can't for the life of me figure out why this isn't working.
I want to search the current page for text using a search box. I googled and found this: http://www.javascripter.net/faq/searchin.htm . I implemented the code into my site, but it doesn't work. the function ( findString() ) works, but only when I hard-code a string (as in i can't use javascript or jquery to get the value of a text input). I made this fiddle: http://jsfiddle.net/alyda/CPJrh/4/ to illustrate the problem.
You can uncomment different lines to see what I've tested.
jQuery has a method :contains() that will make easier what you are looking for.
Take a look here: fiddle
$("button[type='submit']").click(function () {
var string = $('#search').val();
var matched = $('li:contains(' + string + ')');
matched.css('color','red');
console.log(matched);
return false;
});
I found a fix (sort of). It seems that the input needs to be placed well AFTER the content to be searched in the DOM. That means I've done the following:
<section class="content">
<h2>Fire</h2>
<h3>Fire Extinguishers</h3>
<ul>
<li>Model 240</li>
<li>Model C352, C352TS</li>
<li>Model C354, C354TS</li>
</ul>
...
<div id="navbar">
<ul>
...
</ul>
<input id="search" type="text" class="form-control pull-left" placeholder="Search for part number">
<button id="submit" type="submit" class="btn btn-default pull-left" style=" margin-top:6px;">Search</button>
</div>
as you can see, I've moved the input (which is in the navbar div) BELOW all of the text I want to search, and used CSS to programmatically place the navbar at the top of the page. I don't particularly like this setup (as it messes with the flow of content) but since I was looking for the quickest and simplest implementation of a single-page search, it will have to do.
I would still love to know why this happens, when the javascript is at the end of the DOM where it belongs...
In firefox I noticed that the fiddle (v4) as given in the question worked, but not in the way the asker expected it to.
What happens in firefox is that the function does find the value..: you have just entered it in the input-field. Then the browser's find method seems to hang in the 'context' of the input 'control' and doesn't break out of it. Since the browser will continue to search from the last active position, if you select anything after the input-field, the function works as expected. So the trick is not to get 'trapped' in the input-field at the start of your search.
A basic (dirty) example on how to break out of it (not necessarily the proper solution nor pure jquery, but might inspire a useful routine, since you now know the root of the problem in FF):
$( "button[type='submit']" ).click(function(){
var tst=$('#search').val(); //close over value
$('#search').val(''); //clear input
if(tst){ //sanity check
this.nextSibling.onclick=function(){findString( tst );}; //example how to proceed
findString( tst ); //find first value
} else { alert('please enter something to search for'); }
return false;
});
Example fiddle is tested (working) in FF.
PS: given your specific example using <li>, I do feel Sergio's answer would be a more appropriate solution, especially since that would never run line: alert ("Opera browsers not supported, sorry..."), but the proper answer to your window.find question is still an interesting one!
PS2: if you essentially are using (or replicating) the browser's search-function, why not educate the user and instruct them to hit Ctrl+F?
Hope this helps!
I had same problem in an angularjs app and I fix it by changing DOM structure.
my HTML code was something like this:
<body>
<div class="content" >
<input class="searchInput" />
<p>
content ....
</p>
</div>
</body>
and I changed it to something like this:
<body>
<div class="search">
<input class="searchInput" />
</div>
<div class="content">
<p>
content ....
</p>
</div>
</body>
Note: I'm aware that this topic is old.

Categories

Resources