PDA

View Full Version : Help me with a code i wrote.. plz



Neoeyal
07-17-2006, 06:51 PM
Hey.
I wrote this code and put it in the <head> section:

<script LANGUAGE="JavaScript">
function displaymbkb(obj)
{
var after_text='Its <b>'+obj.value/1000000+'</b> MB and <b>'+obj.value/1000+'</b> KB'
document.write(after_text)
}
</script>


then I wrote this in the <body> section:

<input type="text" name="canup" size="15" onkeyup="return displaymbkb(this)" value="<? echo $canup; ?>">

When I pressed the Submit button the function worked but it displayed the result in a new page... how can I make it appears in the same page the <input> was?

Twey
07-17-2006, 07:20 PM
<script LANGUAGE="JavaScript">The language attribute is deprecated for type.


<input type="text" name="canup" size="15" onkeyup="return displaymbkb(this)"You can't document.write() after the page has finished loading, or it will implicitly document.open() and obliterate the contents of your document.

value="<? echo $canup; ?>">If you're using short tags anyway, you may as well use the <?=VALUE?> construct.
<script type="text/javascript">
function displayByteValues(val, op) {
var opEl = op;
if(typeof op == 'string') opEl = document.getElementById(op);
for(var i = 0, e = opEl.childNodes; i < e.length; ++i) // remove all children
opEl.removeChild(e[i]);
op.appendChild( // add text
document.createTextNode("It's ")
);
op.appendChild( // add a <b> element
document.createElement("b")
).appendChild( // add text to that <b> element
document.createTextNode(val / 1024 / 1024)
);
op.appendChild(
document.createTextNode(" MB and ")
);
op.appendChild(
document.createElement("b")
).appendChild(
document.createTextNode(val / 1024)
);
op.appendChild(
document.createTextNode(" KB.")
);
}
</script>

<!-- Create a blank span to store the output... -->
<span id="sizeOutput"></span>

<!-- Call the function, passing the value and the ID of the element to which to output... -->
<input type="text" name="canup" size="15" onkeyup="return displayByteValues(this.value, 'sizeOutput');" value="<?=$canup?>">

jscheuer1
07-17-2006, 07:22 PM
document.write will do that. Use an element's innerHTML and write to that, ex:


<script type="text/javascript">
function displaymbkb(obj){
var after_text='Its <b>'+obj.value/1000000+'</b> MB and <b>'+obj.value/1000+'</b> KB';
document.getElementById('mbkb').innerHTML=after_text;
}
</script>

For this to work, you will need an element with the id used, somewhere in the body:


<br><span id="mbkb"></span><br>

Unless you want some type of actual submission to occur, make sure your form has action="javascript:void(0)" and no method set. Otherwise, use the action and method most appropriate to your purposes.

Neoeyal
07-17-2006, 07:29 PM
Thanks !!
I have another question:
I have two Input Radios and i want to do that if i check Radio 1 it will show me something lets say "value1" and if i'll check Radio 2 it will show me "value2"

how can I do it ?

Twey
07-17-2006, 08:00 PM
Use an element's innerHTMLinnerHTML has several problems that could spring up to ensnare a coder, and will hopefully soon be deprecated. It should be avoided where possible.
I have two Input Radios and i want to do that if i check Radio 1 it will show me something lets say "value1" and if i'll check Radio 2 it will show me "value2"Use the code above with a simple if statement.

Neoeyal
07-17-2006, 08:17 PM
ok i'll try...

now about the code you wrote
it gives me an error

Object doesn't support this property or method.

jscheuer1
07-17-2006, 10:50 PM
Which code? It seems you recieved two responses here.

Neoeyal
07-17-2006, 11:19 PM
it's about the first code of Twey
but i fixed it..
i did

onkeyup="return displayMB(this.value, sizeOutput)"
instead of

onkeyup="return displayMB(this.value, 'sizeOutput')"

look at the sizeOutput .

I have another problem with this script
it seems like it doesn't remove all the children

my code now is:

<script type="text/javascript">
function displayMB(val, op) {
var opEl = op;
if(typeof op == 'string') opEl = document.getElementById(op);
for(var i = 0, e = opEl.childNodes; i < e.length; i++) // remove all children
opEl.removeChild(e[i]);
op.appendChild( // add text
document.createTextNode("It's ")
);
op.appendChild( // add a <b> element
document.createElement("b")
).appendChild( // add text to that <b> element
document.createTextNode(val * 1024 * 1024)
);
op.appendChild(
document.createTextNode(" MB")
);
}
</script>

the <input> and the <span>:

<input type=text name=MB onkeyup="return displayMB(this.value, sizeOutput)"> <span id="sizeOutput"></span>

