I have an array in Javascript that consists of three different countries. I have a form in my HTML page that contains a drop down box. Instead of populating the drop down box using
<option value=""> *option name* </option>,
I want to try including the elements of my array in my drop down box, so when the user clicks it, they'll see the elements.
var countries=["Sri Lanka","Bangladesh","India"]
I tried using the 'onclick' function in my HTML so that it would link to this following function
function myFunction() {document.getElementById('Bangladesh').innerhtml= (countries[2])>
But I since removed it since it didn't work. How exactly can I populate the drop down box with elements from my array. My JS and HTML code have been provided below.
<DOCTYPE html>
<head>
<script src="inquiries.js"> </script>
</head>
<body>
<h1 align="center"class='header1'> <font size="8"> </font> </h1>
<div class="busybox">
<form name="myForm" form action="/action_page.php" onsubmit="return validateForm();" method="post">
<label for="fname"> <b> First Name </b> </label>
<input type="text" id="fname" name="firstname" placeholder="Your name......"
required >
<label for="Birthday"> <b> E-Mail </b> </label>
<input type="text" id="email" name="email" placeholder="Enter your E-mail address....." >
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
<option value="Sri Lanka"> Sri Lanka </option>
<option value="India"> India </option>
<option value="Bangladesh"> <p id="bangladesh"> </p> </option>
</select>
<label for="summary"> <b> Summary </b> </label>
<textarea id="summary" name="Summary" placeholder="Write a summary of your inquiry
here...." style="height:200px"> </textarea>
<input type="submit" value="submit" id="sbox" onclick="myfunction()">
</form>
----JS CODE----
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}else{
return true;
} }
var countries = ["Sri Lanka", "India", "Bangladesh"];
function myFunction() {document.getElementById('Bangladesh').innerhtml =(countries[2])>
var countries=["Sri Lanka","Bangladesh","India"];
document.getElementById("Select").innerHTML = "";
for(var i=0;i<countries.length;i++)
{
var node = document.createElement("option");
var textnode = document.createTextNode(countries[i]);
node.appendChild(textnode);
document.getElementById("Select").appendChild(node);
}
<select id="Select"></select>
Here is a solution using array#foreach.
var select = document.getElementById("selectCountry");
var countries = ["Sri Lanka", "India", "Bangladesh"];
countries.forEach((country) => {
var element = document.createElement("option");
element.textContent = country;
element.value = country;
select.appendChild(element);
});
<select id="selectCountry"></select>
Try this:
$('#country').change(function(){
var dropdown=document.createElement('select');
var options="";
for(i = 0; i < countries.length; i = i+1){
options+= "<option value='"+countries[i]+"'>"+countries[i]+"</option>";
}
dropdown.innerHTML= options;
document.getElementById('country').appendChild(dropdown);
});
To do it with jQuery:
$(document).ready(function() {
var select = $('#country');
var countries = ["Sri Lanka", "India", "Bangladesh"];
for (var i=0; i<countries.length; i++) {
var country = countries[i];
var el = $("<option value='" + country + "'>" + country + "</option>");
$(select).append(el);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Label for="country"> <b> Country </b> </Label>
<select id="country" name="country">
Related
I am trying to detect if an HTML FORM in a web page contains ComboBox or List. . I could detect all the rest and here are my efforts so far. As you can see, the ComboBox is not detected. I understand its not an input control. Is there any other way to do this?
MY SAMPLE CODE:
<html>
<head>
<script language="javascript" type="text/javascript">
function detectTypes() {
var str = document.getElementById("Select1").value;
var inputs = document.querySelectorAll('input');
var inputtype = document.getElementsByTagName ("input");
for(i =0; i < inputs.length; i++)
{
//Output result to console
console.log("The " + i + ". input type = " + inputs[i].type);
//Output result to multiline textbox
var s = inputs[i].type;
document.getElementById('output').value += s.substring(s.length - 10) + '\n';
}
}
</script>
</head>
<body>
<form name="form1" id="form1" method="">
<p>
<label>TextBox </label>
<input type="text" id="Name">
</p>
<p>
<label>Password</label>
<input type="password" id=phone>
</p>
<p>
<label>Dropdown Comobox</label>
<select name="Options" id="Select1">
<option value="Jack,12345">Jack</option>
<option value="John,45678">John</option>
<option value="Tom,98765">Tom</option>
</select>
</p>
<P>
<label>CheckBox</label>
<input type="checkbox" id="check1">
<p>
<label>Radio Button</label>
<input type="radio" id="Option1" name="Option1" value="">
<p>
<label>Color Box</label>
<input type="color" name="ColorCode" id="color-picker">
</form>
Click to List types of controls
<p>
<label>RESULT:</label>
<textarea name="output" id="output" rows="7" cols="30"></textarea>
</p>
</body>
</html>
I would praise your work becse it is very creative
I have solved your problem
<html>
<body>
<form name="form1" id="form1" method="">
<p>
<label>TextBox </label>
<input type="text" id="Name">
</p>
<p>
<label >Password</label>
<input type="password" id="phone">
</p>
<p>
<label>Dropdown Comobox</label>
<select name="Options" id="Select1">
<option value="Jack,12345">Jack</option>
<option value="John,45678">John</option>
<option value="Tom,98765">Tom</option>
</select>
<input type="hidden">
</p>
<P>
<label>CheckBox</label>
<input type="checkbox" id="check1">
<p>
<label>Radio Button</label>
<input type="radio" id="Option1" name="Option1" value="">
<p>
<label>Color Box</label>
<input type="color" name="ColorCode" id="color-picker">
</form>
Click to List types of controls
<p>
<label>RESULT:</label>
<textarea name="output" id="output" rows="7" cols="30"></textarea>
</p>
</body>
</html>
/*
//* user script
function detectTypes() {
//var str = document.getElementById("Select1").value;
var inputs = document.querySelectorAll('input');
var inputtype = document.getElementsByTagName("input");
for(i =0; i < inputs.length; i++)
{
//Output result to console
//console.log("The " + i + ". input type = " + inputs[i].type);
//Output result to multiline textbox
var s = inputs[i].type;
document.getElementById('output').value += s.substring(s.length - 10) + '\n' ;
}
} */
function detectTypes(){
// const inputtype = { "'SELECT'" : 'Dropdown' , 'OPTION' : 'Combo Box'} // I wish, it would work as alert(inputtype.SELECT) will show deopdown
var inputs = document.querySelectorAll("input, select");
var s = "hi";
for(i=0;i<=inputs.length;i++){
var tagnames = inputs[i].tagName;
if(tagnames == "INPUT"){
document.getElementById('output').value += inputs[i].type + '\n';
}else{
document.getElementById('output').value += tagnames.toLowerCase() + '\n';
}
}
}
setTimeout(detectTypes, 1);
I would be glad if you contact. I have to discuss further about this problem. Contact me libertmahin#gmail.com
I have two data list in the below snippet and the values of the selected option should be shown beside them.
My First(Account) one is working properly, but second(Head) one is not working. The value is not getting selected for Head.
/*List function starts*/
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
/*List function ends*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="accntid">Account: </label>
<input id="accntid" name="taccntlist" list="accnt_list" value="" placeholder="Account" required />
<datalist id="accnt_list">
<option data-value="001">Dummy1</option>
<option data-value="0000000">Dummy</option>
</datalist>
<input type="text" name="txtaccnt" id="accntid-hidden" readonly>
<br /><br /><br />
<label for="headid">Head: </label>
<input id="headid" name="txtheadlist" list="head_list" value="" placeholder="Head" required />
<datalist id="head_list">
<option data-value="1">d1</option>
<option data-value="0000000000">dummy</option>
</datalist>
<input type="text" name="txthead" id="headid-hidden" readonly>
<br /><br /><br />
I changed your js code, and added method forEach(), having previously declared the call to the inputs like this:
let inputs = document.querySelectorAll('input[list]');
This means that e.target is no longer necessary to use.
let inputs = document.querySelectorAll('input[list]');
inputs.forEach(function(current, index) {
current.addEventListener('input', function() {
list = current.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(current.getAttribute('id') + '-hidden'),
inputValue = current.value;
hiddenInput.value = inputValue;
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="accntid">Account: </label>
<input id="accntid" name="taccntlist" list="accnt_list" value="" placeholder="Account" required />
<datalist id="accnt_list">
<option data-value="001">Dummy1</option>
<option data-value="0000000">Dummy</option>
</datalist>
<input type="text" name="txtaccnt" id="accntid-hidden" readonly>
<br /><br /><br />
<label for="headid">Head: </label>
<input id="headid" name="txtheadlist" list="head_list" value="" placeholder="Head" required />
<datalist id="head_list">
<option data-value="1">d1</option>
<option data-value="0000000000">dummy</option>
</datalist>
<input type="text" name="txthead" id="headid-hidden" readonly>
<br /><br /><br />
How to Enable/Disable input field based on a dropdown selection. and also I should take the user data in JSP based on the selection.
<form action="../jsp/findActorbyChar.jsp">
<h3>Search by:
<select name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input type="text" name="firstName"/>
Last Name <input type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
Modified Html as shown below:
<h3>Search by:</h3>
<select name ="nameField" id="nameField">
<option>Only FirstName</option>
<option>Only LastName</option>
<option>Or</option>
<option>And</option>
</select>
<br><br>
First Name <input type="text" name="firstName" id="firstNameInput"/>
Last Name <input type="text" name="lastName" id="lastNameInput" />
<br><br>
<input type="submit"/>
<input type="reset"/>
Javascript code:
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
But I think it would be easier if using JQuery to handle DOM update.
Give your menu an id and then you can access the selected index with menu.options.selectedIndex. From there, you can add an on change handler to the menu and use switch cases to set the disabled attribute of the menu.
<h3>Search by:
<select id="menu" name ="nameField"> </h3>
<option> Only FirstName </option>
<option> Only LastName </option>
<option> Or </option>
<option> And </option>
</select>
<br><br>
First Name <input id="first" type="text" name="firstName"/>
Last Name <input id="last" type="text" name="lastName"/>
<br><br>
<input type="submit"/>
<input type="reset"/>
<script type="text/javascript">
var menu = document.getElementById('menu');
var first = document.getElementById('first');
var last = document.getElementById('last');
menu.onchange = function(){
var enableFirst = false, enableLast = false;
switch(menu.options.selectedIndex){
case 0:
enableFirst = true;
enableLast = false;
break;
case 1:
enableFirst = false;
enableLast = true;
break;
case 2:
/*not sure which results you want here*/
break;
case 3:
/*not sure which results you want here*/
break;
default:
break;
}
first.disabled = !enableFirst;
last.disabled = !enableLast;
}
</script>
My code: still all the input fields are enabled
enter code here
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
<script src="script.js">
var nameField = document.getElementById("nameField");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
nameField.addEventListener("change", function(){
//Update this to your logic...
if(nameField.value === "And"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
else if(nameField.value === "firstNameInput"){
firstNameInput.disabled = false;
lastNameInput.disabled = true;
}
else if(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = false;
}
elseif(nameField.value === "lastNameInput"){
firstNameInput.disabled = true;
lastNameInput.disabled = true;
}
});
</script>
What I'm trying to do is to redirect people to a link depending of what they have summited on the form (the link is built using the values from the form fields)
This is the Form:
<form id="form">
<div class="formbox">
<div class="radio-toolbar">
<input type="radio" id="iconapp1" name="department" value="1250"/>
<label for="iconapp1">PP</label><br>
<input type="radio" id="iconapp2" name="department" value="944"/>
<label for="iconapp2">EP</label><br>
</div>
<div class="radio-bar1">
<input type="radio" id="enginemake1" name="enginemake" value="6"/>
<label for="enginemake1"> Chevrolet</label><br>
<input type="radio" id="enginemake2" name="enginemake" value="8"/>
<label for="enginemake2"> Chrysler</label><br>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar3">
<select name="powerrange">
<option id="powerrange1" value="28">100</option>
<option id="powerrange2" value="128">200</option>
<option id="powerrange3" value="228" selected>300</option>
</select>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar4">
<input type="radio" id="location1" name="location" value="store"/>
<label for="location1"> America (NT - ST)</label><br>
<input type="radio" id="location2" name="location" value="store.au"/>
<label for="location2"> Australia and Oceania</label><br>
</div>
<div class="radio-bar2">
<input onclick="goToPage();" type="button" class="buttonmyapp" value="Submit" />
</div>
</div>
</form>
The link I'm trying to build using the values selected will look like this:
http://{location}.mydomain.com/product-catalog.aspx?section=-{department}-{enginemake}-{powerrange}-
Each bracketed section needs to be replaced by the value of the select with the corresponding name.
First include the jquery library link or download js and link
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function goToPage(){
var location = $('input[name=location]:checked').val();
var department = $('input[name=department]:checked').val();
var enginemake = $('input[name=enginemake]:checked').val();
var powerrange = $('select[name=powerrange]').val();
window.location.href = "http://"+location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
}
</script>
After the goToPage function on the submit button validates the response change the src attribute of the form should work fine.
So in jQuery it should look something like
var location = $('input[name=location]:checked', '.radio-bar4').val();
var dept = $('input[name=location]:checked', '.radio-bar4').val();
var engine = $('input[name=enginemake]:checked', '.radio-bar1').val();
var power = $('powerrange').val() ;
var domain = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+dept+"-"+engine+"-"+power+"-";
$("#form").attr("action", domain);
you can try this
HTML
<select id="powerrange" name="powerrange">
JAVASCRIPT
function goToPage()
{
var location;
var department;
var enginemake;
var powerrange;
pName = document.getElementById('powerrange');
powerrange = pName.options[pName.selectedIndex].value;
var form = document.getElementById('form');
var ele = form.getElementsByTagName('input');
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute('type')=='checkbox')
{
if(ele[i].getAttribute('name')=='department')
{
if(ele[i].checked)
department = ele[i].value;
}
else if(ele[i].getAttribute('name')=='enginemake')
{
if(ele[i].checked)
enginemake = ele[i].value;
}
else if(ele[i].getAttribute('name')=='location')
{
if(ele[i].checked)
location = ele[i].value;
}
else;
}
}
var url = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
form.setAttribute('action',url);
form.submit();
}
i want a particular array item to set as the value of input tag, when the combo1 box's selection changes.
<%# page language="java" import="java.util.*;" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<script language="javascript">
function check()
{
if(!validate())
return false;
}
function validate()
{
if (document.form.amount.value <=0)
{
alert ("Please enter valid loan amount.");
return false;
}
else
return true;
}
var arr = new Array();
arr[0] = new Array("-select-", "10.0","10.5", "12.0");
function change(combo1) {
document.getElementById("rate").style.visibility = "visible";
var sel = document.getElementById("combo1");
var val = document.getElementById("rate").value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML == val) {
sel.selectedIndex = i;
break;
}
}
}
}
</script>
<jsp:include page="include.jsp"></jsp:include>
<body>
<br>
<form action="PaymentServlet.do" name="form" method="post"
ONSUBMIT="return check()">
<fieldset>
<legend>
<font style="font-family: sans-serif" size="4px" color="Megenta">Online Loan
Application Page</font>
</legend>
<br />
Loan Type
<select name="combo1" onchange="change(this);">
<option value="0">
-Select-
</option>
<option value="1">
Home Loan
</option>
<option value="2">
Education Loan
</option>
<option value="3">
Car Loan
</option>
</select>
<br />
Interest Rate(%)<input type="text" name="rate" style="visibility: hidden;">
<br />
Loan Amount
<input type="text" name="loanamount" />
<br />
<input type="submit" name="go" value="o Go o" />
</fieldset>
</form>
</body>
</html>
depending on the loan type i want to select the respective interest rate from the array and want this array item to be used as the value of the input tag whose name="rate".
To get the value of a combo box you need to do the following:
var val = sel.options[sel.selectedIndex].value;
sel is your combo box
You can't use document.getElementById("elementid") by giving name as paramater. The paramater must be id of element not name.
Actually you don't need to use document.getElementById because you are returning this as paramater in change function. this refers the actual element.
So your change function should be like this,
function change(combo1) {
document.getElementById("rate").style.visibility = "visible";
document.getElementById("rate").value = arr[combo1.selectedIndex];
}
Your array definition is wrong as well. The right one is here,
var arr = new Array();
arr[0] = new Array("-select-", "10.0","10.5", "12.0");
var arr = new Array("-select-", "10.0","10.5", "12.0");
Finally don't forget to add id attribute for rate input,
<input type="text" id="rate" name="rate" style="visibility: hidden;">
And here is the complete code and a DEMO
<script language="javascript">
function check()
{
if(!validate())
return false;
}
function validate()
{
if (document.form.amount.value <=0)
{
alert ("Please enter valid loan amount.");
return false;
}
else
return true;
}
var arr = new Array("-select-", "10.0","10.5", "12.0");
function change(combo1) {
document.getElementById("rate").style.visibility = "visible";
document.getElementById("rate").value = arr[combo1.selectedIndex];
}
</script>
<body>
<br>
<form action="PaymentServlet.do" name="form" method="post"
ONSUBMIT="return check()">
<fieldset>
<legend>
<font style="font-family: sans-serif" size="4px" color="Megenta">Online Loan
Application Page</font>
</legend>
<br />
Loan Type
<select name="combo1" onchange="change(this);">
<option value="0">
-Select-
</option>
<option value="1">
Home Loan
</option>
<option value="2">
Education Loan
</option>
<option value="3">
Car Loan
</option>
</select>
<br />
Interest Rate(%)<input type="text" id="rate" name="rate" style="visibility: hidden;">
<br />
Loan Amount
<input type="text" name="loanamount" />
<br />
<input type="submit" name="go" value="o Go o" />
</fieldset>
</form>
</body>
if your array definition is like
arr[0] = new Array("-select-", "10.0","10.5", "12.0");
then
function change(combo1) {
document.getElementById("rate").style.visibility = "visible";
var rate = document.getElementById("rate");
rate.value = arr[0][combo1.selectedIndex];
}