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.
Related
I want the to get the required in the html page if none is selected.
function validation() {
var country = getElementById("country");
if (country.value = "") {
documnet.getElementById("countryy").innerHTML = "Required";
return false;
} else
return true;
}
<form onsubmit="return validation();">
<select id="country"><span id="countryy"></span>
</select><br>
<input type="submit" name="Submit" value="Submit">
</form>
Why The Validation is not working for the provided html/ js code. I want the to get the required in the html page if none is selected. I am new to js learning.
Several issues
Spelling mistake in the document.getElementById
missing document on the other document.getElementById
No preventDefault which will submit the form if any JS errors
= is assignment - you need == or === to compare
span needs to be outside the select
You did not use value="Default" in the "NONE" options
It is not recommended to have inline event handlers. Here is a better version
Note I added a class to toggle the required in case the user changes the select to conform
window.addEventListener("load", function() {
const errorSpan = document.getElementById("countryy"); // cache the elements
const country = document.getElementById("country");
document.getElementById("myForm").addEventListener("submit", function(e) {
const val = country.value; // get the value
if (val === "") {
e.preventDefault(); // stop submit
}
errorSpan.classList.toggle("hide",val); // hide if value
})
country.addEventListener("change",function() { // if user changes the select
errorSpan.classList.toggle("hide",this.val); // hide if value
})
})
.hide { display : none; }
<form id="myForm">
<select id="country">
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select> <span id="countryy" class="hide">Required</span><br>
<input type="submit" name="Submit" value="Submit">
</form>
HOWEVER you could remove all the script and just add required attribute to the select and keep the empty default
<form id="myForm">
<select id="country" required>
<option value="">NONE</option>
<option value="ABDUL">ABDUL</option>
<option value="SULE">SULE</option>
</select><span id="countryy"></span><br>
<input type="submit" name="Submit" value="Submit">
</form>
Use required attribute in the select tag. It will considered in html 5 validation.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_select_required
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*/
This is a very simple select bar. Why is it not working?
<html>
<form>
<label>
<select id="sel1">
<option> op1 </option>
<option> op2 </option>
<option> op3 </option>
</select>
<input onclick="s()" type="submit" value=" ok! ">
</label>
</form>
<script>
function s(){
document.getElementById("sel1").innerHTML += "<option> op4 </option>";
}
</script>
</html>
If I want people to add new option, I need to put some variable on it. How can I add php variable instead of op4, op5, etc?
Create an actual option element and append it to the select element.
var option = document.createElement("option");
option.value = "op4";
option.innerHTML = "op4";
var select = document.getElementById("sel1");
select.appendChild(option);
You should probably be using value attributes in your options too.
This is the next question. Then if i want people to add new option , i need to put some php variable on it. how can i add php variable instead of op4 , op5 and... options?
No, this has nothing to do with PHP.
<input id="option-name">
Using the example above, instead of using a fixed "op4", use the value from the input
var input = document.getElementById("option-name");
var option = document.createElement("option");
option.value = input.value;
option.innerHTML = input.value;
var select = document.getElementById("sel1");
select.appendChild(option);
Now the input value will be used as the name/value for the new option
Change this:
<input onclick="s()" type="submit" value=" ok! ">
To this:
<input onclick="s()" type="button" value=" ok! ">
Using type="submit" will result in your form being submitted and thus your page being reloaded. Using type="button" prevents this.
What happens is the form is submitted and as the form element doesn't have action attribute the current page is reloaded.
You should listen to submit event and prevent the default action of the event using preventDefault method of the event object.
document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault();
var option = new Option('optionText', 'optionValue');
document.getElementById("sel1").add(option);
});
Another option is using a button element with type attribute of button instead of a submit input.
Try this:
<script>
function s(){
var o=new Option();
o.value="<?php echo $option; ?>";
o.text="<?php echo $option; ?>";
var os=document.getElementById("sel1").options;
os[os.length]=o;
}
</script>
I finally write completed Answer. In 2 ways; The first way is safer than another. first way is :
<html>
<form>
<label>
<input type="text" id="option-name">
<select id="sel1">
<option> Option1 </option>
<option> Option2 </option>
<option> Option3 </option>
</select>
<input onclick="s()" type="button" value=" Create ! "><br/><br/>
</label>
</form>
<script>
function s(){
var input = document.getElementById("option-name");
var option = document.createElement("option");
option.value = input.value;
option.innerHTML = input.value;
var select = document.getElementById("sel1");
select.appendChild(option);
}
</script>
</html>
That is other guys answer too. But the second way is easier and useful. not safer (I think innerhtml is not so safe for this purpose! but if I wrong , please tell me.)!
<html>
<form method="post" action="index.php">
<label>
<input type="text" name="txt1">
<select id="sel1">
<option> Option1 </option>
<option> Option2 </option>
<option> Option3 </option>
</select>
<input type="submit" value=" Create ! ">
</label>
</form>
<script>
document.getElementById("sel1").innerHTML += "<option><?php echo $_POST['txt1']; ?></option>";
</script>
My code is as follows:
<!DOCTYPE html>
<html>
<body>
<script>
function tab()
{
current=document.getElementById("test");
next=document.getElementById("run");
if(current.value!="-1")
{
next.focus()
}
}
</script>
<select id="test" onchange="tab()">
<option value="-1">--select--</option>
<option value="1" >TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" name="run"/>
</body>
</html>
Definition: I have a dropdown which is having four values. If I change one value to another value in the dropdown it autotab to the textbox. As per my code, it is working fine.
But the issue is when I select 1st value in the dropdown then the autotab is working and again I select the same value from the dropdown (autotab is not working). I know that the problem is in the event. There is no change so the event won't fire. Please help me to rectify the issue.
There is no element with id run, which is being referenced by:
document.getElementById("run");
You probably intended to write:
<input type="text" name="run" id="run"/>
Use onBlur() instead of onchange().
The onBlur event is fired when you have moved away from an object without necessarily having changed its value.
The onChange event is only called when you have changed the value of the field.
please have a lookinto this to know about events
Try using mouseup & keyup event as a work around:
var current = document.getElementById("test");
var next = document.getElementById("run");
var open = false; //drop-down closed
var watchOpen = function() {
open = !open; //inverse flag to identify state of drop-down
};
var tab = function() {
if (!open && current.value !== "-1") {
next.focus();
}
};
<select id="test" onmouseup="watchOpen();tab();" onkeyup="watchOpen();tab();">
<option value="-1">--select--</option>
<option value="1">TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" id="run" /><!-- replaced name with id -->
try to use onBlur() .It will solve the problem
I think this is possible with html5
onselect
Try this :
<!DOCTYPE html>
<html>
<body>
<select id="test" onchange="tab()">
<option value="-1">--select--</option>
<option value="1">TEST</option>
<option value="2">RUN</option>
</select>
<input type="text" name="run" id="run" />
<script type="text/javascript">
function tab() {
current = document.getElementById("test");
next = document.getElementById("run");
if (current.value != "-1") {
next.focus();
next.value = current.options[current.selectedIndex].text;
} else {
next.value = "";
}
}
</script>
</body>
</html>
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>