Change Dropdown values based on input in textfield - javascript

I try to find a solution, but I can't find it and I am not able to program it by myself. I hope you can help me.
I have 2 elements: A textfield and a drop down menu (select/options).
Based on the birth/year of a person I enter into the textfield, I want to have a related drop down values.
If the person is 0-17 years old, the values in the drop down should bei 0, 100, 200, 300, 400, 500, 600.
If the person is 18 years old or older, the values in the drop down should bei 300, 500, 1000, 1500, 2000, 2500.
Example: If I enter 1978 into the text field, the drop down menu should show the values 300, 500,…
If I enter 2002 into the text field, the drop down menu should show the values 100, 200,…
I hope it is understandable what I am looking for.
I have checked this one:
Change dropdown value based on Text Input
and also this one, which looks also similar to what I need:
jQuery - Change hidden value based on input field
But I can't make it.
A jsfiddle would be really cool!
Thank you in advance.
<input name="Year" type="text" value="" />
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300">300.-</option>
<option value="500">500.-</option>
<option value="1000">1000.-</option>
<option value="1500">1500.-</option>
<option value="2000">2000.-</option>
<option value="2500">2500.-</option>
</select>
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="100">100.-</option>
<option value="200">200.-</option>
<option value="300">300.-</option>
<option value="400">400.-</option>
<option value="500">500.-</option>
<option value="600“>600.-</option>
</select>
Kind regards,
Andy

You could handle this by taking advantage of data-* attributes and using jQuery to determine which values should be shown based on your selection :
<!-- Assumes a valid year is entered -->
<input name="Year" type="text" value="" />
<!-- Notice your possible values data options -->
<select name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300" data-under-18="100" data-over-18="300">300.-</option>
<option value="500" data-under-18="200" data-over-18="500">500.-</option>
<option value="1000" data-under-18="300" data-over-18="1000">1000.-</option>
<option value="1500" data-under-18="400" data-over-18="1500">1500.-</option>
<option value="2000" data-under-18="500" data-over-18="2000">2000.-</option>
<option value="2500" data-under-18="600" data-over-18="2500">2500.-</option>
</select>
<script>
$(function(){
// When your year changes...
$('[name="Year"]').change(function(){
// Check that the value is a year (assumes 4 digit number)
if(/^\d{4}/.test($(this).val())){
// Parse the value
var year = parseInt($(this).val());
// Determine the user's age
var age = new Date().getFullYear() - year;
// Use the data attributes to set each value (ignore the first one)
$('[name="Results"] option:not(:first)').each(function(){
var valueToUse = (age >= 18) ? $(this).attr('data-over-18') : $(this).attr('data-under-18');
$(this).val(valueToUse).text(valueToUse);
});
}
else{
alert('Please enter a year! (any 4-digit number will do)');
$(this).val('').focus();
}
})
})
</script>
You can see a complete working example here and demonstrated below :

https://jsfiddle.net/erjc0fna/
Basically each option has a class that identifies it as lessThan18 or over18. The ones without classes are available for either case according to what you wrote. On keyup for the textbox it then calculates the age and hides/shows the correct options.

Include jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
After add ids to the input(inputId) and the 2 select(select1 and select2)
<input id="inputId" name="Year" type="text" value="" />
<select id="select1" name="Results">
<option selected="selected" value="">please choose:</option>
<option value="300">300.-</option>
<option value="500">500.-</option>
<option value="1000">1000.-</option>
<option value="1500">1500.-</option>
<option value="2000">2000.-</option>
<option value="2500">2500.-</option>
</select>
<select id="select2" name="Results">
<option selected="selected" value="">please choose:</option>
<option value="100">100.-</option>
<option value="200">200.-</option>
<option value="300">300.-</option>
<option value="400">400.-</option>
<option value="500">500.-</option>
<option value="600“>600.-</option>
</select>
Code jquery
<script>
//here the code
$( document ).ready(function() {
$("#inputId").keypress(function(e)
{
if(e.which == 13) //When you press enter key one select is hide an the other is show
{
var aux = parseInt($(this).val());
if( aux >= 1999)
{
$("#select2").show();
$("#select1").hide();
}
else
{
$("#select1").show();
$("#select2").hide();
}
}
});
});
<script>

