Im fairly new to javascript but have some experience in HTML. I am trying to create a form which allows me to select an option from the drop down menu, which further expands the form (showing new fields on the same page) depending on the option selected from the drop down menu. I figured I need some sort of if statement to achieve this but I can't seem to figure out the right way to do so. I already have the drop down menu working. I would put the code I already have on here, but for some reason its not letting me
Thanks for your help
EDIT - Ran the code from comments through HTML tidy
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Linux/x86 (vers 11 February 2007), see www.w3.org" />
<title>Ipod Inventory</title>
<script language="JavaScript" type="text/javascript">
//<![CDATA[
function submitSelect(form) { alert (form.reason.selectedIndex); document.body.innerHTML() = "<h3>NEW STUFF<h3>"; }
//]]>
</script>
</head>
<body>
<h3>General</h3>Employee Requesting:
<form>
<input type="text" name="employee" value="" />
</form>
<form name="myform" action="" method="get" id="myform">
Reason: <select name="reason">
<option>
Conference/Meeting
</option>
<option>
Loaner
</option>
</select> <input type="button" name="submit" value="Submit" onclick=
"submitSelect(this.form)" /><br />
</form>
</body>
</html>
What you could do is split your page in different div sections, one for each case in your dropdown. You would then alter the display property of those divs using
element.style.display = 'none'
or
element.style.display = 'block'
If your setup is more complex, you might want to create a list of fields that should be visible for each item in your combo box, and then show/hide using the same technique.
For example, you would have a dropdown with male, and female. You would then have to div elements, whose id would be male or female. Then you would use
function toggle() {
if (document.getElementById('selector').value == 'male') {
document.getElementById('male').style.display = 'block';
document.getElementById('female').style.display = 'none';
}
else {
document.getElementById('male').style.display = 'none';
document.getElementById('female').style.display = 'block';
}
}
var selectmenu=document.getElementById("mymenu")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
if (chosenoption.value!="nothing"){
window.open(chosenoption.value, "", "") //open target site (based on option's value attr) in new window
}
}
Thats the if condition you need to use and the example also shows how to bind change event too..(code snippet extracted from javascript kit)
What you want to do is start with the onchange event of your reason select box:
<select name="reason" id="reason" onchange="myFunc();">
myFunc() (excuse the name, I'm not very creative) will be where you do your showing/hiding of the other inputs - probably not a different form, as usually inputs are collected into a single form on a page. Each input (or set of inputs) should be in it's own <div> tag, and you can then use the element.style.display property of the tag to show/hide the inputs, as described in the other answers. For example, you might have the following in your form:
<form name="myform" action="" method="get" id="myform">
Reason: <select name="reason" id="reason" onchange="myFunc()">
<option>
Conference/Meeting
</option>
<option>
Loaner
</option>
</select>
<div id="conferenceInputs">
Conference:
<select name="conferenceSelectBox" id="conferenceSelectBox">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div id="loanerInputs">
Loaner:
<select name="loanerSelectBox" id="loanerSelectBox">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<input type="button" name="submit" value="Submit" onclick="submitSelect(this.form)" />
</form>
The myFunc() javascript would look something like this:
function myFunc() {
var selectElem = document.getElementById('reason');
var optionText = selectElem.options[selectElem.selectedIndex].text;
switch(optionText) {
case "Conference/Meeting":
document.getElementById('conferenceInputs').style.display = 'block';
document.getElementById('loanerInputs').style.display = 'none';
break;
case "Loaner":
document.getElementById('loanerInputs').style.display = 'block';
document.getElementById('conferenceInputs').style.display = 'none';
break;
default:
}
}
Finally, you would want to have a javascript function that loads with the HTML page - <body onload="anotherFunc()"> that sets both div's style.display properties to 'none' so that they don't appear before the user selects anything.
Related
I currently have multiple forms that are similar but have small changes. First, the user choses the form from a drop-down menu and then the form is shown below.
My forms looks like this.
Form 1
Customer Name
Phone Number
Address
Form 2
Customer Name
Is married?
Form 3
Customer Name
Social Security Number
Address
My code looks something like this.
<select onchange="changeOptions(this)">
<option value="" selected="selected"></option>
<option value="form1">f1</option>
<option value="form2">f2</option>
<option value="form3">f3</option>
</select>
<form class="className" name="form1" id="form1" style="display:none">
---form---
<form class="className" name="form2" id="form2" style="display:none">
---form---
<form class="className" name="form3" id="form3" style="display:none">
---form---
<script>
function changeOptions(selectEl) {
let selectedValue = selectEl.options[selectEl.selectedIndex].value;
let subForms = document.getElementsByClassName('className')
for (let i = 0; i < subForms.length; i += 1) {
if (selectedValue === subForms[i].name) {
subForms[i].setAttribute('style', 'display:block')
} else {
subForms[i].setAttribute('style', 'display:none')
}
}
}
</script>
Is there any way to create a 'main' form that has all the form elements and then specify which element to use in each form? The method I'm using right now works fine but there is too much repeated code and probably won't scale correctly if I try to make a change in one of the elements (since I would have to change each one of them and it will be easy to make mistakes)
You don't need three different forms, just have one form with all of the fields set as hidden. Then give each field a class matching which form that field should be shown. Then simply show the matching fields based on the selected value.
select_form = document.querySelector(".select_form");
fields = document.querySelectorAll(".field");
select_form.addEventListener("change", function() {
fields.forEach(function(el) {
el.style.display = "none";
});
show = document.querySelectorAll("." + this.value);
show.forEach(function(el) {
el.style.display = "block";
});
});
.field {
display: none;
}
<select class="select_form">
<option value="" selected="selected"></option>
<option value="form1">f1</option>
<option value="form2">f2</option>
<option value="form3">f3</option>
</select>
<form>
<div class="field form1 form2">ONLY form1 and 2</div>
<div class="field form3">ONLY form3</div>
</form>
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 want to be able to read the text which is submitted in a drop down box with jQuery, as I then want to post it to php. I've been following a tutorial but I have the issue when it does not read the value from the drop down box.
An alert with the name selected should appear when the refresh button is pressed. (The submit button in the script below is for something different and links to a different js file. Not relevant)
function update() {
var p1 = $("#playerOne").text();
alert('youre name is ' + p1);
}
<div class="inputForm">
<form id="frm1" onsubmit="return formSubmit()">
<h3>Update League Table!</h3>
<section class="playerOne">
<label for="playerOne">Player One Name:</label>
<select name="playerOne" id="playerOne">
<option value="player1">Player 1</option>
<option value="player2">Player 2</option>
<option value="player3">Player 3</option>
<option value="player4">Player 4</option>
</select>
</section>
<section class="submission">
<input type="submit" value="Submit">
</section>
<input class="refreshButton" type="button" value="Refresh" onclick="update()">
</form>
</div>
In the jquery file, if I remove var p1 = $("#playerOne").text(); then the alert will work. With that in the alert does not appear at all.
I have tried having the refresh button at different points in the HTML, didn't work. I have moved where <script type="text/javascript" src="jquery.js"></script> is within the HTML, didn't work.
I have also tried .val instead of .text. And var p1 = $("#playerOne option:selected").text();. Neither of these worked.
Any help is appreciated.
You can do this by using simple JavaScript code replace your jQuery with
var _val = document.getElementById('playerOne').value;
alert(_val); // it will work for you
$('#playerOne').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$('#playerOne option:selected').text();
function update() {
var p1 = $( "#playerOne option:selected" ).text(); // for getting value in element
alert ('youre name is ' +p1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body background="mkimage.png">
<div class="inputForm">
<form id="frm1" onsubmit="return formSubmit()">
<h3>Update League Table!</h3>
<section class="playerOne">
<label for="playerOne">Player One Name:</label>
<select name="playerOne" id="playerOne">
<option value="player1">Player 1</option>
<option value="player2">Player 2</option>
<option value="player3">Player 3</option>
<option value="player4">Player 4</option>
</select>
</section>
<section class="submission">
<input type="submit" value="Submit">
</section>
<input class="refreshButton" type="button" value="Refresh" onclick="update()">
</form>
</div>
</body>
</html>
Here is your solution
use val() for getting value for the selected list.
if your using text() jquery .it will give all text in the element.
function update() {
var p1 = $("#playerOne").val(); // for getting value in value attribute
alert ('youre name is ' +p1);
}
function update() {
var p1 = $( "#playerOne option:selected" ).text(); // for getting value in element
alert ('youre name is ' +p1);
}
Try changing your selector in your jQuery sentence:
function update() {
var p1 = $("#playerOne option:selected").text();
alert ('youre name is ' + p1);
}
Try this, to get the selected option:
$( "#playerOne option:selected" ).text()
I have a situation, ie, I wanted the selected data from the dropdown box to be displayed inside a form (of type text) below it and which should be readonly.(using html/javascript). I am not able to do that as i am a pioneer in that
Hope responses
The below is a rough sketch of a non-jquery method of dynamically changing one form box using input from a dropdown menu.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function optionCallBack (arg) {
var currentOption = arg.options[arg.selectedIndex].text;
document.getElementById('changeForm').value = currentOption;
}
</script>
</head>
<body>
<select onclick="optionCallBack(this)" id='getForm'>
<option>asia</option>
<option>africa</option>
<option>america</option>
<option>europe</option>
</select>
<form>
<input value='europe' name='changeForm' id='changeForm'></input>
</form>
</body>
</html>
First of all, you need a select list like below (notice the onchange event handler)
<select onchange="fillTextBox(this)" id='mySelectList'>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
You will also need a text box (lets give it an Id myTextBox)
<input value='' name='' id='myTextBox'></input>
You'll need the following script for fillTextBox function
function fillTextBox(obj) {
var sel = obj.value;
document.getElementById('myTextBox').value = sel;
}
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>