How to clear the textarea value using onclick method - javascript

I'm having a listBox, when selected it, it will be printed in the textArea and beside to it I have given a clear button, so when clicked the value of the textArea has to be cleared, it works fine, now the problem is, after clearing the value in textArea and again when i select the listBox, the value is not getting printed on the textArea. What might be the problem?
Here is the code,
HTML:
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
JavaScript:
function addToExpText() {
alert("hello);
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
obj.appendChild(openP);
}
function clearTextArea(){
document.form1.textArea.value='';
}
After clearing the value in the textArea, again if i click on the listBox value and add it, it is not getting added. Pls help... Here is the implementaiton which is not working properly, may be its becaus i'm using it for the first time and i might be wrong.
http://jsfiddle.net/8dHf5/5/

Not sure why it works like that, but here are few possible fixes:
Instead of using append (to add a new aggregation function), you can use value both to add and clear:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId").value += aggreFunct;
}
function clearTextArea(){
document.getElementById("expTextId").value='';
}
Demo: http://jsfiddle.net/8dHf5/17/
Or you can use remove child nodes to clear values of textarea:
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var myNode = document.getElementById("expTextId");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
​
Demo: http://jsfiddle.net/8dHf5/14/
Besides, there is a line obj.appendChild(openP); in your code, but I do not see it being available in code, so I removed it.
Another moment: in your clearTextArea you are trying to access your textarea like document.textArea - if I'm not missing something, it is IE only feature and it works with ids instead of names. It is better to use document.getElementById which is cross browser.

There was some mistake in your code.
I have modified it...
Now you are able to clear data.
Please refer below code:
<html>
<body>
<script>
function addToExpText() {
alert("hello");
var aggreFunct = document.getElementById("aggregationFunct").value;
var obj = document.getElementById("expTextId");
var aggFun = document.createTextNode(aggreFunct);
obj.appendChild(aggFun);
}
function clearTextArea(){
var textArea = document.getElementById("expTextId");
while (textArea.firstChild) {
textArea.removeChild(textArea.firstChild);
}
}
</script>
<select id="aggregationFunct" name="aggregationFunct" size="3" multiple="multiple">
<option value="Count">Count</option>
<option value="Sum">Sum</option>
<option value="Avg">Avg</option>
</select>
<input type="button" id="addToExp1Id" value="Add" onclick="addToExpText()" >
</br> </br>
<label for="expTextId" style="font-family: sans-serif; font-size: small;"> Expression : </label>
<textarea name="textArea" id="expTextId" readonly="readonly"> </textarea>
<input type="button" id="clearId" value="Clear" onclick="clearTextArea()">
</body>
</html>

Related

Using innerHTML of <select> for windows.open()

On a page of my website I want user to select one choice of a and when they click on "connect" it open a new tab with the correct link.
code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_this_link(){
var element = document.getElementById("choice");
var link = element.innerHTML;
myWindow = window.open(link,"_blank");
}
</script>
According to the documentation this should works ... but since I'm new to JS and not expert in HTML I must have failed something.
I want to use JS only and make something that also works with datalist.
Any help is welcome !
Solved:
Ok I had 2 problem :
In order to post this on stackoverflow I changed all my variable and function name, and I forgot to change one ...
As said in the comment, I needed to use "value" and not innerHTML. I tried with value once but it also failed that's why I gave up this, I guess something else was wrong.
Thx for helping solving the problem !
(working) code :
<select name="choice" id="choice">
<option value="Server1.html">Server1</option>
<option value="Server2.html">Server2</option>
<option value="Server3.html">Server3</option>
</select>
<input type="button" name="go_button" id= "go_button" value="go" onclick="go_to_the_link()"/>
<script>
function go_to_the_link(){
var element = document.getElementById("choice");
var link = element.value;
myWindow = window.open(link,"_blank");
}
</script>

Filling hidden input field from select menu using Js

I am using this function:
function selectionchange() {
var e = document.getElementById("mySelect");
var str = e.options[e.selectedIndex].value;
document.getElementById('txt').value = str;
}
to fill the hidden field when changing options:
<form>
<select id="mySelect" onchange="selectionchange();">
<option value="1">Sun</option>
<option value="2">Moon</option>
</select>
<input type="hidden" id="txt" value="">
<button type="submit">send</button>
</form>
but it does not work.
The closing tag of < /script> looks bad. Not sure if it is caused by editing. But I have tested the code after changing < /script> to </script> and it worked fine.

Javascript onchange function not working on select tag

