Problem Clearing TextBox in JavaScript - javascript

I am new to this, but I am trying to clear whatever content is in a text box. The code I have in the body section is as follows:
<body>
<FORM NAME = "frmOne" method=POST>
Name: <INPUT TYPE=text NAME=name onFocus="this.form.name.value=''" /><br />
<input type="button" value="Click To Clear" onClick="clearForm(this.form)">
</FORM>
<SCRIPT LANGUAGE="JAVASCRIPT">
function clearForm(form){
form.name.value = "";
</SCRIPT>
</body>
Problem is, clicking the button does nothing and anything in the Name box remains there! Can anyone suggest why? I am probably making a very basic mistake.
Thanks,
Stuart

It's because you have a syntax error, you are missing a }. It should be:
function clearForm(form){
form.name.value = "";
} // <- you have to close the function
Then it works.
Tools like Chrome developer tools or Firebug for Firefox help you to detect such errors. For example, your code results in the following error:
Uncaught SyntaxError: Unexpected end of input

Instead of using name, its good practise to use ids.
So for your input, use:
<INPUT TYPE=text NAME=name ID="myFormTextbox" onFocus="this.value=''" /><br />
And for your js:
function clearForm(form) {
document.getElementById("myFormTextbox").value = "";
}

Related

I cant change text using javascript?

Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?
js:
<script>
function sending(){
document.getElementById("submit_form").value = 'Sending...';
};
if (window.location.href.indexOf("err") != -1){
alert("An error occured! Please make sure to check your input fields."); //this works fine
document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
};
</script>
HTML:
<form action="https://postmail.invotes.com/send"
method="post" id="email_form">
<h2>Feedback</h2>
<h4>Your Email:</h4>
<input type="text" name="subject" placeholder="aa#aa.aa" style="width: 80%;"/><br>
<h6>Your Message:</h6>
<textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
<input type="hidden" name="access_token" value="--" />
<input type="hidden" name="success_url" value="./comments.html" />
<input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>
<input id="submit_form" type="submit" value="Send" onclick="sending();" />
</form>
<p id="ertext"></p>
<br> <br>```
The Javascript code needs to be executed after the html document is loaded. As mentioned before you can achieve this by putting the script tag somewhere below all referenced elements in your DOM.
Another possibility is to put your JavaScript into a separate file "test.js" and then include it in the head of your document:
<script type="text/javascript" src="test.js" defer></script>
Using the defer attribute makes sure the script will be executed after the page finished parsing.
It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.
<script>
// before the DOM element
// Below line would raise TypeError: Cannot set property 'innerHTML' of null
document.getElementById('ertext').innerHTML = location.href;
</script>
<h1 id="ertext">the element</h1>
<script>
// after the DOM element
// You'd see `the element after` which indicates
// the script that is after the DOM element can find the element.
document.getElementById('ertext').innerHTML += ' after';
</script>

Cannot clear text input field

I've tried several different ways, including Pure-JS and jQuery, but I can't get my input text field to clear. Please help.
Here's the relevant HTML:
<div align="center" id="searchDiv"></div>
<input type="text" id="searchBar" size="40" onsubmit="loadAllItems()">
<input type="submit" id="searchButton" value="Search" onclick="loadAllItems()">
<input type="button" value="Reset" onclick="reset()">
I'm trying to submit the searchBar, run backend code, and then call the reset() function to avoid manually clearing the text field:
function reset() {
document.getElementById("gradeQuestionsForm").reset();
document.getElementById('Output1').innerHTML = '';
document.getElementById('Output1').innerHTML = '';
updateStatus('Form has been reset.');
}
I tested with a JSFiddle. Please advise.
With jQuery you can do like this
fiddle
$('#searchBar').val('');
Try document.getElementById("searchBar").value = '';
Also, you need to set LOAD TYPE TO No wrap -in <head> in your JSFiddle
.
See more on running script on JSFiddle here.

Why don't I see the .value property for my string in javascript?

VS2013, MVC5, VB, in a Razor View
I wanted to set the value for a string that will be posted back to the controller. I'm pretty new to javascript, but I found this (link) which included the following code:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
When I try to type that in, the 'value' property as seen on 'elem' above is not available. Why would that be?
Ultimately I am trying to modify a form field that will be returned to a controller. While my question above is what I'm wondering about, I thought it would be useful to include the full context.
The view is setup with:
#Using (Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "thisForm"}))
My input element is:
<input type="button" onclick="UserCommit()" value="Next" class="btn btn-default" tabindex="2" />
And the script shell is:
<script type="text/javascript">
function UserCommit() {
$("#thisForm").submit()
}
</script>
The script above works and submits the form the same as the original input element which was:
<input type="submit" value="Next" class="btn btn-default" tabindex="2" />
I wanted to combine the value of multiple checkbox fields together into the single form field the controller is expecting back, so I figure I could use javascript to concatenate all the checked fields into the expect field. But I don't seem to be able to access the form field as the SO post that I linked to above suggests.
My current view uses html helpers and generates the follow html (this was taken looking at the generated source):
<input id="Response1" name="Response1" type="checkbox" value="true" /><input name="Response1" type="hidden" value="false" /> one<br />
<input id="Response2" name="Response2" type="checkbox" value="true" /><input name="Response2" type="hidden" value="false" /> two<br />
The actual form element expected is "Response", so if I concatenate Response1 and Response2 and so on, the Response will capture the data of however many checkboxes were created and checked. The controller is expecting to see "Response" and it is a bound field in the receiving method.
This is what I typed in:
<script type="text/javascript">
function UserCommit() {
var myElement = document.getElementById("Response");
myElement.value = "A new response";
$("#thisForm").submit()
}
</script>
But, the '.value' seen above doesn't show up in Intellisense, and of course doesn't run.
Added after original post:
I did also find this (link) SO post for using the checkbox helper which I will study and try to follow. But the javascript question still remains.
added for mplungjan in comments. Is this what you are asking, the line that generates the "Response" field?
#Html.CheckBox("Response", False)
That line in turn generates:
<input id="Response" name="Response" type="checkbox" value="true" /><input name="Response" type="hidden" value="false" />
Your JS code is valid from testing on JSFiddle, so this is likely a bug or limitation of Intellisense. Try setting the value directly on the document.getElementById instead of setting a variable first.
So change
var elem = document.getElementById("mytext");
elem.value = "My default value";
To:
var elem = document.getElementById("mytext").value = "My default value";
Or, use jQuery:
$('#mytext').val("my default value");

JS function not changing URL in address bar

I've trying to design a workout website which returns exercises from a database depending on a user selection. I'm writing some test code that will change the URL in the address bar when a button is clicked if an 'Arms' checkbox is checked. However, it doesn't seem to be working so any help you can offer would be appreciated:
JAVASCRIPT
<script>
function getSelection(){
if(document.getElementById('armsCheck').is(':checked')){
window.location.search = "";
window.location.href = window.location.href + "?bodypart=Arms";
}else{
return;
}
}
</script>
HTML
<form>
<input type="checkbox" id="armsCheck" />Arms<br />
<input type="button" value="Submit" onClick="getSelection()" />
</form>
You are trying to call the jQuery is() method on a DOM object, which doesn't have one. This would be obvious if you looked at your browser's JavaScript console.
Check the checked property instead.
if(document.getElementById('armsCheck').checked){
Also replace these lines:
window.location.search = "";
window.location.href = window.location.href + "?bodypart=Arms";
with:
window.location.search = "?bodypart=Arms";
As the first line would trigger a page reload before reaching the second line.
There's no need to involve JavaScript at all though. You can get the same effect with plain HTML.
<form>
<label><input type="checkbox" name="bodypart" value="Arms"> Arms</label>
<input type="submit" value="Submit">
</form>
Solved it. 'getSelection()' wasn't a valid function name - thanks for your help!

when setting the value of an input field, it just appears for a brief moment.

I am sure I am missing some basic part here, but have a look at my very simple code:
<html>
<head>
<script>
function showscore(){
var score = document.createTextNode("test");
var placeholder = document.getElementById("field");
placeholder.value = score.nodeValue;
}
</script>
</head>
<body>
<form>
<input type="text" id="field"/>
<input type="submit" value="Show score" onclick="javascript:showscore()" />
</form>
</body>
</html>
When I run it, the result (for the moment, the word "test") appears inside the input field for a very brief moment and then goes away.
What extremely simple and easy thing I am missing? :-)
Thanks very much.
That's because the page is submitting the form. Just change type="submit" to type="button" or prevent the form from submitting.
It's because your button is an <input type="submit /> so after your Javascript is executed, the browser submits the form.
If you don't want the form to submit, you could use an <input type="button" /> instead.
Alternatively you could leave it as a submit and return false; after the showscore() call. That will prevent the form from submitting.

Categories