you can check the bug it does here:
http://www.eyal.webkit.biz/MsU/admin.php
(password- admin)
because i don't know how to explain the problem...
Write a number at the <input> below to "How much MB?"
then delete the number or write another number.. it's getting crazy

what's the solution ?

Twey
07-18-2006, 12:37 AM
<script type="text/javascript">
function displayMB(el, op) {
var inEl = (typeof el == 'string' ? document.getElementById(el) : el),
outEl = (typeof op == 'string' ? document.getElementById(op) : op);

while(outEl.hasChildNodes())
outEl.removeChild(outEl.firstChild);

outEl.appendChild(
document.createTextNode("It's ")
);
outEl.appendChild(
document.createElement('b')
).appendChild(
document.createTextNode(Math.floor((parseFloat(inEl.value) / 1024 / 1024) * 10000) / 10000)
);
outEl.appendChild(
document.createTextNode(" MB")
);
}
</script>
<input type="text" name="MB" onkeyup="displayMB(this, 'sizeOutput');">
<span id="sizeOutput"></span>Sorry, I'm new to all this new-fangled DOM malarkey too, but thanks to Mike Chambers (http://weblogs.macromedia.com/mesh/archives/2006/01/removing_html_e.html), I have discovered a Better Way of Doing Things. :) I even added some rounding code.

jscheuer1
07-18-2006, 02:40 AM
innerHTML has several problems that could spring up to ensnare a coder, and will hopefully soon be deprecated. It should be avoided where possible.Use the code above with a simple if statement.

What exactly could those be? I mean, just about every method or technique used in code has its potential problems. As things stand now though, in my experience, the DOM is a less reliable method because it is newer and not as universally supported, and where it is supported, not uniformly so. As a way to dynamically change an existing element, it is far more complex than need be.

I agree that innerHTML has its problems. But considering that even universally deprecated elements, let alone code, still enjoy wide and effective use, I would not count on its disappearing anytime soon.

Don't get me wrong. I like the DOM and am happy to use it in original code and to work with it in existing code when it is a good way to deal with the task at hand.

I would caution you though, Twey. In your exuberance to abandon innerHTML and embrace the DOM, especially in light of your tendency to ignore the limitations of IE, you may find yourself writing niche code, without even realizing it.

Oddly enough, if you think about it, innerHTML still suffers from some of the same problems since its introduction as the DOM methods now do. Except that, with innerHTML, this is no longer the case in the typical modern browser. So, I wouldn't necessarily say one is better than the other but that certain situations seem tailor made for one or the other and that, whichever you use, one must continue to code for as wide an audience as possible.

Twey
07-18-2006, 03:05 AM
I agree that innerHTML has its problems. But considering that even universally deprecated elements, let alone code, still enjoy wide and effective use, I would not count on its disappearing anytime soon.Deprecation doesn't imply removal from browsers. However, just because something exists isn't necessarily a reason to use it, as you should know well.
Don't get me wrong. I like the DOM and am happy to use it in original code and to work with it in existing code when it is a good way to deal with the task at hand.I feel exactly the opposite way :) I love innerHTML, it's certainly easy to code with, and I used it to excess when working with the new Typing Text script, which would have been a purest nightmare to code using DOM methods. Even widely-implemented as it is now, though, it's still not part of the DOM specification, and so isn't reliable in the slightest.
In your exuberance to abandon innerHTML and embrace the DOM, especially in light of your tendency to ignore the limitations of IE, you may find yourself writing niche code, without even realizing it.I agree. I suppose I'm an academic at heart, and as much as I try to tell myself it's the end result that matters, I occasionally slip back in the familiar pattern of "if IE can't be bothered to support the standards, I can't be bothered to support IE." Having IE unavailable for testing most of the time doesn't help either. I do tend to hold off publishing any major code until it's been checked in IE, though.
Oddly enough, if you think about it, innerHTML still suffers from some of the same problems since its introduction as the DOM methods now do. Except that, with innerHTML, this is no longer the case in the typical modern browser. So, I wouldn't necessarily say one is better than the other but that certain situations seem tailor made for one or the other and that, whichever you use, one must continue to code for as wide an audience as possible.Yes, but that includes future audiences as well. I guess that's what feature detection is for.

