Event Handling when option is selected from dropdown menu - html

I have a form wherein I have to select an item from the drop down menu and display the selected value on the form. The values in the dropdown menu come from the database.
Here is my code of select:
<aui:select id="empName" name="empName" onChange = "showEmpName()">
<%
List<Employee> EmpList = EmployeeLocalServiceUtil.getEmployees(-1,-1);
for(Employee emp : EmpList ) {
%>
<aui:option value='<%=emp.getEmpFname()%>' name = "leaveEmp" onClick = "showEmpName()"><%=emp.getEmpFname()%> <%=emp.getEmpLname()%></aui:option>
<% } %>
Here is the script: the value selected from drop down should be displayed on the form
<script>
function showEmpName()
{
var empName = document.getElementById("empName")
var showEmpName = document.getElementById("showEmpName")
showEmpName.value = empName.value
alert("my name is" + empName)
}
</script>
I have a couple of questions regarding this:
onchange onclick aren't working.
Secondly I want to display the selected item on the form.
How should I approach?
EDIT:
I even tried the following but it doesn't work at all.
<script>
var selectedEmpName = document.getElementById('empName');
var absentEmp = document.getElementById('absentEmp');
selectedEmpName.onchange = function() {
absentEmp.value = selectedEmpName.value;
};
</script>
<aui:select id="empName" name="empName">
<%
List<Employee> EmpList = EmployeeLocalServiceUtil.getEmployees(-1,-1);
for(Employee emp : EmpList ) {
%>
<aui:option value='<%=emp.getEmpFname()%>' name = "leaveEmp"><%=emp.getEmpFname()%> <%=emp.getEmpLname()%></aui:option>
<% } %>
</aui:select>
The above code I am trying to display in a non editable text box.
What I actually want is once the value from drop down is selected it should be displayed as the value of the radio button which already exists. once the value of this radio button is set, it will be used for further processing.
EDITCODE:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
$(document).ready(function(){
$('#empName').change(function(){
var value = $(this).val();
console.log(value);
$('label').text(value);
});
});
</script>
</head>
<body>
<portlet:actionURL name="markAbsent" var="markAbsentURL" />
<aui:form name="markAbsent" action="<%=markAbsentURL.toString() %>" method="post" >
<aui:select id="empName" name="empName" >
<%
List<Employee> EmpList = EmployeeLocalServiceUtil.getEmployees(-1,-1);
for(Employee emp : EmpList ) {
%>
<aui:option value='<%=emp.getEmpFname()%>'><%=emp.getEmpFname()%> <%=emp.getEmpLname()%></aui:option>
<% } %>
</aui:select>
<label for="empName" id = "labelname"></label>
</aui:form>

Say you have the following html
<select id="mySel">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
</select>
<label for="mySel">
</label>
And you use jQuery, then you should be able to listen to selections by
// attach a ready listener to the document
$(document).ready(function(){ // ran when the document is fully loaded
// retrieve the jQuery wrapped dom object identified by the selector '#mySel'
var sel = $('#mySel');
// assign a change listener to it
sel.change(function(){ //inside the listener
// retrieve the value of the object firing the event (referenced by this)
var value = $(this).val();
// print it in the logs
console.log(value); // crashes in IE, if console not open
// make the text of all label elements be the value
$('label').text(value);
}); // close the change listener
}); // close the ready listener
Working example: http://jsbin.com/edamuh/3/edit
Or you could also do it with basic javascript, by putting the following after the generated select & label:
<script type="text/javascript">
var sel = document.getElementById('mySel');
var lbl = document.getElementById('myLbl');
sel.onchange = function(){
lbl.innerHTML = this.options[this.selectedIndex].value;
};
</script>
Working example here: http://jsbin.com/edamuh/7/edit
Note: The latter might not work equally in all browsers.
Eg. Works in Firefox(Windows) but might not in others. Thus I'd suggest opting for using jQuery.
EDIT
In your case the markup should be something like (no onChange):
<aui:select id="empName" name="empName" >
<!-- options -->
</aui:select>
<label id="myUniqueLabelId"></label>
<script type="text/javascript">
$(document).ready(function(){
// assigns a listener to 1 or more select elements that contains empName in their id
$('select[id*=empName]').change(function(){
// when the change event fires, we take the value of the selected element(s)
var value = $(this).val();
// take an element with the exact id of "myUniqueLabelId" and make its text be value
$('#myUniqueLabelId').text(value);
// take the reference to a radio input
var radio = $('#radioId');
// make it enabled
radio.prop('checked', true);
});
});
</script>
Working example with radio buttons:
http://jsbin.com/edamuh/12/edit
It is important to notice, that when the document loads the select must have been already rendered, otherwise the script won't work.