Related

How to get values of two different select elements and use them in a function

I have two different select elements. One where a user select their gender and the second where a user selects a place they live.
I have;
<select class="selectGender" name="gender" id="styleSelect" required>
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
and
<select class="selectPlace" name="place" id="styleSelect" onchange="return checkGender()" required>
<option name="dorm" value="">None</option>
<option name="dorm" value="town" name="">Town</option>
<option name="g" value="city">City</option>
</select>
What I want is that when a user selects male as gender and selects town from other select element, he should get an alert "not allowed".
Here's what I have done so far but I get nothing from this.
function checkGender() {
let gender = document.getElementsByName('gender');
let place = document.getElementsByName('place');
if (gender.value == "male" && place.value == "town") {
alert("Not allowed");
}
}
You have error on your html code check this
enter code here
<select class="selectGender" name="gender" id="styleSelect" required >
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
enter code here
<select class="selectPlace" name="place" id="styleSelect1" onchange="checkGender()" required>
<option name="dorm" value="">None</option>
<option name="dorm" value="town">Town</option>
<option name="g" value="city">City</option>
</select>
<script>
function checkGender(){
let gender=document.getElementsByName('gender')[0].value;
let place=document.getElementsByName('place')[0].value;
console.log(gender);
console.log(place);
if (gender=="male"&&place=="town") {
alert("Not allowed");
}
}
</script>
Couple of errors with your code:
You can't have two or more elements with the same id but both of your selects have id="styleSelect".
You should add the checkGender() function to your first select too, as users not necessarily choose the second select last. Changing the first select should also fire the handler to check the values of the options.
As others have mentioned, getElementsByName returns a NodeList collection of elements with the given name. It means, you need to grab the element at the zeroth index.
You can check the working code below by clicking on the "Run code snippet" button:
function checkGender() {
let gender = document.getElementsByName('gender')[0];
let place = document.getElementsByName('place')[0];
if (gender.value === "male" && place.value === "town") {
alert("Not allowed");
}
}
<select name="gender" onchange="checkGender()" required>
<option value="">None</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<select name="place" onchange="checkGender()" required>
<option value="">None</option>
<option value="town">Town</option>
<option value="city">City</option>
</select>
Try
document.getElementsByName('gender')[0].value

Stopping form from submitting until all dropdown boxes are completed