I made 2 input fields and 1 select field and I applied onchange() function to select tag which calls javascript and that script make calculation and show it in other two fields
but it is not working for some syntax or logic reasons. please take a look at my code ,any help would be appreciated.
<html>
<head>
<script type="text/javascript">
function update() {
var x = document.getElementsByName("n_person").value;
document.getElementsByName("m_income").value= x*5;
document.getElementsByName("y_income").value= x*4;
}
</script>
</head>
<body>
<div class="elist"> <span class="b_text"><span>*</span>Level 1:</span>
// here is select tag where I put onchage function <select class="ifield" name="n_person" onChange="update()">
<option value="" selected="selected">Choose no. of person referred</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// These are teh input where resultant value will appear <input type="text" value="" placeholder="Your weekly Income..." name="m_income" id="weekly_income" class="field" readonly required />
<input type="text" value="" placeholder="Your day Income..." name="y_income" id="day_income" class="field" readonly required/>
</div>
<!--elist-->
</body>
</html>
See this fiddle
Updated JS
function update() {
var x = document.getElementsByName("n_person")[0].value;
document.getElementsByName("m_income")[0].value = x * 5;
document.getElementsByName("y_income")[0].value = x * 4;
}
The problem with your JS was you was not targetting the correct HTML elements using getElementsByName.
Please read more about it here
The method getElementsByName returns, as its name indicates, a list of elements with the specified name and not just one. In your case, the names are unique to the document and the method will return a list with just one value, but you'll still need to index this list. Therefore, you must change this:
var x = document.getElementsByName("n_person").value;
to
var x = document.getElementsByName("n_person")[0].value;
Do this also for the other uses of getElementsByName and your code will work.

Using jquery-ui autocomplete in combination with dynamic form generation

I have a form that can be dynamically updated by using a js script based on this script. A select-list is dynamically generated to allow selection of an attribute for the dynamically generated field. However, the list contains hundreds of unique attributes and I therefore want to add a "search" box so selection is easier. I have been using the Jquery-ui autocomplete function and it works fine when the input box is outside the dynamically updated form, however, once I put it inside the form it does not work. The following div is dynamically inserted into the form:
<div id="readroot" style="display: none">
<select name="_name">
<option value="1">1</option>
<option value="2">2</option>
//many more options...
</select>
First text
<input type="text" size="15" name="xyz" /> Second text
<input type="text" size="15" name="xyz2" />
<input type="button" value="Remove trait" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
The form:
<form method="post" name="disForm" target="_blank" id="disForm">
<div id="writeroot"></div>
<input type="button" value="Add trait" onclick="moreFields();" />
</form>
And here is the script that adds new fields (the "readroot"div) to the "writeroot"-div:
<script type="text/javascript">
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
//newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
newField[i].title = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
}
window.onload = moreFields;
</script>
Here is the input and script for the autocomplete:
<input title="autocomplete" name="autocomplete">
<script>
$("[title^='autocomplete']").autocomplete({
source: ["...many values..."]
});
</script>
I'm using jQuery UI Autocomplete 1.11.4 from jqueryui.com. Just to repeat myself, this script works when it is outside the "readroot" div but not when it is inside the "readroot"-div. Why doesn't it work inside the "readroot" div?
Update I have corrected the code as suggested by pablito.aven. Adding other types of searchable lists such as chosenjs also works outside the 'readroot' div but not inside. The autocomplete script works like this:
<div id="readroot" style="display: none">
<select name="_name">
<option value="1">1</option>
<option value="2">2</option>
//many more options...
</select>
First text
<input type="text" size="15" name="xyz" /> Second text
<input type="text" size="15" name="xyz2" />
<input type="button" value="Remove trait" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
<input title="autocomplete" name="autocomplete">//input is outside readroot, Works!
<script>
$("[title^='autocomplete']").autocomplete({
source: ["...many values..."]
});
</script>
But not like this:
<div id="readroot" style="display: none">
<select name="_name">
<option value="1">1</option>
<option value="2">2</option>
//many more options...
</select>
First text
<input type="text" size="15" name="xyz" /> Second text
<input type="text" size="15" name="xyz2" />
<input type="button" value="Remove trait" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
<input title="autocomplete" name="autocomplete"> //input is inside 'readroot' Does not work :(
</div>
<script>
$("[title^='autocomplete']").autocomplete({
source: ["...many values..."]
});
</script>
I think I found your answer now.
When you add a new select with the function moreFields(), you take the code inside readroot and copy it before writeroot. You are copying the code, generating new elements. But, the script that generates the autocomplete has already been ran.
<script>
$("[title^='autocomplete']").autocomplete({
source: ["...many values..."]
});
</script>
So, the autocomplete will work only in the elements that were already there when the script is ran.
I might guess that if you remove the display:none from readroot, the autocomplete will work in it, but still won't work on the dynamically generated selects.
What you should have to do is to run that script again when you add more fields, so that it binds to the new generated fields. Something like this may probably work:
<script type="text/javascript">
function initializeAutocomplete(){
$("[title^='autocomplete']").autocomplete({
source: ["...many values..."]
});
}
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
//newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name;
if (theName){
newField[i].name = theName + counter;
newField[i].title = theName + counter;
}
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
initializeAutocomplete();
}
window.onload = moreFields;
</script>
I also added the {} to the if statement, and one or two semicolons that were missing.
If this works, I would be thankful if you upvote my answers. If it doesn't, we will have to keep trying.
For having a search box inside your <select>, I use angularJS, which automatically creates the search box and is quite easy and friendly.
Something like this would be
<select ng-app="moduleName" ng-controller="controllerName" name="_name" id="unique_id" class="chosen-select" required>
<option ng-repeat="x in options" value="{{x.val}}">{{x.name}}</option>
</select>
And you have to initialize it with javascript.
angular.module('moduleName', []).controller('controllerName', function($scope){
$scope.options = [
{val: 'value 1, 'name:'name 1'},
{val: 'value 2', name:'name 2'},
{val: 'value 3', name:'name 3'}
];
});
As your form loads dinamically, all you have to do is figure out how to fill the options inside the $scope variable in the controller from your js script
In order for this to work correctly, you have to include angularJS source code.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
If you want to understand more about how angularJS works, i recommend you reading about it here, it shouldn't take you too much time
There is a slight problem with your code <input type="button" id="moreFields" value="Add trait" onclick="init(this);" />
Here you call init function with a parameter. In it's definition it takes no parameters.
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
And, I don't understand why on that init function you are binding a on click event to #moreFields if you already have the onclick attribute in your html. Isn't that function unnecesary? Maybe you could just do <input type="button" id="moreFields" value="Add trait" onclick="moreFields();" />
Also, you have a html comment line (<!--) inside your <script></script> tags. I think you should remove it, it may be causing some trouble. If you want to comment javascript code you should do it with //commented line or /*commented block*/