Related

How to stop refreshing the select box option after pressing OK button

I have created a UI Page in Servicenow below is my simple HTML snipped that creates a Select box and a OK button
Now i selected the select box as Mango and i typed ok, once i click on ok it is setting the value but when i refresh the browser it going to back to previous view. how to keep the same option which user select until user changes it
function validation(){
var value=document.getElementById("selectedValue").value;
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
<div class="container">
<div class="row">
<div class="form-group" style="margin-top:12px;">
<select class="form-control" name="selectedValue" id="selectedValue" style="width:150px;">
<option value="disabled selected">Choose your option</option>
<option value="1" >Mango</option>
<option value="2">Orange</option>
<option value="3">Grapes</option>
</select>
<!--<h4 id="number_of_updates" style="display:none"><span class="label label-danger"></span></h4> -->
</div>
<button type="button" class="btn btn-primary" onclick="validation()" style="padding: 0px 8px;">Ok</button>
</div>
</div>
It is working as required, when i refresh the browser it will be set to Choose your option. Can anyone please help me how to save the selected value till it is changed
To achieve the desired result I would use localStorage.
I would set localStorage item inside your validation() function:
function validation(){
var value=document.getElementById("selectedValue").value;
localStorage.setItem('MyValue', value);
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
Note, that I'm setting it to selected value from selectList.
Then we need to retrieve this saved value on page load(in case someone refreshes the page):
window.onload = function (){ //function that is called when your page
var selectList = document.getElementById('selectedValue');
var stored = localStorage.getItem('MyValue');
console.log(stored);
if(stored && selectList){
selectList.value = stored //setting saved value to as selected in selectList
}
}
EDIT: Even though localStorage is supported by majority of browsers, its is recommended to check if its accessible. Like if (typeof localStorage !== 'undefined') ...
There's several ways to keep state across refresh. localStorage is obvious choice but maybe an easier solution for your case may be encoding the state in the URL like this (basically the same way web apps keep some of their state).
Insert this code at the end inside validation() function:
history.pushState(null, '', '?val=' + value);
Insert this code after that function:
window.onload = function() {
var params = new URLSearchParams(location.search);
var value = params.get('val') || 'disabled selected';
var select = document.getElementById('selectedValue');
if (select) select.value = value;
}
That's it. Notes: URLSearchParams doesn't work on IE, instead it's not hard to parse the query by hand.

Select menu to pass variable to function to change innerhtml

I'm making a sidebar page for an add-on in Google Sheets.
The user will select a topic from a select menu (drop down), which will then change the inner html of div to display a different help topic.
So far the variable passed along is what gets displayed. I want the contents of the variable to be displayed as html.
I was able to make this work from text links, but they took up too much space in the sidebar, so I went to a select menu.
I made a simpler sample than my actual help sidebar so there would be less code to look at:
<!DOCTYPE html>
<html>
<body>
<p>Select a choice from the list.</p>
<select id="topic" onchange="showContent(this.value)">
<option value="choice1">This one</option>
<option value="choice2">the next one</option>
<option value="choice3">Yet another</option>
</select>
<p>When you select a choice, the output should change based on the value of the variable passed.</p>
<p id="helpContent">Results go here</p>
<script>
//VARS
var choice1 = '<ul><li>This is the first choice<li></ul>';
var choice2 = '<ul><li>This is the second choice<li></ul>';
var choice3 = '<ul><li>This is the, like, third choice<li></ul>';
function showContent(topic) {
document.getElementById("helpContent").innerHTML = topic;
}
</script>
</body>
</html>
Use a data structure to represent your elements, and then create them accordingly
<!DOCTYPE html>
<html>
<body>
<p>Select a choice from the list.</p>
<select id="topic" onchange="showContent(this.value)">
<option value="choice1">This one</option>
<option value="choice2">the next one</option>
<option value="choice3">Yet another</option>
</select>
<p>When you select a choice, the output should change based on the value of the variable passed.</p>
<p id="helpContent">Results go here</p>
<script>
var choices = {
"choice1": {
list: ["item1", "item2", "item3"]
},
"choice2": {
list: ["item1"]
},
"choice3": {
list: ["item3"]
},
}
function showContent(topic) {
var currentChoice = choices[topic];
if (currentChoice == null)
return alert("Invalid choice");
var newList = document.createElement('ul');
for (var i = 0; i < currentChoice.list.length; i++) {
var newListItem = document.createElement('li');
newListItem.innerText = currentChoice.list[i];
newList.appendChild(newListItem);
}
var sidebarContainer = document.getElementById("helpContent");
sidebarContainer.innerHTML = "";
sidebarContainer.appendChild(newList);
}
window.onload = function() {
showContent("choice1");
}
</script>
</body>
</html>

HTML Form: Other input required ONLY if other is selected

I'm currently working on a form with a bunch of options. On some of the questions, there is an "Other" option for the user to type in whatever they choose. I am trying to make it appear only "Other" is selected (I've gotten this to work on the first question but not the others). I am also trying to make this input required ONLY if they select it, so that they can't submit the form having selected "Other" and left it blank.
Here is my HTML and the Javascript for making the other text inputs appear when selected:
<label for="Accom">Question</label>
<table>
<tr>
<td><select name="Accom">
<option value="">Select...</option>
<option value="Handicapped">Handicap Accessibility</option>
<option value="Hearing Impaired">Hearing Impaired</option>
<option value="Visually Impaired">Visually Impaired</option>
<option value="OtherAccom">Other</option>
</select>
</td>
</tr>
<tr>
<td colspan="4">
<label style="" id="other">If Other, Please Specify
<input type="text" name="Other_Accom" size="20"></label></td><tr></table>
.
window.onload=function() {
var other = document.getElementById('other', 'otherAccom','otherDiet');;
other.style.display = 'none';
document.getElementsByName('Title', 'Diet', 'Accom')[0].onchange = function() {other.style.display =(this.value=='Other')? '' : 'none'};
I'm also trying to get a this to work for a checkbox form.
<label for="Interests">Question</label><br>
<input class="checkbox2" TYPE="checkbox" NAME="formInterests[]" required value="Use Cases ||" />Use Cases<br>
<input class="checkbox2" TYPE="checkbox" NAME="formInterests[]" required value="Other" />Other<br>
<label style="" id="other">If Other, Please Specify
<input type="text" name="Other_Interests" size="20"></label>
Thank you very much!
EDIT 1: When I try and duplicate the function, it stops working for everything.
window.onload=function() {
var other = document.getElementById('other', 'otherAccom', 'otherDiet');;
other.style.display = 'none';
document.getElementsByName('Title')[0].onchange = function() {other.style.display = (this.value=='Other')? '' : 'none'};
};
window.onload=function() {
var otherDiet = document.getElementById('other', 'otherAccom', 'otherDiet');;
otherDiet.style.display = 'none';
document.getElementsByName('Diet')[0].onchange = function() {otherDiet.style.display = (this.value=='OtherDiet')? '' : 'none'};
};
document.getElementsByName('Title', 'Diet', 'Accom')[0].onchange = function() {other.style.display =(this.value=='Other')? '' : 'none'};
This selects an array of elements, which you then access by [0], meaning you target the first element (which will be the first of the three that appears in the DOM), and add the onChange listener to it.
This results, as you said yourself:
(I've gotten this to work on the first question but not the others)
Because you actually only run the code on one of the three elements.
You should instead use something like:
document.getElementsByName('Title', 'Diet', 'Accom').forEach(function(element) {
element.onChange = function() {
var target = document.getElementById('Other'+this.name);
if(this.options[this.selectedIndex].value=='Other') {
target.style.display = 'block';
} else {
target.style.display = 'none';
}
};
});
The basic idea is using a forEach to loop through ALL your desired elements, rather than just one of them.
Keep in mind that:
<option value="OtherAccom">Other</option>
does not have value="Other", but value="OtherAccom". Make sure your javascript and html are consistent with eachother.
you can use IDs only once on a page ("other")
you need to rename those other "others" and create seperate functions for them

How to get data into html checkbox list, taken from javascript function call

I have a page which assign some values to arrays when a function named 'hndlr' is called.code of the file is given bellow
<html>
<head>
<title>Search Example</title>
</head>
<body>
<script>
var pageName = new Array();
var pageLink = new Array();
var pageDetails = new Array();
function hndlr(response) {
// here I assign values to arrays pageName,pageLink,pageDetails using a for loop
}
// Some codes (I cant change anything in here)
// call the function hndlr here (I cant change anything in here)
</script>
</body>
</html>
I want to take pageName array into a checkbox list and pass the pageLink of selected checkboxes to another file.
I tried using bellow code just before the end of the body tag. but it isn't passing any data to next page(b.php)
<form action="b.php" method="post">
<script>
for (var j = 0; j < 5; j++) {
document.write("<input type='checkbox' name='formDoor[]' id='"+j+"' value= '' />"+pageName[j]+"<br />");
document.getElementById(j).value = pageLink[j];
}
</script>
<input type="submit" name="formSubmit" value="Submit" />
</form>
When I print the output, It displays 'undefined' strings just before the check boxes.
That means pageName[j] doesn't return any value.
problem is, these arrays are not visible to second part(part I tried with check boxes)
Please show me the way to do this..
Weird, your code is working for me (click the code box to show it): http://codepad.viper-7.com/4IVobE
You can't submit the form on this site but you can see that the arrays are accessible within the second script tag. I also tried it on my local server and after submitting the form I was able to access the values in b.php just fine.

How to make HTML combo box save values added by user in textbox?

I have made a combobox for a web page. It takes values from user into text box & adds those to list on double click in text box. I want to make user entered values permanently stored as option in list. How can I do it. One more question is how can I count the number of options in list so that I add an element next to that.
Here is my code.
<html>
<head>
<script language="javascript">
function AddListItem(form)
{
var TestVar = form.txtInput.value;
form.txtInput.value = "";
form.select.options[3]=new Option(TestVar, TestVar, true);
}
</script>
<head>
<body>
<form id='Form1'>
<input id='txtInput' type='text' maxlength = "5" size="5" ondblclick="AddListItem(this.form)"/>
<p>
<select id='select'>
<option>abc</option>
<option>cde</option>
<option>efg</option>
</select>
</form>
</body>
</html>
To permanently add you need a server-side script.
To temporarily add you can use javascript:
function addVal(newVal) {
var sel = document.getElementById('select');
var opt = document.createElement("OPTION");
sel.addChildNode(opt);
opt.innerHTML = newVal;
opt.value = newVal; //(alternatively)
}
To count the number of options:
function countOpts() {
var sel document.getElementById('select');
return sel.options.length;
}
(only for conceptual use, not tested as functional)
You add an <option> dynamically like this:
function add(selectId, optText, optValue)
{
var newOption = document.createElement("option")
newOption.text = optText;
newOption.value = optValue;
document.getElementById(selectId).options.add(newOption);
}
selectId is the id of <select>, optText is the text to be displayed in the dropdown and optValue is the value that will be sumbitted to the server.
For your code, call it as
<input id='txtInput' type='text' maxlength = "5" size="5" ondblclick="add('select', this.value, this.value)"/>
As you see, you don't really need to find the length of the options, but you can do it via options.length:
document.getElementById(selectId).options.length;
That said,
You might want to add this to the
dropdown, as well as to pass to the
server, to add to some table, for
instance. You might have to do that
call via AJAX, when you add it to
the dropdown
Adding the new item
on double click of the textbox is
not very usable. On blur might be an
option. Better is an 'Add' button after the
textbox .
Sounds like you need a server-side script then. When you submit the form, you can have a field that is 'remembering' all of the dropdown options:
The simplified HTML:
<form method='post' action=''>
<input name='newDDoption' />
<input type='hidden' name='ddStorage' value='<?PHP echo implode("|||",$ddOptions); ?>' />
<button>GO</button>
</form>
The simplified PHP:
<?PHP
$ddOptions = explode("|||",$_POST['ddStorage']);
$ddOptions[] = $_POST['newDDoption'];
echo "<select>";
for($x=0;$x<count($ddOptions);$x++) {
echo "<option>".$ddOptions[$x]."</option>";
}
echo "</select>";
?>
To explain: PHP saves the ddOptions in the form -> User enters new option -> The form is submitted -> PHP finds the stored values -> PHP pushes on the new value -> PHP loops through and creates your permanent dropdown menu.