How to disable fields in html using javascript - javascript

My code isn't disabling the other fields. please help
i am trying to select either a participant or exhibitor.once the participant is selected the other fields must be disable.
the Html
<label> <span>Test:</span>
<select id="reg" name="reg" onkeyup="disableField()">
<option value="" selected="selected" >Select Your Registration type </option>
<option value="Male">Participant</option>
<option value="Female">Exhibitor</option>
</select>
</label>
<label> <span>test 1 field:</span>
<input type="text" name="test1" id="test1"/>
</label>
<label> <span>test field 2:</span>
<input type="text" name="test2" id="test2"/>
</label>
the javascript
var disableField = function () {
var state = document.getElementById("reg").value === "Participant";
document.getElementById("test1").disabled = state;
document.getElementById("test2").disabled = state;
};

Do not use inline javascript. It makes your code messy and not reusable.
[Edit] This is a working example for you:
<html>
<head> <title></title></head>
<body>
<label> <span>Test:</span>
<select id="reg" name="reg">
<option value="" selected="selected" >Select Your Registration type </option>
<option value="Male">Participant</option>
<option value="Female">Exhibitor</option>
</select>
</label>
<label> <span>test 1 field:</span>
<input type="text" name="test1" id="test1"/>
</label>
<label> <span>test field 2:</span>
<input type="text" name="test2" id="test2"/>
</label>
<script type="text/javascript">
//<!--
var obj = document.getElementById("reg");
obj.onchange = function(event){
if(this.value=="Male"){
document.getElementById("test1").disabled = 'disabled';
document.getElementById("test2").disabled = 'disabled';
}else{
document.getElementById("test1").disabled = '';
document.getElementById("test2").disabled = '';
}
}
//--></script>
</body>
</html>
[/edit]
Have fun and may the source be with you.

Firstly, use onchange:
<select id="reg" name="reg" onchange="disableField()">
Secondly:
Your option values are 'male' and 'female'. So use that to compare:
var state = document.getElementById("reg").value == "Male";

try this ....it is working
<script type="text/javascript">
function disableField() {
var state = document.getElementById("reg").value === "Participant";
if (state == false) {
document.getElementById("test1").style.visibility = "hidden";
document.getElementById("test2").style.visibility = "hidden";
}
};
</script>

Try this,
<label> <span>Test:</span>
<select id="reg" name="reg" onchange="disableField();">
<option value="" selected="selected" >Select Your Registration type </option>
<option value="Male">Participant</option>
<option value="Female">Exhibitor</option>
</select>
</label>
<label> <span>test 1 field:</span>
<input type="text" name="test1" id="test1"/>
</label>
<label> <span>test field 2:</span>
<input type="text" name="test2" id="test2"/>
</label>
JS
function disableField() {
var val = document.getElementById("reg").value;
if(val == 'Male') {
document.getElementById("test1").disabled = true;
document.getElementById("test2").disabled = true;
} else {
document.getElementById("test1").disabled = false;
document.getElementById("test2").disabled = false;
}
}
Check value for Male not Participant
Here is the working code,
<html>
<head>
<script>
function disableField() {
alert('jdhsfg')
var val = document.getElementById("reg").value;
if(val == 'Male') {
document.getElementById("test1").disabled = true;
document.getElementById("test2").disabled = true;
} else {
document.getElementById("test1").disabled = false;
document.getElementById("test2").disabled = false;
}
}
</script>
</head>
<body>
<label> <span>Test:</span>
<select id="reg" name="reg" onchange="disableField();">
<option value="" selected="selected" >Select Your Registration type </option>
<option value="Male">Participant</option>
<option value="Female">Exhibitor</option>
</select>
</label>
<label> <span>test 1 field:</span>
<input type="text" name="test1" id="test1"/>
</label>
<label> <span>test field 2:</span>
<input type="text" name="test2" id="test2"/>
</label>
</body>
</html>

Add an on change in the select list
<select id="reg" name="reg" onchange="SelectedIndexChanged(this)">
function SelectedIndexChanged(e){
var selectedValue= e.value;
//if Participant is selected
if(selectedValue == "Participant "){
document.getElementById("test1").disabled = true;
document.getElementById("test2").disabled = true;
}
}

Related

How to sum the values of different field types in a form using Javascript

