开发者

Javascript onsubmit clearcontent not working

开发者 https://www.devze.com 2023-01-03 03:32 出处:网络
<textarea onfocus=\" javascript:clearContents(this); this.cleared=true;\" rows=\"5\" cols=\"40\" id=\"comment\" name=\"comment\" <?php if($vis[\"username\"] == $pusernam开发者_如何转开发e) { ech
<textarea onfocus=" javascript:clearContents(this); this.cleared=true;" rows="5" cols="40" id="comment" name="comment" <?php if($vis["username"] == $pusernam开发者_如何转开发e) { echo "DISABLED"; } ?>>...</textarea>
<input onsubmit="if (!this.comment.cleared) clearContents(this.comment); return true;" type="submit" name="Submit" value="Stem!"/> 

function clearContents(element) {
  element.innerHTML = '';
}

This wont work, and i cant figure out why. What it does: clears the content if it hasnt been onfocus/clicked on by the person


clearContents( document.getElementById('comment') )

You should bind onsubmit to the <form> and do this unobtrusively, ideally...


<input onsubmit="if (!this.comment.cleared)

this is the <input>. Input elements don't have a submit event or a comment property. Probably you want to put this on the surrounding <form> element:

<form onsubmit="if (!this.comment.cleared) ...

Whilst it is possible to put it on the submit button, you'd have to use onclick="if (!this.form.comment.cleared) ..., to navigate up to the form and down to the other input. It's not generally a good idea to tie form submission code to a particular button.

As meder said, doing all this in inline event handlers is a bit ugly. (Especially the unnecessary javascript: prefix.) Prefer to assign from JS instead:

<form id="someform" method="post" action="somewhere"><div>
    <textarea
        rows="5" cols="40" name="comment"
        <?php if($vis['username']==$pusername) { ?>disabled="disabled"<?php } ?>
    >
        ...
    </textarea>
    <input type="submit" name="Submit" value="Stem!" />
</div></form>

<script type="text/javascript">
    var f= document.getElementById('someform');
    var cleared= false;
    f.elements.comment.onfocus= function() {
        f.comment.value= '';
        cleared= true;
    };
    f.onsubmit= function() {
        if (!cleared)
            f.comment.value= '';
    };
</script>

I've used XHTML syntax for the disabled attribute (since you seem to be using XHTML syntax elsewhere), and used value to clear the content. Don't use innerHTML—it doesn't do what you think, except when it coincidentally does due to browser bugs. Form fields should always be accessed using value.

0

精彩评论

暂无评论...
验证码 换一张
取 消