This question already has answers here:
How to ensure javascript addition instead of string concatenation (Not always adding integers)
(4 answers)
Closed 7 years ago.
I am trying to get the month that is 3 months from a selected month using a html select box and jquery in the below code. The code is not adding two variables together instead its treating them as two strings. Could anyone assist me to get this right?
<body>
<form role="form" class="form-inline">
<div class="form-group">
<label class="control-label" for="Q1Month">
Quarter 1 Month
</label>
<select class="form-control" id="Q1Month">
<option selected value=''>--Select Month--</option>
<option value='1'>January</option>
<option value='2'>February</option>
<option value='3'>March</option>
<option value='4'>April</option>
<option value='5'>May</option>
<option value='6'>June</option>
<option value='7'>July</option>
<option value='8'>August</option>
<option value='9'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
</div>
</form>
<script src="js/jquery.js"></script>
<script>
$(function() {
$('#Q1Month').change(function() {
var month = $(this).val();
$('#Q2Month').val(month);
var advanceby = 3;
var newmonth = month + advanceby;
window.alert(newmonth);
});
});
</script>
</body>
When any value is read from the DOM, it is string. To convert it to the Number you can use unary + operator.
Add + in front of the value
var month = +$(this).val();
+ is also the concatenation operator in Javascript, so when any one of the operand is string + is used for string concatenation.
$(function() {
$('#Q1Month').change(
function() {
var month = $(this).val();
$('#Q2Month').val(month);
var advanceby = 3;
var newmonth = month + advanceby;
window.alert(newmonth);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form role="form" class="form-inline">
<div class="form-group">
<label class="control-label" for="Q1Month">
Quarter 1 Month
</label>
<select class="form-control" id="Q1Month">
<option selected value=''>--Select Month--</option>
<option value='1'>January</option>
<option value='2'>February</option>
<option value='3'>March</option>
<option value='4'>April</option>
<option value='5'>May</option>
<option value='6'>June</option>
<option value='7'>July</option>
<option value='8'>August</option>
<option value='9'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
</div>
</form>
Because the value that you have fetched is a string!
What You need is the option index and the actual value, so try accessing the current selected options index instead of value and then add 3 and reset your required element.
Hope I helped
val() always returns string, so use parseInt() to convert string to integer before adding
$(function() {
$('#Q1Month').change(
function() {
var month = parseInt($(this).val(),10);
$('#Q2Month').val(month);
var advanceby = 3;
var newmonth = month + advanceby;
window.alert(newmonth);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form role="form" class="form-inline">
<div class="form-group">
<label class="control-label" for="Q1Month">
Quarter 1 Month
</label>
<select class="form-control" id="Q1Month">
<option selected value=''>--Select Month--</option>
<option value='1'>January</option>
<option value='2'>February</option>
<option value='3'>March</option>
<option value='4'>April</option>
<option value='5'>May</option>
<option value='6'>June</option>
<option value='7'>July</option>
<option value='8'>August</option>
<option value='9'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
</div>
</form>
Related
I'm setting up a new form on my site, and I'm using some code I found here (Vehicle drop down selector). However, I'm using this code within a form, and once the form is submitted, the values for make/model aren't changed to their respective names, instead showing their form values. Being a complete JS noob, how would I go about changing the values submitted from values to make/model names?
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
$model.html($options.filter('[value="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
var $model = $('#model'),
$year = $('#year'),
$yearOptions = $year.find('option');
$model.on('change', function() {
$year.html($yearOptions.filter('[value="' + this.value + '"]'));
$year.trigger('change');
}).trigger('change');
var $year = $('#year'),
$identifier = $('#identifier'),
$identifierOptions = $identifier.find('option');
$year.on('change', function() {
var filteredIdetifiers = $identifierOptions.filter('[value="' + this.value + '"]');
debugger
if (!($("#make").val() == 3 && $("#model option:selected").text() == 'Falcon')) {
filteredIdetifiers = filteredIdetifiers.filter(function(i, e) {
return e.value !== '3'
});
}
$identifier.html(filteredIdetifiers);
$identifier.trigger('change');
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
<option value="0">Make</option>
<option value="1">BMW</option>
<option value="2">Daewoo</option>
<option value="3">Ford</option>
<option value="4">Holden</option>
<option value="5">Honda</option>
<option value="6">Hyundai</option>
<option value="7">Isuzu</option>
<option value="8">Kia</option>
<option value="9">Lexus</option>
<option value="10">Mazda</option>
<option value="11">Mitsubishi</option>
<option value="12">Nissan</option>
<option value="13">Peugeot</option>
<option value="14">Subaru</option>
<option value="15">Suzuki</option>
<option value="16">Toyota</option>
<option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="1">318i</option>
<option class="lanos" value="2">Lanos</option>
<option class="courier" value="3">Courier</option>
<option class="falcon" value="3">Falcon</option>
<option class="festiva" value="3">Festiva</option>
<option class="fiesta" value="3">Fiesta</option>
<option class="focus" value="3">Focus</option>
<option class="laser" value="3">Laser</option>
<option class="ranger" value="3">Ranger</option>
<option class="territory" value="3">Territory</option>
<option class="astra" value="4">Astra</option>
<option class="barina" value="4">Barina</option>
<option class="captiva" value="4">Captiva</option>
<option class="colorado" value="4">Colorado</option>
<option class="commodore" value="4">Commodore</option>
<option class="cruze" value="4">Cruze</option>
<option class="rodeo" value="4">Rodeo</option>
<option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
<option value="0">Year</option>
<option value="1">1998</option>
<option value="1">1999</option>
<option value="1">2000</option>
<option value="1">2001</option>
<option value="1">2002</option>
<option value="1">2003</option>
<option value="1">2004</option>
<option value="1">2005</option>
<option value="2">1997</option>
<option value="2">1998</option>
<option value="2">1999</option>
<option value="2">2000</option>
<option value="2">2001</option>
<option value="2">2002</option>
<option value="2">2003</option>
<option value="3">1991-1999</option>
<option value="4">1997-2007</option>
<option value="5">1997-2007</option>
<option value="3">2002</option>
<option value="3">2003</option>
<option value="3">2004</option>
<option value="3">2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
<option value="0">Type</option>
<option class="E46" value="1">E46</option>
<option class="1997-2003" value="2">N/A</option>
<option class="1997-2007" value="4">N/A</option>
<option class="1997-2007" value="5">N/A</option>
<option class="5041618" value="3">BA</option>
<option class="1997-2005" value="3">AU</option>
<option class="1997-2005" value="3">AU2</option>
<option class="1997-2005" value="4">N/A</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
</select>
In every <option> tag there is an attribute called value. This value attribute is what is returned at as the value of the dropdown when that option is selected. Seems like in the code you found they are all simply set to numbers. You can set them to be whatever you want though:
<option value="Ford">Ford</option>
<option class="focus" value="Focus">Focus</option>
FIXING DYNAMIC OPTIONS
I see that modifying the values directly affect how the dynamic options are displayed. For example the value attribute of the car model dropdown is used to filter the car make dropdown by only displaying options with the same value. Instead of using the model dropdown's value attributes to compare with make, we can add a new data- attribute called data-make and filter the model dropdown based on that instead. This allows you to freely modify the value attribute in model. The example code below shows this. You would need to modify your JS so model affects year, and year affects identifier in the same way.
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
// We now filter model using the data-make attribute, not value
$model.html($options.filter('[data-make="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
$('#carForm').submit(function(e) {
e.preventDefault();
let formData = $(this).serializeArray();
let data = {};
for (let i = 0; i < formData.length; i++) {
data[formData[i].name] = formData[i].value;
}
alert('Make: ' + data.make + '\nModel: ' + data.model);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="carForm">
<select name="make" id="make">
<option value="0">Make</option>
<option value="BMW">BMW</option> <!-- These values are now make names -->
<option value="Daewoo">Daewoo</option>
<option value="Ford">Ford</option>
</select>
<!-- Vehicle Model List -->
<!-- Notice the new "data-make" attributes for each -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="318i" data-make="BMW">318i</option>
<option class="lanos" value="Lanos" data-make="Daewoo">Lanos</option>
<option class="courier" value="Courier" data-make="Ford">Courier</option>
<option class="falcon" value="Falcon" data-make="Ford">Falcon</option>
<option class="festiva" value="Festiva" data-make="Ford">Festiva</option>
<option class="fiesta" value="Fiesta" data-make="Ford">Fiesta</option>
<option class="focus" value="Focus" data-make="Ford">Focus</option>
</select>
<button type="submit">Submit</button>
</form>
You can get the selected option text like this.
$('#form').submit(function(e) {
e.preventDefault();
var make = $make.find(':selected').text();
}
But it would be good practice to set the value you expect to return as the option value and use a data attribute or class to handle the filtering logic.
This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 5 years ago.
I'm still a beginner hence this is difficult, but how do I display the options I selected into an alert box. So it would be "You selected (value), (value), (value)".
This is my select list
<form id='form1'>
<select id="options" multiple >
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>
Should I add a button. But what I'm struggling with is the javascript.
The easiest way to access selected elements of a select tag is with the "selectedOptions" property.
I would do it this way:
var form = document.getElementById('form1');
form.addEventListener('submit', function () {
var select = form.querySelector('#options'),
options = select.selectedOptions,
values = [];
for (var i = options.length - 1; i >= 0; i--) {
values.push(options[i].value);
}
alert('You selected: ' + values.join(', '));
}, false);
Try something like this:
function selectedValues()
{
var x=document.getElementById("options");
var selectedValues= '';
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
selectedValues += x.options[i].value + ", ";
}
}
alert("You selected: "+ selectedValues.slice(0, -2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='form1'>
<select id="options" multiple onchange="selectedValues()">
<option value="action">Action</option>
<option value="animation">Animation</option>
<option value="children">Children</option>
<option value="classics">Classics</option>
<option value="comedy">Comedy</option>
<option value="documentary">Documentary</option>
<option value="drama">Drama</option>
<option value="family">Family</option>
<option value="foreign">Foreign</option>
<option value="games">Games</option>
<option value="horror">Horror</option>
<option value="music">Music</option>
<option value="new">New</option>
<option value="scifi">Sci-Fi</option>
<option value="sports">Sports</option>
<option value="travel">Travel</option>
</select>
</form>
I'm running a filter for my object on a django-run website.
I have two select fields, with dropdowns based on related models to my model that i'd like to sort.
The problem is that some options are incompatible with each another and i'd like to hide the options of the second picklist based on what the user has selected on the first one.
I feel like i am going to use some JS but i've never used it before.
1st picklist: tasks <option value = task_id>
2nd picklist: crafts <option value = craft_id>
I have prepared a dictionnary that holds all the compatible values of any option selected on the first picklist, if that can help !
useful_dictionnary = {
first_task_id = [list_of_compatible_craft_ids]
...
last_task_id = [list_of_compatible_craft_ids]
}
How can i get JS to look at the task_id selected on the first picklist, and hide the options from the second picklist that are not in this list ?
Would be great! Thanks !
Here is my picklists code, if that helps
<div class="form-group col-sm-4 col-md-3">
<label for="id_tasks">Tasks:</label>
<select class="form-control" id="id_tasks" name="task">
<option value="">---------</option>
<option value="1" selected="selected">Tie-job: Front-tie Marker</option>
<option value="2">Tie-job: Scrapmachine support trackman</option>
<option value="3">Tie-job: Plate Thrower</option>
<option value="4">Tie-job: New-tie Marker</option>
</select>
</div>
<div class="form-group col-sm-4 col-md-3">
<label for="id_craft">Craft:</label>
<select class="form-control" id="id_craft" name="craft">
<option value="" selected="selected">---------</option>
<option value="1">Senior Engineer</option>
<option value="2">Roadmaster</option>
<option value="3">Foreman</option>
<option value="4">Assistant Foreman</option>
<option value="5">Electrical Welder EA</option>
<option value="6">Oxygen Welder OA</option>
<option value="7">Railway Machine Operator (RMO)</option>
<option value="8">Truck Driver (Type A, B or C)</option>
</select>
</div>
This snippet should do the trick. Change compatibleIds to map the options for the second select based on the first one.
$(document).ready(function(){
$("#id_craft option:not([value=0])").hide();
});
$("#id_tasks").change(function(){
$("#id_craft").val("0");
$("#id_craft option:not([value=0])").hide();
var compIds = { 1: [ 1,2,3,4,5], 3 : [ 4,2,3,8,7], 4 : [ 7,9,1,5], 2 :[5,3,1,8]};
for(var i = 0; i < compIds[$("#id_tasks").val()].length; i++){
$("#id_craft option[value=" + compIds[$("#id_tasks").val()][i] + "]").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-4 col-md-3">
<label for="id_tasks">Tasks:</label>
<select class="form-control" id="id_tasks" name="task">
<option value="0" selected="selected">---------</option>
<option value="1">Tie-job: Front-tie Marker</option>
<option value="2">Tie-job: Scrapmachine support trackman</option>
<option value="3">Tie-job: Plate Thrower</option>
<option value="4">Tie-job: New-tie Marker</option>
</select>
</div>
<div class="form-group col-sm-4 col-md-3">
<label for="id_craft">Craft:</label>
<select class="form-control" id="id_craft" name="craft">
<option value="0" selected="selected">---------</option>
<option value="1">Senior Engineer</option>
<option value="2">Roadmaster</option>
<option value="3">Foreman</option>
<option value="4">Assistant Foreman</option>
<option value="5">Electrical Welder EA</option>
<option value="6">Oxygen Welder OA</option>
<option value="7">Railway Machine Operator (RMO)</option>
<option value="8">Truck Driver (Type A, B or C)</option>
</select>
</div>
Small add-on as the original question was about a django dictionary object:
To use a django list or dictionnary in the javascript, it is pretty straightforward as the {{ django_variable }} works fine inside the script tags.
So the final JS for this django template page is:
$(document).ready(function(){
$("#id_craft option:not([value=0])").hide();
});
$("#id_tasks").change(function(){
$("#id_craft").val("0");
$("#id_craft option:not([value=0])").hide();
var compatibleIds = {{ my_python_dictionary }};
for(var i = 0; i < compatibleIds[$("#id_tasks").val()].length; i++){
$("#id_craft option[value=" + compatibleIds[$("#id_tasks").val()][i] + "]").show();
}
});
A very interesting thing hapens to my code.I have 3 different selects,one for years, the second for months and the third for days.I created options for the years and days via JS. My problem is my years list starts from the start point but dosn't end in the finish point I give,but when I'm changing the start point of j to 300 for instance, everything works perfectly.What is the reason or maybe my code is not correct? https://jsfiddle.net/arminemash/f9gy1p4L/15/
select{float:left}
#month,#days,input{display:none}
<body onload='addOptions()'>
<form action=''>
<select required id='year' class='selectOption' onchange='select(this)'>
<option value=""> Select year</option>
</select>
<select required id='month' class='selectOption' onchange='select(this)'>
<option value=""> Select month</option>
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<select required id='days' class='selectOption' onchange='select(this)'>
<option value="">Select Day</option>
</select>
<input type="submit" class='selectOption' onclick='getDate()'>
</form>
</body>
function addOptions(){
var x= document.getElementById('year');
var y = document.getElementById('days');
for(var i=1900,j=1;i<3000,j<=31;i++,j++){
var option1 = document.createElement("option");
var option2 = document.createElement("option");
option1.text =i;
x.add(option1);
option2.text =j;
y.add(option2);
}
}
var i=0;
function select(par){
var x=document.getElementsByClassName('selectOption');
if( par.selectedIndex !== "0"){
x[i+1].style.display='block';
i++;
collectData.push(par.value);
}
}
The problem is your for loop. for(var i=1900,j=1;i<3000,j<=31;i++,j++) this will stop when j reaches 31. What you need is two for loops one for days and one for years. I edited your fiddle here.
I need to change the 3rd field automatically depending on first two field. ( it would be best if I change 3rd field and then first 2 fields changes also )
I need a Jquery solution. Anyone can help me please?
<select id="First">
<option val="car">car</option>
<option val="phone">phone</option>
</select>
<select id="Second">
<option val="car">car</option>
<option val="phone">phone</option>
<option val="boll">boll</option>
</select>
<hr>
<select id="ChangeItAutomatically">
<option val="carcar">car car</option>
<option val="carphone">car phone</option>
<option val="carboll">car boll</option>
<option val="phonecar">phone car</option>
<option val="phonephone">phone phone</option>
<option val="phonecarboll">phone boll</option>
</select>
Is this what you're looking for?
$(document).ready(function() {
// on change for the 3rd select
$("#ChangeItAutomatically").on("change", function() {
// get the value and split on space
var value = $(this).val().split(" ");
// select the other two selects based on the values
$("#First").val(value[0]);
$("#Second").val(value[1]);
});
// on change for the first two selects
$("#First, #Second").on("change", function() {
// set the value of the 3rd select based on the combination of values of the first two
$("#ChangeItAutomatically").val($("#First").val() + " " + $("#Second").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="First">
<option val="car">car</option>
<option val="phone">phone</option>
</select>
<select id="Second">
<option val="car">car</option>
<option val="phone">phone</option>
<option val="boll">boll</option>
</select>
<hr>
<select id="ChangeItAutomatically">
<option val="car car">car car</option>
<option val="car phone">car phone</option>
<option val="car boll">car boll</option>
<option val="phone car">phone car</option>
<option val="phone phone">phone phone</option>
<option val="phone boll">phone boll</option>
</select>