I have created an HTML form that is generated from a PHP script. The PHP script outputs an HTML dropdown based on data held in a database. The number of dropdowns being displayed on the page varies as it is based on the number of lines in a MySQL database. All the dropdowns have the same ID inputDropdown
I am trying to create a jquery script that prevents the form from being submitted until all the dropdown boxes have been completed (So whenever the value doesn't equal No Response).
This is the HTML code outputted from the PHP Script. Please note the number in the name (E.G. "1" in dropdown_1) is generated based on the ID of a row in the database.
<select name="dropdown_1" id="inputDropdown" class="form-control">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
<select name="dropdown_2" id="inputDropdown" class="form-control">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
<select name="dropdown_3" id="inputDropdown" class="form-control">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
I tried the following jquery Code, however, this only worked for the first of the dropdowns and didn't check the other dropdown values.
$(document).ready(function () {
$("#update-form").submit(function (e) {
if ($('#inputDropdown').val() == 'No Response') {
alert('Please complete all the boxes');
}
e.preventDefault(e);
});
$("#inputDropdown").change(function () {
$("#inputDropdown").submit();
return false;
});
});
Please, could someone advise of an efficient way on how to do this?
Thank you in advance!
Your first issue is that you have repeated the same id in the DOM, which is invalid. Use a class to group the elements instead.
Then you can use filter() to find how many of the selects still have the first option selected when the form is submit. If any of them do, show the alert(). You also need to call preventDefault() at this point only. Try this:
jQuery(function($) {
$("#update-form").submit(function(e) {
var unselected = $('.inputDropdown').filter(function() {
return $(this).find('option:selected').index() == 0;
}).length;
if (unselected != 0) {
e.preventDefault(e);
alert('Please complete all the boxes');
}
});
$(".inputDropdown").change(function() {
$("#update-form").submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="update-form" action="#">
<select name="dropdown_1" class="form-control inputDropdown">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
<select name="dropdown_2" class="form-control inputDropdown">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
<select name="dropdown_3" class="form-control inputDropdown">
<option value="No Response" selected>Blank - Please Select A Option</option>
<option value="No">No</option>
<option value="Full">Yes</option>
</select>
</form>

Autoselect HTML hidden option value based on previous option

I have 2 select tags which come with the same option, male and female. One of the select, "age" is hidden.
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:none;">
<option value="12">Male</option>
<option value="18">Female</option>
</select>
When user select "male" in "gender", I wish the "age" will automatically select "male" as well. I expect the same thing as "female". How to achieve this through javascript?
You can attach an event change to your select gender and set the value of age on every change.
Note that both elements should be loaded with a default selected value for case that the end user do not select nothing and also check that it is better to move inline styling style="display:none;" to a separated css file.
Code:
var gender = document.getElementsByName('gender')[0],
age = document.getElementsByName('age')[0];
gender.addEventListener('change', function() {
age.value = (gender.value == 1) ? 12 : 18;
console.log('Gender:', gender.value);
console.log('Age:', age.value);
});
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:none;">
<option value="12">Male</option>
<option value="18">Female</option>
</select>
Here's an option using jQuery.
$(document).ready(function() {
$("#age").val("12");
$("#gender").change(function() {
var userselected = $(this).find(':selected').text();
if (userselected == "Male") {
$("#age").val("12");
} else {
$("#age").val("18");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="gender" id="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<select name="age" style="display:inherit;" id="age">
<option value="12">Male</option>
<option value="18">Female</option>
</select>

Add a text field to html dropdown

I have a html dropdown field where there should be a text field added at the bottom naming other.The text typed in this field should come as other:text
drop down html is :
<select name="drop">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
Here other should be text field.For understanding i kept other as option,but i want that to be a input text field where value is given by user.
Thanks in advance
You could add hidden input field by default for other text :
<input type='text' id='other' name='other' style="display:none"/>
And capture the change on select in your js then check if selected option value equal Other and show the field or hide it :
$('select').on('change', function(){
if($(this).val()=='Other'){
$('#other').show().focus();
}else{
$('#other').val('').hide();
}
})
Hope this helps.
$('select').on('change', function(){
if($(this).val()=='Other'){
$('#other').show().focus();
}else{
$('#other').val('').hide();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="drop">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
<input type='text' id='other' name='other' style="display:none" value='other:'/>
<script type="text/javascript">
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='Other: <input type="text" name="other" />';
else document.getElementById('div1').innerHTML='';
}
</script>
<select name="drop" id="drop" onchange="showfield(this.options[this.selectedIndex].value)">
<option selected="selected">Please select ...</option>
<option value="car">car</option>
<option value="bike">bike</option>
<option value="Other">Other</option>
</select>
<div id="div1"></div>
you could go the other way and make all options accessible by the text field - but giving an autocomplete option as the user types. This can be done with jQuery autocomplete plugins etc or the new html5 datalist. This ties a predetermined set of options to the textfield - allowing the user to select from it if theinput value matches the value, but also allows for alternative text to be entered if there are no matches. Just note though that Safari (and possible other browsers) do not support this feature yet. But its very cool when it is supported.
<input id="transportOptions" list="transport">
<datalist id="transport">
<option value="Car">
<option value="Bike">
<option value="Scooter">
<option value="Taxi">
<option value="Bus">
</datalist>

Select input changes the values of second select [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hello I have first one input which is
<select id="selectcontract" name="contract" class="input-xlarge" >
<option value="">Contract</option>
<option value="1">Buy</option>
<option value="2">Rent</option>
this input contains 2 options Buy and Rent. So I would like when you choose Buy foe example to populate the values of second and third input if you choose Rent to populate exactly those same inputs but with different values and value names.
here are the second and the third inputs:
Second Select:
<select id="Pricefrom" name="minimum_price" >
<option value="">Price From</option>
<option value="1">1</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
Third Select:
<select id="Princeuntil" name="maximum_price" >
<option value="">Price Until</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="2000">2000</option>
Any advice in which direction I should realize this goal ? I guess it should be something with jquery since the change should be made mediate when you choose either buy or rent.
You can create one div for buy and one for rent with class and after show or hide their
Example on fiddle:
https://jsfiddle.net/tehb2fxt/1/
Div Buy (is necessary change the name prop to not repeat) and add CLASS "class_price"
<select id="selectcontract" name="contract" class="input-xlarge class_price">
<option value="">Contract</option>
<option value="1">Buy</option>
<option value="2">Rent</option>
</select>
<div class="div_buy" style="display: none">
<select id="Pricefrom_buy" name="Pricefrom_buy" class="class_price">
<option value="">Price From Buy</option>
<option value="1">1</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
</select>
<select id="Princeuntil_buy" name="Princeuntil_buy" class="class_price">
<option value="">Price Until Buy</option>
<option value="500">500</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="2000">2000</option>
</select>
</div>
<div class="div_rent" style="display: none">
<select id="Pricefrom_rent" name="Pricefrom_rent" class="class_price">
<option value="">Price From Rent</option>
<option value="8">8</option>
<option value="800">800</option>
<option value="8000">8000</option>
<option value="8500">8500</option>
</select>
<select id="Princeuntil_rent" name="Princeuntil_rent" class="class_price">
<option value="">Price Until Rent</option>
<option value="900">900</option>
<option value="9000">9000</option>
<option value="9500">9500</option>
<option value="9000">9000</option>
</select>
</div>
Jquery to show and hide according with select:
<script type="text/javascript">
$(document).ready(function(){
$('#selectcontract').change
(
function()
{
if($(this).val() == "1")
{
$('.div_buy').show('slow');
$('.div_rent').hide('slow');
}
else if($(this).val() == "2")
{
$('.div_buy').hide('slow');
$('.div_rent').show('slow');
}
else
{
$('.div_buy').hide('slow');
$('.div_rent').hide('slow');
}
}
);
}
);
</script>
To control and not be in conflict 2 selects add input text(will changed to type="hidden" when finish test) for recovery values of pricefrom and princeuntil(buy and rent)
<input type="hidden" id="Pricefrom" value="0" name="Pricefrom">
<input type="hidden" id="Princeuntil" value="0" name="Princeuntil">
And add event Jquery when values class changed
$('.class_price').change
(
function () {
if($('#selectcontract').val() == "1") //if buy
{
$('#Pricefrom').val($('#Pricefrom_buy').val()); //get value select
$('#Princeuntil').val($('#Princeuntil_buy').val()); //get value select
}
else if($('#selectcontract').val() == "2") //if rent
{
$('#Pricefrom').val($('#Pricefrom_rent').val()); //get value select
$('#Princeuntil').val($('#Princeuntil_rent').val()); //get value select
}
else {//if not select
$('#Pricefrom').val("0");
$('#Princeuntil').val("0");
}
}
);
Static Lists
A simple fiddle proof of concept.
https://jsfiddle.net/cgjjg2dy/
The main part is:
$('#selectcontract').change(function (event) {
$(".section").hide();
$("#section" + $(this).val()).show();
});
I hide all the sections, then I show the one that corresponds to the option chosen. You can get even fancier with fadeOut() and fadeIn() too!
AJAX
If you want to dynamically retrieve your options from a server/database, you have to use AJAX. Instead of using .hide() and .show() in your change() handler, you just make an AJAX call and retrieve the data, then modify the DOM as necessary. Quite a bit more complex, but still the same idea.

Categories