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.
Related
I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE
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.
Is there a way to reveald a secon input in a form after the first input has been filled? For example if I have a text input asking how many kids are going on the trip, person responds and a second input appears asking age range...
A simple example:
jsFiddle Demo
HTML:
<input id="in1" type="text" /><br>
<input id="in2" type="text" /><br>
javascript/jQuery:
$('#in1').change(function(){
if ( this.value != '' ) $('#in2').show().focus();
});
Update:
Note that you must wrap the jQuery code in a document.ready wrapper:
$(document).ready({
$('#in1').change(function(){
if ( this.value != '' ) $('#in2').show().focus();
});
}); //END document.ready
This prevents the javascript from attempting to bind an event (the change event) to a DOM element (the #in1 element) before that element exists in the DOM. $(document).ready() ensures the DOM has been fully rendered before attempting to create the event bindings.
Usually, all (or almost all) of your javascript/jQuery code is written within the $(document).ready() wrapper.
Notes:
The above code example uses jQuery, so you should reference the jQuery library in the <head> tags, comme ca:
<head>
<!-- other stuff in head -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Note that if you use a CDN to load the jQuery library, as above, it is likely that jQuery is already pre-loaded from other websites visited previously.
If you want some fast lessons on jQuery, find free video tuts here:
https://www.thenewboston.com/videos.php?cat=32
or at
http://phpacademy.org
Yes, it is possible.
You should look at either JavaScripts onchange() or jQuery's .change() event to control this action. And then of course hiding and showing certain elements.
I am working for selecting the text from a text box to the clipboard with the help of zclip. But the document.ready() is not working. It is not even showing the alert.
All required libraries are above the script tag and inside the head section. All the files are at the required positions.
I have even checked the files along with the full URL.
<script type="text/javascript" language="javascript">
$(document).ready(function(){
alert('hi');
$("a#copy_initiator").zclip({
alert('hi');
path:"js/ZeroClipboard.swf",
copy:function(){return $("input#copy-box").val();}
});
});
</script>
<a id="copy_initiator">Copy Link:</a> <input id="copy-box" type="text" value="here_is_a_url" onfocus="this.select();">
you have a syntax problem here:
$("a#copy_initiator").zclip({
alert('hi');
path:"js/ZeroClipboard.swf",
copy:function(){return $("input#copy-box").val();}
});
should be:
$("a#copy_initiator").zclip({
path:"js/ZeroClipboard.swf",
copy:function(){
return $("input#copy-box").val();
}
});
And better version:
$("#copy_initiator").zclip({
path:"js/ZeroClipboard.swf",
copy:function(){
return $("#copy-box").val();
}
});
Suggestion: use firebug to track these kind of issues.
you say "All required libraries", are you including several libraries ?
If this is the case, it could be possible that they are creating a conflict with jquery "$".
here is a webpage explaining this : https://api.jquery.com/jQuery.noConflict/
a test you can do, is going to your console entry in your browser's debugguer and try typing $('div'), or $('p'). If any of the html tags you select are recognize it means the $ is working, otherwise not.
I have a page where you can click a link that says "add a keyword" and an input will appear and you can enter the keyword, and then convert it into a span tag on blur or the "return" key. However, I've been adding onto it to allow for an "autocomplete" feature, so I'm trying to insert a
<ul></ul>
after my input in order to do a .load inside the list.
The relevant code I have is:
var addKeywordId = 0;
$('a.add_keyword').live('click', function(){
$(this).before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" /><ul><li>hi</li></ul>');
$('.add_keyword').focus();
addKeywordId++;
});
The problem is, that my HTML structure ends up looking like this:
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
<input id="addKeyword0" class="add_keyword" type="text />
INSTEAD OF
<input id="addKeyword0" class="add_keyword" type="text />
<ul><li>hi</li></ul>
<a class="add_keyword">+ add keyword</a>
Anybody know why my HTML is added out of the order I specified??
Thanks
EDIT: This seems to be working fine in Google Chrome, but not in Mozilla Firefox.. :(
This is likely due to the weird rejiggering of code Firefox does to try to display things even when there are errors. I've seen it where I miss a closing div, IE freaks out (as it should) and Firefox looks fine, as it ignores that you missed adding the ending div and guesses.
You could try a 2 stage thing. I would add an id to the ul tag, then add the input before it.
$(this).before('<ul id="ulid"><li>hi</li></ul>');
$('#ulid').before('<input type="text" class="add_keyword" id="addKeyword'+addKeywordId+'" />');
Happy haxin.
_wryteowl