jscheuer1
07-18-2006, 07:56 AM
Well Twey, I tested my code (really mostly the OP's code) and it worked. So what's wrong with innerHTML for this? Also, your code worked but gave NAN in some situations.

Twey
07-18-2006, 09:22 AM
So what's wrong with innerHTML for this?In this case, just the usual non-standard-code issues, insofar as I can tell. There's some rather complex closure problems that result in forms and event handlers created by innerHTML not working properly, if I remember correctly.
Also, your code worked but gave NAN in some situations.Yours should as well, and in more circumstances (you didn't parseFloat()). I started to implement NaN-checking, but ended up deciding not to since it was only a convenience mechanism.

jscheuer1
07-18-2006, 09:41 AM
I don't see a form here, only a text input. Even if one were to have a form, the innerHTML could be used solely to display the results outside of the form.

I'm not claiming any great credit for 'my' code, I just adapted the OP's method to the innerHTML technique. I think the OP's math was simpler, perhaps.

One thing I don't understand though, is this thing supposed to do anything besides convert the user input number to MB's and KB's and if not, what's the php for?

I ran both versions on a php enabled server and neither one of them seemed to get anything out of being .php pages.

Twey
07-18-2006, 10:35 AM
I don't see a form here, only a text input.As I said, in this case there's no specific issue other than the fact that it would be non-standard code. I don't think it really matters here since the form itself wouldn't be modified by innerHTML, but I've a feeling <input> elements must be in a <form>. Not too sure though.
I think the OP's math was simpler, perhaps.But not necessarily so accurate. It's simple enough for him/her to switch his/her arithmetic back in if he/she wants (although I would point out the difference between one kilobyte [1KB, 1,024 bytes] and one kibibyte [1KiB, 1,000 bytes]).
One thing I don't understand though, is this thing supposed to do anything besides convert the user input number to MB's and KB's and if not, what's the php for?The PHP just sets a default value for the textbox, presumably defined elsewhere on the page, outside the pertinent code. You're right: without that value being defined, the PHP doesn't do anything.

Neoeyal
07-18-2006, 11:00 AM
http://www.eyal.webkit.biz/MsU/admin.php
password: admin

The php sets values for
http://www.eyal.webkit.biz/MsU/upload.php
(it's written in Hebrew.. but you can understand it)
try to write a number of MBs in the last <input> at the admin.php page (Users can upload (in bytes))
default- 5MB
press Submit
then go to uplaod.php... you can upload only the same MBs number you wrote

btw
http://www.eyal.webkit.biz/MsU/url.php
i did it with innerHTML
is it ok to use it here or should I use DOM?

Twey
07-18-2006, 11:06 AM
i did it with innerHTML
is it ok to use it here or should I use DOM?Now you've done it. The debate was just beginning to settle down too. :p

You should use DOM. You should also use a valid parse tree (http://validator.w3.org/check?uri=http%3a%2f%2fwww%2eeyal%2ewebkit%2ebiz%2fMsU%2fupload%2ephp).

Neoeyal
07-18-2006, 11:17 AM
what is valid parse tree?
i didn't understand it

and about the url.php
i wrote this:

<script type="text/javascript">
function checkRadio(el, op) {
var inEl = (typeof el == 'string' ? document.getElementById(el) : el),
outEl = (typeof op == 'string' ? document.getElementById(op) : op);

while(outEl.hasChildNodes())
outEl.removeChild(outEl.firstChild);
if(el=='f')
{
var input = document.createElement("input");
input.type = "file";
input.name = "userfile";
outEl.appendChild(input);
} else if (el=='u')
{
var input = document.createElement("input");
input.type = "text";
input.name = "userurl";
outEl.appendChild(input);
}
</script>
upload: <input type="radio" name="r1" checked value="filer" onClick="checkRadio('f', 'fileUrl)"> file <input type="radio" name="r1" value="urlr" onClick="checkRadio('u', fileUrl)"> url
<br>
<span id="fileUrl"><input type="file" name="userfile"></span>

ant it didn't worked.. maybe because i don't how to make an <input> in appendChild

what should I do ?

Twey
07-18-2006, 12:26 PM
You should use well-formed markup in order to achieve a correctly-formed DOM tree. The validator to which I linked you will help you do so. Manipulating the DOM will often fail with no other apparent cause if you have an invalid DOM tree, and the behaviour of browsers that parse it is unpredictable.

Neoeyal
07-18-2006, 12:43 PM
amm I didn't understand everything you said (sry i'm so go at english, yet :P)
what do I have to do exactly?

and what about the url.php ? (I edited the post if you mess it)

jscheuer1
07-18-2006, 02:29 PM
Neoeyal,

Twey is certainly right that to use the DOM you need a valid parse tree for the document. But, there's more. Having a valid document makes any future editing/modifications more likely to work as expected.

Twey,

Sorry about that, I thought the issue was settled here and that Neoeyal was using your method successfully. It wasn't my intent to push a competing versions agenda. I just wanted more of your thinking.

Both,

It seems that this issue wasn't settled. Either method should be OK if you know what you are doing. I think we should try to follow Twey's recommendations here as, he is more familiar with PHP than I am, and should be able to consider more of that side of the issue. However it is done, the markup should be valid. This should be fairly simple as these appear to be fairly simple documents.

Twey
07-18-2006, 03:01 PM
Sorry about that, I thought the issue was settled here and that Neoeyal was using your method successfully. It wasn't my intent to push a competing versions agenda. I just wanted more of your thinking.Oh no, I wasn't suggesting you were. It's just one of those arguments that's been discussed to death, rebirth, and further death without anybody really coming up with a satisfactory answer.
I think we should try to follow Twey's recommendations here as, he is more familiar with PHP than I am, and should be able to consider more of that side of the issue.PHP doesn't really come into this, it's only (from the point of view of the script) used to set a default value.

I view the innerHTML/DOM issue as I do the invalid/valid markup one: the latter is a much cleaner solution, and while in some cases it may offer no immediate benefits at the present time -- in fact, it's usually more trouble to implement -- it's more likely to be well-supported in the cases one can't consider, and a little extra work now will probably save a lot of rewriting in the future.

I found out more about problems of innerHTML with forms and event handlers, by the bye. The key point is to remember that a += b is shorthand for a = a + b. So, if you have a form:
<form action="">
<input type="text" name="a">
<input type="button" onclick="this.form.innerHTML += unescape('<input type=%22text%22>');" value="Add new input">
</form>If the user types some text (say 'sakana') into one of the text fields and then clicks the button, the script will delete every element in the form then create new ones from the supplied HTML string. This means that the contents of all the fields will be lost, except in IE, which, apparently, alters the innerHTML when the value of a form element is modified. After inputting our example text, the form's innerHTML would be:
<input type="text" name="a" value="sakana">
<input type="button" onclick="this.form.innerHTML += unescape('<input type=%22text%22>');" value="Add new input">The same happens with other properties that aren't set in the HTML, such as script-set event handlers.

jscheuer1
07-18-2006, 03:30 PM
It's just one of those arguments that's been discussed to death, rebirth, and further death without anybody really coming up with a satisfactory answer.

I tend to like to have my own shot at resolving those questions, especially with someone who has a strong opinion one way or the other but who is also open to rational discussion.

The example you give about wiping out a form while appending to it, the way you put it, I wouldn't have thought that would have worked without wiping out the previous values in any browser. If I had just thought to do it on my own though, I would have tested it in at least three browsers and seen that it only worked in IE. However, one could just as easily wipe things (not just form values) out using the DOM, if one were not being precise. The trick with any technique is to use it within its limitations and to use it properly and to make it actually do what you want it to do.

On the wider compatibility issue, I don't think we need to worry about appropriately utilized innerHTML being phased out. As for non-standard markup (the separate issue of valid vs. invalid HTML and css code), as long as the correct DOCTYPE or no DTD is used, that will also, most likely, continue to be widely supported but, not as widely as I suspect innerHTML to be.

Interestingly, I've noticed the W3c using invalid css for some of its pages to (presumably) support legacy browsers and the quirks of current browsers. This doesn't seem to prevent them from using the "valid css" images on some of those pages. Go figure. I can happily live with that standard, validate the css unless needed to deal with a quirk or legacy browser.

Neoeyal
07-18-2006, 03:41 PM
What is DOM tree?
what do I have to do exatly with my document?
and can you help me please with this post -
http://www.dynamicdrive.com/forums/showpost.php?p=44037&postcount=18
just the part with the url.php

Twey
07-18-2006, 03:42 PM
However, one could just as easily wipe things (not just form values) out using the DOM, if one were not being precise.Well, of course. It would be a lot more difficult to do it unintentionally, though.
Interestingly, I've noticed the W3c using invalid css for some of its pages to (presumably) support legacy browsers and the quirks of current browsers. This doesn't seem to prevent them from using the "valid css" images on some of those pages. Go figure. I can happily live with that standard, validate the css unless needed to deal with a quirk or legacy browser.I did actually intend to add "except where absolutely necessary" to that third paragraph somewhere. I guess I forgot. :rolleyes:
That doesn't excuse its use for sheer convenience, though.

Neoeyal:
Just do what the validator tells you. If you have any problems with a specific error, post here.
With regards to your url.php page, you've forgotten to close the quotes for 'fileUrl'.

Neoeyal
07-18-2006, 06:54 PM
Result: Failed validation, 1 error
Below are the results of attempting to parse this document with an SGML parser.

1. Error Line 8 column 120: required attribute "ACTION" not specified.
...בצים: jpeg, jpg, bmp, png, gif, rar, swf<br><form enctype=multipart/form-
The attribute given above is required for an element that you've used, but you have omitted it. For instance, in most HTML and XHTML document types the "type" attribute is required on the "script" element and the "alt" attribute is required for the "img" element.

Typical values for type are type="text/css" for <style> and type="text/javascript" for <script>.
http://validator.w3.org/check?uri=http%3A%2F%2Fwww.eyal.webkit.biz%2FMsU%2Fupload.php&charset=%28detect+automatically%29&doctype=Inline



What do I have to do ?

never mind.. i fixed it
Thanks for all the help both of you!