How to show form input fields based on select value? - javascript

I know this is simple, and I need to search in Google. I tried my best and I could not find a better solution. I have a form field, which takes some input and a select field, which has some values. It also has "Other" value.
What I want is:
If the user selects the 'Other' option, a text field to specify that 'Other' should be displayed. When a user selects another option (than 'Other') I want to hide it again. How can I perform that using JQuery?
This is my JSP code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="otherType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
Now I want to show the DIV tag**(id="otherType")** only when the user selects Other.
I want to try JQuery. This is the code I tried
<script type="text/javascript"
src="jquery-ui-1.10.0/tests/jquery-1.9.0.js"></script>
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>
<script>
$('#dbType').change(function(){
selection = $('this').value();
switch(selection)
{
case 'other':
$('#otherType').show();
break;
case 'default':
$('#otherType').hide();
break;
}
});
</script>
But I am not able to get this. What should I do? Thanks

You have a few issues with your code:
you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">
should be <select name="dbType" id="dbType">
$('this') should be $(this): there is no need for the quotes inside the paranthesis.
use .val() instead of .value() when you want to retrieve the value of an option
when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function
try this:
$('#dbType').on('change',function(){
if( $(this).val()==="other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
http://jsfiddle.net/ks6cv/
UPDATE for use with switch:
$('#dbType').on('change',function(){
var selection = $(this).val();
switch(selection){
case "other":
$("#otherType").show()
break;
default:
$("#otherType").hide()
}
});
UPDATE with links for jQuery and jQuery-UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​

Demo on JSFiddle
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>

You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"
Live Demo
Change
selection = $('this').value();
To
selection = $(this).val();
or
selection = this.value;

I got its answer. Here is my code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
And my script is
$(function() {
$('#dbType').change(function() {
$('.selectDBType').slideUp("slow");
$('#' + $(this).val()).slideDown("slow");
});
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>
</body>
</html>

$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});

Related

How to Display Select Tag using 'change' jquery 2.1.4?

I am trying to display select box when user input some values in the textbox , I tried using onchange property of jquery but its not working.
Below is my code
$(document).ready(function() {
$("#total_enter").change(function() {
$(".gst_sel_wrap").css("display", "block");
});
})
.gst_sel_wrap {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
Try using the jQuery keydown method: https://api.jquery.com/keydown/
I also added some code to hide the dropdown in the beginning, so the effect becomes obvious.
$(document).ready(function(){
$(".gst_sel_wrap").hide();
$("#total_enter").keydown(function(){
$(".gst_sel_wrap").show();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
You can use either keyup or keydown or both as I do here:
$(document).ready(function() {
$("#total_enter").on("keyup keydown",function() {
$(".gst_sel_wrap").css("display", "block");
});
})
.gst_sel_wrap {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>
To achieve this you can use the input event, as it fires when a key is pressed and also when a value is copy/pasted in. You should also check the value of the element to ensure that it isn't empty, as the value can be deleted, when I would assume your select should be hidden again.
Finally, note that you can use toggle() to hide or show the select based on the given value, in a more succinct way. Try this:
$(document).ready(function() {
$("#total_enter").on('input', function() {
$(".gst_sel_wrap").toggle(this.value.trim() != '');
});
})
.gst_sel_wrap {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap_box">
<input type="text" name="total_enter" id="total_enter">
<select class="gst_sel_wrap">
<option>GST SLABS</option>
<option value="">0%</option>
<option value="">5%</option>
<option value="">12%</option>
<option value="">18%</option>
<option value="">28%</option>
</select>
</div>

How to enable disable text input while making my function modular

Here is my script, what my goal is if other is selected in select, the other text input beside it will be enabled, this is what i've got so far, any approach will be really appreciated, I have 4 questions like this and I want it to be modular, best approach for doing my function to be reuseable.. How do I properly do this without any problem posting my data as 2 name inputs will generate 2 post variables in php.. T_T
<script type="text/javascript" charset="utf-8">
function validate()
{
var ddl = document.getElementById("cause_pain");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OTHER")
{
document.getElementsByClassName("causepain")[0].removeAttribute("name");
document.getElementsByClassName("causepain1")[0].removeAttribute("disabled");
}
}
</script>
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain" onchange="validate()">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain" name="cause_pain" size="40" onkeyup="clean('this.id')" disabled>
<input type="submit" id="submit"/>
</form>
This method is reusable and pretty straight forward. Using data attributes, you could specify the element that needs to be shown on the specific option element. Also before showing any input element hide the elements that were attributed to the previous selection.
Example:
<form action="test.php" method="GET">
<select class="select causepain" id="cause_pain" name="cause_pain">
<option value="" selected="selected">Select Cause of Pain</option>
<option value="ARTHRITIS">ARTHRITIS</option>
<option value="RHEUMATISM">RHEUMATISM</option>
<option value="OLD AGE">OLD AGE</option>
<option value="ACTIVE LIFESTYLE WHEN YOUNGER">ACTIVE LIFESTYLE WHEN YOUNGER</option>
<option value="OTHER" data-show="cause_pain_other">OTHER</option>
</select>
<input class="causepain1" type="text" id="cause_pain_other" name="cause_pain" size="40"
onkeyup="clean('this.id')" disabled style="display: none;">
<input type="submit" id="submit"/>
</form>
<script type="text/javascript" charset="utf-8">
var selectedOpt;
function selectionChanged(e) {
if (selectedOpt && selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = true;
showEl.style.display = 'none';
}
selectedOpt = this.querySelector('[value="'+e.target.value+'"]');
if (selectedOpt.dataset.show) {
var showEl = document.getElementById(selectedOpt.dataset.show);
showEl.disabled = false;
showEl.style.display = 'block';
}
}
document.querySelector('select').addEventListener('change', selectionChanged);
</script>
Your selectedOpt should be an object if you're using multiple selects on the same page and then just add the element to the object with the id as an index:
var selectedOpt = {};
...
selectedOpt[this.id] = this.querySelector('[value="'+e.target.value+'"]');

How to change the Input Name based on the dropdown selection in html form?

I have a HTML form which changes its form action based on the drop down selection but input name remains same.
Here is my HTML:
<form action="car.php" method="GET">
Select Your Option :
<select onChange="this.form.action=this.options[this.selectedIndex].value;">
<option value='car.php'>Car Name</option>
<option value='bike.php'>Bike Name</option>
<option value='laptop.php'>Laptop Name</option>
<option value='place.php'>Place Name</option>
<option value='mobile.php'>Mobile Name</option>
</select>
Enter your query // I want to change this also
<input id="Value" name="Value" type="text">
<button id="submit" type="submit" value="Submit">Submit Query</button>
If I select Car Name and enter Maruti then value is passed like this:
http://www.mywebsite.com/car.php?Value=Maruti
If I select Bike Name and enter Honda then value is passed like this :
http://www.mywebsite.com/bike.php?Value=Honda
My problem is I have to name the column as "Value" in all the 5 database which stores all the information regarding all this, which I want to avoid.
I want, If I select Car Name and enter Maruti then value should pass like this
http://www.mywebsite.com/car.php?car=Maruti
If I select Bike Name and enter Honda then value should pass like this
http://www.mywebsite.com/bike.php?bike=Honda
What changes should be made in the code to achieve this goal?
If this can also happen then its very nice otherwise no problem.
In the form it is written Enter your query. I want the same change to happen here. If I select Car Name then it should be Enter you car. If I select Bike Name then it should be Enter your bike... and so on.
UPDATE
Little modification I need. When selecting car, the input name is changing to car, the form action is changing to car.php and query to Enter your car. But If I want to change the name like this then what should I do? When I will select anything say bike then form action will be changed to bike.php, But I want input name to be different say USY and Enter your bike to Enter your Serial No. What should I do ?
I have updated the code now and got ur exact requirement now and i hope this will help you
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
var str=$(this).val(); // On Change get the option value
$("form").attr("action",str);
var res=str.split(".");
$("#input1").attr("name",res[0]);
$(".title").html("Enter your "+res[0]+" Name."); // Add this below $("input").attr("name",res[0]);
if(res[0]=='bike')
{
var title2="XYZ";
var title3="Serial No";
}
else if(res[0]=='laptop')
{
var title2="ABC";
var title3="Model No";
}
else if(res[0]=='place')
{
var title2="KLM";
var title3="Area";
}
else if(res[0]=='mobile')
{
var title2="FGH";
var title3="Brand";
}
$("#input2").attr("name",title2);
$("#input3").attr("name",title3);
$(".title2").html("Enter your "+title3);
});
});
</script>
<form action="car.php" method="GET">
Select Your Option :
<select value="car.php">
<option value='car.php'>Car Name</option>
<option value='bike.php'>Bike Name</option>
<option value='laptop.php'>Laptop Name</option>
<option value='place.php'>Place Name</option>
<option value='mobile.php'>Mobile Name</option>
</select>
<span class="title2">Enter your Color</span>
<input name="WER" id="input2" type="text">
<button id="submit" type="submit" value="Submit">Submit Query</button>
</form>
I advise you to not use JavaScript embedded into HTML attributes. Other than that, you can change the name attribute in the same change handler where you're modifying the action.
document.getElementById('Type').addEventListener('change', function(evt) {
var type = this.selectedOptions[0].value;
console.dir(this);
document.getElementById('Value').setAttribute('name', type);
document.getElementById('QueryName').textContent = type;
this.form.action = type + ".php";
});
<form action="car.php" method="GET">
Select Your Option :
<select id="Type">
<option value='car' selected>Car Name</option>
<option value='bike'>Bike Name</option>
<option value='laptop'>Laptop Name</option>
<option value='place'>Place Name</option>
<option value='mobile'>Mobile Name</option>
</select>
Enter your <span id="QueryName">car</span>
<input id="Value" name="car" type="text">
<button id="submit" type="submit" value="Submit">Submit Query</button>
EDIT: If you want everything to be different as said in comments, you can use an object to hold the values. For example,
var setup = {
car: {
action: 'mycar.php',
param: 'DFS',
query: 'color'
},
...
};
and then instead of directly using the option's value, pull from this object based on the selected option.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
var str=$(this).val(); // On Change get the option value
$("form").attr("action",str);
var res=str.split(".");
$("input").attr("name",res[0]);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<form action="car.php" method="GET">
Select Your Option :
<select value="car.php">
<option value='car.php'>Car Name</option>
<option value='bike.php'>Bike Name</option>
<option value='laptop.php'>Laptop Name</option>
<option value='place.php'>Place Name</option>
<option value='mobile.php'>Mobile Name</option>
</select>
Enter your query // I want to change this also
<input id="Value" name="car" type="text">
<button id="submit" type="submit" value="Submit">Submit Query</button>
</form>
</html>
I have used jquery here some few changes in html try it out this one
<form action="car.php" method="GET">
Select Your Option :
<select value="car.php">
<option value='car.php'>Car Name</option>
<option value='bike.php'>Bike Name</option>
<option value='laptop.php'>Laptop Name</option>
<option value='place.php'>Place Name</option>
<option value='mobile.php'>Mobile Name</option>
</select>
Enter your query // I want to change this also
<input id="Value" name="car" type="text">
<button id="submit" type="submit" value="Submit">Submit Query</button>
</form>
And for Jquery you can use this one
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
var str=$(this).val(); // On Change get the option value
$("form").attr("action",str);
var res=str.split(".");
$("input").attr("name",res[0]);
});
});
</script>
This works perfectly for me Enjoy :)

JavaScript Populating an input Field Using an Html combo Box

i am trying to find a way to allow a user to click items in a combo box and have its value populate an input field and also alert "work stop" or "work start" message when appropriate option is selected. But my code is not working. Please Help!
Here is my code:
<html>
<head>
</head>
<body>
<form>
<select name="sel1" onChange="populateField(this.form)" >
<option value="">---Select---</option>
<option value="stop" >Stop</option>
<option value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">
function populateField(frm){
test = frm.stop.value;
alert('work' test);
frm.eStop.value = test;
}
</script>
</body>
</html>
Thanks in Advance
http://jsfiddle.net/snHQY/
<form>
<select name="sel1" id="select" onchange="populateField();" >
<option value="">---Select---</option>
<option name="stop" value="stop" >Stop</option>
<option name="start" value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script>
function populateField() {
test = document.getElementById('select').value;
alert(test);
document.getElementById('eStop').value = test;
}
</script>
You can do it using the selectedIndex if you want as well,
<form>
<select name="sel1" id="select" onchange="populateField(this);" >
<option value="">---Select---</option>
<option name="stop" value="stop" >Stop</option>
<option name="start" value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script>
function populateField(sel) {
sel.form.eStop.value = 'work ' + (sel.selectedIndex == 1 ? 'Stop' : 'Start');
}
</script>
http://jsfiddle.net/cnpuM/
Your code has two errors. You can not reference an element by its value like this test = frm.stop.value; instead use test = frm.sel1.value; . Another error is in this line alert('work' test);. Here you are joining a string "work" with a variable "test". In java script where ever you join two or more variables or strings and variables you alway have to join them with + sign like this:alert('work ' + test);. Remaining code is ok:
<html>
<head>
</head>
<body>
<form>
<select name="sel1" onChange="populateField(this.form)" >
<option value="">---Select---</option>
<option value="stop" >Stop</option>
<option value="start">Start</option>
</select>
<input type="text" id="eStop" name="eStop" />
</form>
<script type="text/javascript">
function populateField(frm){
var test = frm.sel1.value;
alert('work '+ test);
frm.eStop.value = test;
}
</script>
</body>
</html>
You can also use selectedIndex property of "sel1" to do the same.
in your select you can add to onchange's and onkeypress to the populateField's function this as the objects reference.
<select name="sel1" onchange="populateField(this)" onkeypress="populateField(this)">
Now you can reference the select from o. to pass the selected value to the alert dialog and the input field.
function populateField(o){
alert("work " + o.value);
// use regular W3C DOM syntax for element referencing the input and populate it with the select objects selected options value
document.getElementById("eStop").value = o.value;
}

How to change value from one Select to another?

I have two Selects with several options in html code:
<select name="t" id="t">
<option value="0">Overall</option>
<option value="1">t_name</option></select>
<select name="m" id="m">
<option value="0">back to Overall</option>
<option value="1">m_some</option></select>
And my question is how to force change value from first Select named "t" to "0" (Overall) only in the case when user chosen value "0" (back to Overall) in second Select named "m"? And submit form at the end.
--EDIT--
Now because of advices I tried do that in this way:
<script>
$(function(){
$('#m, #t').change(function(){
if($('#m').val() == '0')
$('#t').val('0').change();
$('form#myform').submit();
});
});
</script>
And this script submits the form everytime when I change Select "m" or "t", except situation when I change Select "m" to value "0" (script only changes "t" to "0" in correct way without submit). Why?
<html>
<body>
<form name="form1" id="form1">
<select id="t" name="t" onchange="this.form.submit();">
<option value="0">Overall</option>
<option value="1">t_name</option>
</select>
<select name="m" onchange="setposition(this.value)">
<option value="0">back to Overall</option>
<option value="1">m_some</option>
</select>
</form>
</body>
</html>
<script language="javascript" type="text/javascript">
function setposition(svalue) {
if (svalue == "0") {
document.getElementById("t").options[1].selected = true;
}
}
</script>`enter code here`
You should be using ID's as below as they are easier on DOM searching.
<select name="t" id="t" onchange="this.form.submit();">
<option value="0">Overall</option>
<option value="1">t_name</option></select>
<select name="m" id="m" onchange="this.form.submit();">
<option value="0">back to Overall</option>
<option value="1">m_some</option></select>
<script>
$(function(){
$('#m, #t').change(function(){
//don't forget to trigger the change event
if($('#m').val() == '0')
$('#t').val('0').change();
$('form#form_id').submit();
});
});
</script>
You could do something like that:
$(function(){
$('[name="t"],[name="m"]').change(function(){
if($(this).attr('name')=='m') && $(this).val()=='0'){
$('[name="t"]').val('0');
}
$(this).closest('form').submit();
});
});
$('select[name="m"]').change(function() {
if($(this).val() == '0') {
$('select[name="t"]').val('0');
}
});
Besides that, you should use jQuery to set the onchange events instead of doing so via inline JS:
$('select[name="t"], select[name="m"]').change(function() {
$(this).closest('form').submit();
// if you do not need any jquery submit events,
// you can also use this.form.submit();
});
See http://jsfiddle.net/ThiefMaster/NfVQZ/ for a demo.

Categories

Resources