Cannot get document.getElementById() to find my textarea

Maybe I've been working on my site for to long, but I can't get the following to work. I am having my textarea fire an onkeyup() event called limiter which is supposed to check the textarea and limit the text in the box, while updated another readonly input field that shows the amount of characters left.
This is the javascript code:
<script type="text/javascript">
var count = "500";
function limiter(){
var comment = document.getElementById("comment");
var form = this.parent;
var tex = comment.value;
var len = tex.length;
if(len > count){
tex = tex.substring(0,count);
comment.value =tex;
return false;
}
form.limit.value = count-len;
}
</script>
The form looks like this:
<form id="add-course-rating" method="post" action="/course_ratings/add/8/3/5/3"
accept- charset="utf-8"><div style="display:none;"><input type="hidden"
name="_method" value="POST" />
//Other inputs here
<div id="comment-name" style="margin-top:10px">
<div id="comment-name-text">
<b>Comments</b><br />
Please leave any comments that you think will help anyone else.
</div>
<style type="text/css">
.rating-form-box textarea {
-moz-border-radius:5px 5px 5px 5px;
}
</style>
<div class="rating-form-box">
<textarea name="data[CourseRatings][comment]" id="comment"
onkeyup="limiter()" cols="115" rows="5" ></textarea>
<script type="text/javascript">
document.write("<input type=text name=limit size=4
readonly value="+count+">");
</script>
</div>
<input type="submit" value="Add Rating" style="float: right;">
</form>
If anyone can help that would be great.
You have:
onkeyup="limiter()"
Since you aren't calling limiter in the context of an object, you are calling window.limiter.
var form = this.parent;
So this is window and form is window.parent, which is the same as window (unless the document is loaded in a frame).
You want to make this the form control. Do this using event binding in unobtrusive JavaScript.
(And don't use an input as an element solely for displaying output, it does not make sense. You probably want to use a label associated with the textarea … and to use another label for <b>Comments</b><br />Please leave any comments that you think will help anyone else.)
Would this work for your? Example Link
EDIT:
You should pass the element instance with the function call onkeyup="limiter(this)" this way in your function you'll have a reference to the object that called this function, now your function will be something like:
function limiter(a) {
var comment = a;
var form = document.getElementById('add-course-rating');
var tex = comment.value;
var len = tex.length;
if (len > count) {
tex = tex.substring(0, count);
comment.value = tex;
return false;
}
form.limit.value = count - len;
}
Also no need to create element dynamically if you don't really need that! so just set the value of the readonly with Javascript:
<input type="text" name="limit" id="limit" size="4" readonly value="">
<script type="text/javascript">
var limit = document.getElementById('limit');
limit.value = count;
</script>
And you are good to go!

Categories

Resources