I can't seem to figure out how to sum the values of various field types in a form. I have some select fields like this:
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
And some radio buttons:
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
But how would I add the selections all up? I can find solutions for adding values of just inputs, or just radios, or just selects. But not all together.
I'd use jQuery if I have to.
[EDIT] I should have said, I'd like to output the total value to the user, perhaps inside a element.
Could clean this up a bit, but an example of using the FormData interface to add up all values in a form: https://developer.mozilla.org/en-US/docs/Web/API/FormData
function getValues() {
let myForm = document.getElementById('myForm');
let formData = new FormData(myForm);
let total = 0;
for (var value of formData.values()) {
total += parseInt(value);
}
document.getElementById("total").innerHTML = total;
console.log(total);
}
<form id="myForm" name="myForm">
<div>
<label for="age">What is your age?</label>
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
</div>
<div>
<label for="riskSmoke">Do you smoke?</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</div>
</form>
<button onclick="getValues()">Get Values</button>
<p>Total:</p>
<div id="total"></div>
You can use constructor FormData.
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
You could add a key/value pair to this using FormData.append:
formData.append('username', 'Chris');
I assume that you mean adding the values of the selected elements and that you use some trigger in this case I use a button. To make it work select options that have values
Please try this option
const button = document.querySelector("button");
button.addEventListener("click", () => {
const age = document.querySelector("select");
const riskSmoke = document.querySelector('input[name="riskSmoke"]:checked');
if (age && age.value && riskSmoke) {
const ageValue = +age.value;
const riskSmokeValue = +riskSmoke.value;
console.log(ageValue + riskSmokeValue);
}
});
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label><input type="radio" name="riskSmoke" value="2" /> Yes</label><br />
<label><input type="radio" name="riskSmoke" value="0" /> No</label>
<button>Click</button>
Without jQuery and for selecting specific values:
function getValues() {
var ageValue = Number(document.querySelector("select[name=age]").value);
console.log('age value: ' + ageValue);
var smokeValue = Number(document.querySelector('input[name="riskSmoke"]:checked').value);
console.log('smoke value: ' + smokeValue);
console.log('age + smoke: ' + (ageValue + smokeValue));
}
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<p>
<button onclick="getValues()">Get Values</button>
jQuery seems to be a bit of a overkill. In order to get the sum of the options and inputs, you may first get the value of the option in the select tag, and then add to the value of the selected radio input as such:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Your Title Here</title>
</head>
<body>
<select name="age" id="someId">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label><br>
<button onclick="CalculateValue()">Calculate</button>
<script>
let ageRangePicker = null, riskSmokeOptions = null;
function CalculateValue(){
ageRangePicker = document.getElementById("someId");
if(ageRangePicker.value !== ""){
let sum = Number(ageRangePicker.value);
riskSmokeOptions = document.getElementsByName("riskSmoke")
for(i = 0; i < riskSmokeOptions.length; i++) {
if(riskSmokeOptions[i].checked)
sum += Number(riskSmokeOptions[i].value);
}
alert("Your risk is: " + sum);
}
else{
alert("Select an age range");
}
}
</script>
</body>
</html>
I wrap in a form with an ID and sum on all input, making sure only to count checked radios and checkboxes
const sumValues = () => {
let val = 0;
$("#myForm :input").each(function() {
if (this.type === "radio" || this.type === "checkbox")
val += this.checked ? +this.value : 0;
else val += +this.value; // cast to number
})
$("#total").text(val)
};
$(function() {
$("#myForm").on("change", sumValues).change(); //when page loads
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
Plain JS
const sumValues = () => {
let val = 0;
[...document.getElementById("myForm").querySelectorAll("input, select, textarea")].forEach(function(elem) {
if (elem.type === "radio" || elem.type === "checkbox")
val += elem.checked ? +elem.value : 0;
else val += +elem.value; // cast to number
})
document.getElementById("total").textContent = val;
};
window.addEventListener("load", function() {
document.querySelector("#myForm").addEventListener("change", sumValues)
sumValues()
})
<form id="myForm">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="" selected>30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" checked name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
<br/>Total: <span id="total" />
</form>
With jQuery, you can listen for the change event and use both the jQuery .serializeArray() and the array .reduce() method to get the total:
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//output to a predefined element
$('#output').text( totalScore );
})
.change();
Here is how you may define an output element:
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Note that this will give a running total and there's no need to click any button or to trigger any event other then the actions needed to make choices on the various form elements.
$('form').on('change', function() {
let totalScore = $(this).serializeArray().reduce((a, f) => a += +f.value, 0);
//console.log( totalScore );
$('#output').text( totalScore );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<select name="age">
<option value="">- Select -</option>
<option value="1" class="">30-34</option>
<option value="2">35-39</option>
</select>
<p>Do you smoke?</p>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="2"> Yes</label><br>
<label for="riskSmoke"><input type="radio" name="riskSmoke" value="0"> No</label>
</form>
<div class="output">
<label>Total Score: </label>
<span id="output"></span>
</div>
Put a button below at the bottom of your HTML and make a function something like this:
const radioControls = document.querySelectorAll('.radio-btn');
const selectControl = document.querySelectorAll('.select');
let dataTransferObject = {
radioValue: 0,
selectValue: 0
};
let sum = 0;
function collectValues() {
for(let control of radioControls) {
if (control.checked) {
dto.radioValue = control.value
}
}
dto.selectValue = selectControl[0].value;
for(let attr of Object.values(dto)) {
sum += parseInt(attr);
}
}
Then your button simply calls this function, I would imagine this would all be contained in a form of some sort:
<button onclick="collectValues()">Submit</button>
Now the variable sum holds the accumulated value.

Make a Textfield required when list/menu option is selected

I want to validate a textfield when a relating dropdown is selected.
usually it should be allowed to submit null but when its relating drop menu is selected null should not be allowed.
<select>
<option></option>
<option value="red">one</option>
<option value="blue">two</option>
<option value="green">three</option>
</select>
Lets say i select red from the dropdown
<input name="red" id="red" type="text">
should be required, while others like <input name="blue" id="blue" type="text"><input name="green" id="green" type="text"> can be sent as null and vice versa.
The text field should serve as a full detail for the option selected so, it should correspend.
Is there a way to handle this with javascript?
<html>
<head>
<script>
window.addEventListener('load',function(){ SimpleVal.init(); });
var SimpleVal = {};
SimpleVal.init = function(){
this.form = document.getElementById("myForm");
this.textInputs = [this.form.elements.namedItem("red"), this.form.elements.namedItem("blue"),this.form.elements.namedItem("green")];
for(let i = 0; i < this.textInputs.length; i++) this.textInputs[i].disabled = true;
this.form.elements.namedItem("submit").disabled = true;
let sel = this.form.elements.namedItem("select");
this.form.addEventListener("change",function(){
for(let i = 0; i < this.textInputs.length; i++) this.textInputs[i].disabled = true;
this.form.elements.namedItem("submit").disabled = true;
if(sel.value){
this.form.elements.namedItem(sel.value).disabled = false;
if(this.form.elements.namedItem(sel.value).value) this.form.elements.namedItem("submit").disabled = false;
}
}.bind(this));
};
</script>
</head>
<body>
<form id='myForm'>
<select name='select'>
<option></option>
<option value="red">one</option>
<option value="blue">two</option>
<option value="green">three</option>
</select>
<input name='red' type='text'/>
<input name='blue' type='text'/>
<input name='green' type='text'/>
<input name='submit' type='submit'/>
</form>
</body>
</html>
https://jsfiddle.net/d0ep6z16/
https://jsfiddle.net/yce3Ljpf/1/
<select id="colors">
<option></option>
<option value="red">one</option>
<option value="blue">two</option>
<option value="green">three</option>
</select>
<input name="blue" id="red" type="text" class="color-input">
<input name="blue" id="blue" type="text" class="color-input">
<input name="green" id="green" type="text" class="color-input">
<script>
document.getElementById('colors').addEventListener("change", function() {
if (this.value.length) {
var inputs = document.getElementsByClassName("color-input");
for(var i = 0; i < inputs.length; i++) {
inputs.item(i).removeAttribute('required');
}
document.getElementById(this.value).setAttribute('required', 'required');
}
});
</script>
OK so I've laid this out so you can see what's happening:
<select id="colourSelect" onchange="val()">
<option value="nothing">Please Choose:</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="green">Green</option>
</select>
<br><br>
<input type="text" id="colourTextInput" size="50" onkeyup="clearMe()">
<br><br>
<button type="submit">Submit Button</button>
<script>
function val() {
d = document.getElementById("colourSelect").value;
if(d !== "nothing")
{
document.getElementById("colourTextInput").value = d;
}
else
{
document.getElementById('colourTextInput').value = "";
}
}
function clearMe() {
selectBox = document.getElementById("colourSelect");
selectBox.selectedIndex = null;
}
</script>
When the value of the dropdown is changed the value in the text box is set to the same as the dropdown. If they then go to the text field and try to change the colour, it defaults the dropdown back to its default setting, meaning that you can only ever have one or the other.
It could be made cleaner by simply clearing the text field when the dropdown is selected etc, but it gives you something to work with.
https://jsfiddle.net/cx1x2txu/
I modified this and got it right. Thanks all
<html><html>
<head>
<script>
window.addEventListener('load',function(){ SimpleVal.init(); });
var SimpleVal = {};
SimpleVal.init = function(){
this.form = document.getElementById("myForm");
this.textInputs = [this.form.elements.namedItem("red"), this.form.elements.namedItem("blue"),this.form.elements.namedItem("green")];
for(let i = 0; i < this.textInputs.length; i++) this.textInputs[i].disabled = true;
this.form.elements.namedItem("submit").disabled = true;
let sel = this.form.elements.namedItem("select");
this.form.addEventListener("change",function(){
for(let i = 0; i < this.textInputs.length; i++) this.textInputs[i].disabled = true;
this.form.elements.namedItem("submit").disabled = true;
if(sel.value){
this.form.elements.namedItem(sel.value).disabled = false;
if(this.form.elements.namedItem(sel.value).value) this.form.elements.namedItem("submit").disabled = false;
}
}.bind(this));
};
</script>
</head>
<body>
<form id='myForm'>
<select name='select'>
<option></option>
<option value="red">one</option>
<option value="blue">two</option>
<option value="green">three</option>
</select>
<input name='red' type='text'/>
<input name='blue' type='text'/>
<input name='green' type='text'/>
<input name='submit' type='submit'/>
</form>
</body>
</html>

Hide or Show div based on option selection

I'm trying to show or hide the div based on the option selected. When Customer is selected, it should show retCustDetails and when Trade is selected it should show tradeCustDetails.
Please let me know what I'm missing on the codes below.
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change()">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="visibility:hidden">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
JS
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === '1'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else{
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
}
There were few minor mistakes in your code, I have corrected it to make it work -
<body>
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="display:none">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
<script>
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected == 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else{
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
}
</script>
</body>
You are using visibility:hidden in your html but in your js your are changing the display property.
Change visibility:hidden to display:none.
Use this as change funtion's parameter like onchange="change(this)"
And JS function change to following.
function change(obj) {
var selectBox = obj.value;
var retCustDetails = document.getElementById('retCustDetails');
var tradeCustDetails = document.getElementById('tradeCustDetails');
if(selectBox == 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else{
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
}
This is an alternative method. This too works. Cheers !
<script>
jQuery(function($) {
$('#show').change(function(){
var val = $(this).val();
if( val == 'ret') {
$('#retCustDetails').show();
$('#tradeCustDetails').hide();
} else if(val == 'trd') {
$('#tradeCustDetails').show();
$('#retCustDetails').hide();
} else {
$('#tradeCustDetails').hide();
$('#retCustDetails').hide();
}
});
});
</script>
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails" style="display:none">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="display:none">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
pass the this as argument to the change() method. Also change the if condition as like below
if(selected === 'ret'){
//...
}
because you get the selected value, it give either "ret" or "trd"
Change the tradeCustDetails visibility: hidden to display: none
Try this code.
function change(obj) {
//alert(obj);
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else{
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
}
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
<div id="retCustDetails" class="custDetails">
Forename <input type="text" name="forename" id="forename" />
Surname <input type="text" name="surname" id="surname" />
</div>
<div id="tradeCustDetails" class="custDetails" style="display:none">
Company Name <input type="text" name="companyName" id="companyName" />
</div>
Hope this will help you.

Redirect to a page according to selected option from radio button through 'onclick' , without 'submit' the form in php

This is the code which is not working according to my requirement
<head>
<script type="text/javascript">
function test(){
if(document.form.choice.value='pc'){
window.open('pc.php','_self');
return true;
}
else if(document.form.choice.value='ps2'){
window.open('ps2.php','_self');
return true;
}
else if(document.form.choice.value='ps3'){
window.open('ps3.php','_self');
return true;
}
else if(document.form.choice.value='psp'){
window.open('psp.php','_self');
return true;
}
}
</script>
</head>
<body>
Games<br /><br />
<form name="form">ALL
<input type="radio" onClick="test()" name="choice" value="pc">PC
<input type="radio" onClick="test()" name="choice" value="ps2">PS2
<input type="radio" onClick="test()" name="choice" value="ps3">PS3
<input type="radio" onClick="test()" name="choice" value="psp">PSP
</form>
</body>
Also i want to know that how to display the field automatically just by selecting the selected field in Drop down list without 'submit'
<select name="genre">
<option value="">--Select Genre and Click Go--</option>
<option value="All">All</option>
<option value="Action / Mission">Action / Mission</option>
<option value="Arcade">Arcade</option>
<option value="Racing">Racing</option>
<option value="Sports">Sports</option>
<option value="Kids">Kids</option>
<option value="Strategy">Strategy</option>
<option value="Adventure">Adventure</option>
</select>
Try this...
EDITED:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script type="text/javascript">
function idForm(){
var selectvalue = $('input[name=choice]:checked', '#idForm').val();
if(selectvalue == "pc"){
window.open('http://www.google.com','_self');
return true;
}
else if(selectvalue == "ps2"){
window.open('http://www.google.com','_self');
return true;
}else if(selectvalue == 'ps3'){
window.open('http://www.google.com','_self');
return true;
}else if(selectvalue == 'psp'){
window.open('http://www.google.com','_self');
return true;
}
return false;
};
</script>
</head>
<body>
Games<br /><br />
<form id="idForm">ALL
<input type="radio" onclick="idForm()" name="choice" value="pc"/>PC
<input type="radio" onclick="idForm()" name="choice" value="ps2"/>PS2
<input type="radio" onclick="idForm()" name="choice" value="ps3"/>PS3
<input type="radio" onclick="idForm()" name="choice" value="psp"/>PSP
</form>
</body>
Jsfiddle
link
You can get the value of the option by adding onchange event in the <select> tag.
<select name="genre" onchange="selectOption()">
<option value="">--Select Genre and Click Go--</option>
<option value="All">All</option>
<option value="Action / Mission">Action / Mission</option>
<option value="Arcade">Arcade</option>
<option value="Racing">Racing</option>
<option value="Sports">Sports</option>
<option value="Kids">Kids</option>
<option value="Strategy">Strategy</option>
<option value="Adventure">Adventure</option>
</select>
In your script add this
function selectOption(){
//each option value
var option=document.form.genre.value;
alert(option);
}
For redirecting you can use window.location in your test() method
use this window.location=yourpage.php instead of this window.open('pc.php','_self')

Setting visibility of select tag based on selection in prior select tag

I want to have my States select dropdown only be visible after a country has been chosen in a prior dropdown.
Here is my code:
<form>
Name: <input type="text" name="name" autofocus>
<br />
E-mail: <input type="text" name="email">
<br />
<input type="radio" name="sex" value="male">Male
<br />
<input type="radio" name="sex" value="female">Female
<br />
<select name="country" onchange="showStates()" id="country">
<option>Select A Country</option>
<option id="US" value="US">USA</option>
<option id="AUS" value="AUS">Australia</option>
</select>
<br />
<select name="State" style="display:none;" id="us-states">
<option>Select A State</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
<br />
<select name="State" style="display:none;" id="aus-states">
<option value="" selected="selected">Select A State</option>
<option value="TAS">Tasmania</option>
<option value="QLD">Queensland</option>
<option value="VIC">Victoria</option>
</select>
<br />
<button type="submit">Submit</button>
<br />
<input type="reset" value="Reset">
</form>
Here is the showStates() function:
function showStates() {
var selected = $('#country :selected').text();
if (selected == "US") {
document.getElementByID('us-states').style.display = "block;";
} else {
document.getElementByID('us-states').style.display = "none;";
}
if(selected == "AUS") {
document.getElementByID('aus-states').style.display = "block;";
} else {
document.getElementByID('aus-states').style.display = "none;";}
}
}
I'm finding that the program initially hides the select boxes, but doesn't redraw them when a new option is selected in the country tag.
Since you're already using jQuery you can do away with the inline function call. Just add a change handler, and use the value of #country to determine which element to show:
$('#country').on('change', function() {
var country = this.value.toLowerCase();
$('select[name="State"]').hide()
.filter('#' + country + '-states')
.show();
});
Here's a fiddle
You can do this way using jQuery:
$('#country').on('change', function() {
var selected = $(this).val();
if(selected === "US") {
$('#us-states').show();
}
else {
$('#us-states').hide();
}
if(selected === "AUS") {
$('#aus-states').show();
}
else {
$('#aus-states').hide();
}
});
}
Fiddle Example HERE
OR:
$('#country').on('change',function()
{
var selected = $(this).val();
showStates(selected);
});
ShowStates Function:
function ShowStates(value)
{
if(value === "US") {
$('#us-states').show();
}
else {
$('#us-states').hide();
}
if(value === "AUS") {
$('#aus-states').show();
}
else {
$('#aus-states').hide();
}
}
Fiddle With Existing Function Reuse
How is this?
function showStates(id)
{
$("#"+id).css("display", "block");
}
$("#country").on("change", function(){
showStates('us-states');
});
http://jsfiddle.net/Lukx8/

Categories