Select Box option keep changing - javascript

<Select id="amount" onchange="document.formName.submit(); updateCost();">
<option id="0" value = "0"> Select amount ... </option>
<option id="1" value = "2000"> $2000 </option>
<option id="2" value = "3000"> $3000 </option>
<option id="3" value = "4000"> $4000 </option>
<option id="4" value = "5000"> $5000 </option>
</Select>
<Select id="duration" onchange="document.formName.submit(); updateCost();">
<option id="1" value="2 years"> 2 years </option>
<option id="2" value="6 years"> 6 years </option>
<option id="3" value="Lifetime"> Lifetime </option>
</Select>
function updateCost() {
var rate = 0;
if(document.formName.plan[p].checked) {
if(value('coverageUser').indexOf('Enrolled') > -1){
rate = getRate();
}
payCycle = 1;
document.formName.cost.value = formatCurr((rate) * payCycle);
}
}
I have these two select boxes and when I choose an option from first, cost is getting updated correctly. But after selecting amount, I am supposed to select duration from second selectbox where default value is 2 years. But when I change the value to 6 years, cost is updated , but the select box option does not remain to 6 years, but changes back to 2 years. How do I keep the option I selected in second select box and also update the cost correctly?

The select boxes don't keep their state because of the submit you're doing at onchange().
It will cause page reload on every change. Try remove it from both select's.
Besides that, you're using id in a wrong way: you can't have the same id twice in a same page. Try something like this:
<option value="1"> 2 years </option>
<option value="2"> 6 years </option>
<option value="3"> Lifetime </option>

When you return the page after a form submit:
Mark the user's selected options with the selected attribute:
<select id="duration">
<option value="2 years"> 2 years </option>
<option value="6 years" selected> 6 years </option>
<option value="Lifetime"> Lifetime </option>
</select>
Call updateCost() on page load:
window.onload = updateCost;
Or add it to your window.onload function if you already have one:
window.onload = function() {
...
updateCost();
};

Related

How to pass two user input dates through url

I have a requirement where I need to pass two dates(DateFrom and DateTo) through the URL using <a href> which goes to another page where it shows the report of that dates.both the dates are in format yyyy-mm-dd.
below is the code I'm using.
here DateFrom and DateTo in the URL will be the dates that the user selects.
I have used radio buttons to select the columns to be generated in the report. user will choose either 1st set of columns or 2nd set of columns. and the chosen set of columns will be shown in the report.
After choosing from date, to date, and set of columns, the user will click on the generate report button which goes to the other page where it shows the report.
How shall I pass those two date values and radio button conditions for selecting columns.
the UI is in FTL(freemarker). I'm also attaching an image of the UI for better understanding.
there are two different URLs for two different sets of columns.
the URLs are
1st set of columns: http://localhost:9191/preview?__report=production_1.rptdesign&__format=pdf&DateFrom=2022-06-10&DateTo=2022-06-10
2nd set of columns: http://localhost:9191/preview?__report=production_2.rptdesign&__format=pdf&DateFrom=2022-06-10&DateTo=2022-06-10
if the user selects 1st set of columns one <a href> will be used and if the user selects 2nd set of columns another <a href> will be used. I haven't completed the coding part yet. how shall I achieve this in FTL?
<input type="date" id="quality-fromdate">
<input type="date" id="quality-toDate">
<input id="radiobutton1" type="radio" name="radio-button">
<div class="select-columns-options-1" id="select-columns-options1">
<option value="tasks">Product Name</option>
<option value="tasks">Order Id</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
<option value="tasks">Due Date</option>
<option value="tasks">Estimated Completion Time</option>
</div>
<input id="radiobutton2" type="radio" name="radio-button">
<div class="select-columns-options-2">
<option value="tasks">Product Name</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
</div>
Generate Report
I wouldn't use <a> here, since the url has to be generated dynamically. Here's an example using a button and figuring out the url when the button is clicked. If you absolutely have to use <a>, you'd probably have to bind into the change events of the dates and the radios and update the href of the <a> that way.
const btnclick = () => {
let radio = document.querySelector("input[type='radio']:checked").id === "radiobutton1" ? 1 : 2;
let from = document.querySelector("#quality-fromdate").value;
let to = document.querySelector("#quality-toDate").value;
console.log(`http://localhost:9191/preview?__report=production_${radio}.rptdesign&__format=pdf&DateFrom=${from}&DateTo=${to}`)
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
To: <input type="date" id="quality-fromdate"> From: <input type="date" id="quality-toDate">
<br/>
<input id="radiobutton1" type="radio" name="radio-button" checked>
<select class="select-columns-options-1" id="select-columns-options1">
<option value="tasks">Product Name</option>
<option value="tasks">Order Id</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
<option value="tasks">Due Date</option>
<option value="tasks">Estimated Completion Time</option>
</select>
<br/>
<input id="radiobutton2" type="radio" name="radio-button">
<select class="select-columns-options-2">
<option value="tasks">Product Name</option>
<option value="tasks">Quantity Ordered</option>
<option value="tasks">Quantity To Produce</option>
</select>
<br/>
<button onclick="btnclick()">Generate Report</button>
You had quite a bit to go, here is working version using eventListener and URL object
I am not testing the dates
You also needed to be more consistent with IDs etc. I assume your link needed the two selects (they were divs in your code)
const url = new URL("http://localhost:9191/preview?__format=pdf")
const linkSpan = document.getElementById("link");
const dateFrom = document.getElementById("quality-fromDate")
const dateTo = document.getElementById("quality-toDate")
const reportType1 = document.getElementById("select-columns-options1");
const reportType2 = document.getElementById("select-columns-options2");
document.getElementById("reportDiv").addEventListener("click", function(e) {
linkSpan.innerHTML = "";
const reportRad = document.querySelector("[name=radio-button]:checked")
if (!reportRad) return;
if (reportType1.selectedIndex < 1 || reportType2.selectedIndex < 1) return; // nothing selected
url.searchParams.set("__report", reportRad.id === "radiobutton1" ? "production_1.rptdesign" : "production_2.rptdesign")
url.searchParams.set("__reportType1", reportType1.value);
url.searchParams.set("__reportType2", reportType2.value);
url.searchParams.set("DateFrom", dateFrom.value)
url.searchParams.set("DateTo", dateTo.value)
linkSpan.innerHTML = `${reportType1.options[reportType1.selectedIndex].text} - ${reportType2.options[reportType2.selectedIndex].text}`;
})
<div id="reportDiv">
<input type="date" id="quality-fromDate">
<input type="date" id="quality-toDate">
<input id="radiobutton1" type="radio" name="radio-button">
<select class="select-columns-options-1" id="select-columns-options1">
<option value="pname">Product Name</option>
<option value="oid">Order Id</option>
<option value="qo">Quantity Ordered</option>
<option value="qp">Quantity To Produce</option>
<option value="ddd">Due Date</option>
<option value="ect">Estimated Completion Time</option>
</select>
<input id="radiobutton2" type="radio" name="radio-button">
<select class="select-columns-options-2" id="select-columns-options2">
<option value="pname">Product Name</option>
<option value="qo">Quantity Ordered</option>
<option value="qtp">Quantity To Produce</option>
</select>
<span id="link"></span>
</div>

How to apply different section to a radio button

I have this project for school, to show different drop-down option for each selected radio button. I tried few JavaScript code but it wasn't working at all.
I need when clicked on Sizes radio button to show the correspondent sizes drop-down selectors.
As well for the colors. To show only colors drop-down selectors
Thank you in advance for the help.
Bellow is the code
<form>
<fieldset>
<p>
<input type = "radio"
name = "sizes"
id = "sizes"
value = ""
checked = "checked">
<label for = "sizes"> Sizes </label>
<input type = "radio"
name = "colors"
id = "colors"
value = "">
<label for = "colors"> Colors </label>
</p>
</fieldset>
</form>
<label for="small-size"> Small Size </label>
<select name="size" id="size">
<option value="1" selected> Size 1 </option>
<option value="2"> Size 2 </option>
<option value="3"> Size 3 </option>
</select>
<label for="big-size"> Big Size </label>
<select name="size" id="size">
<option value="1" selected> Size 1 </option>
<option value="2"> Size 2 </option>
<option value="3"> Size 3 </option>
</select>
<label for="dark"> Dark Colors </label>
<select name="canvas" id="canvas">
<option value="1" selected> Color 1</option>
<option value="2"> Color 2 </option>
<option value="3"> Color 3 </option>
</select>
<label for="light"> Light Colors </label>
<select name="canvas" id="canvas">
<option value="1" selected> Color 1</option>
<option value="2"> Color 2 </option>
<option value="3"> Color 3 </option>
</select>
https://jsfiddle.net/Farsoun/dw813ky2/9/
You should really show at least an attempt of some sort when posting something like this, especially with the JavaScript tag.
Anyways, to do this you would want to listen to when a user clicks on a radio button and show/hide the corresponding elements.
Here's a sample:
document.getElementById('colors').addEventListener("click", function(e){
document.getElementById("colors-selections").style.display = "block";
document.getElementById("size-selections").style.display = "none";
});
If you have more than two elements in the future, I'd recommend using an onchange so you can hide it once it's untoggled rather than hiding everything else everytime a new radio button is clicked.
If you want to use just CSS you're going to have to used the :checked attribute and hide or display another element also:
Other users already have asked about this, ex:
https://stackoverflow.com/a/50921066/4107932

How can I set the default value for an HTML <select> element with JavaScript?

How to set the 'selected' (default) value for an HTML <select> element with JavaScript. Aka. currently option0 is 'selected', how to run a script to change it to display the value i want?
this for example because that value is previously saved in a database, and i only want it updated if the user actually specifies to do so. But if i don't specify the value (by re-selecting the previous option), saving the 'edit' will overwrite the previous value with the 'default selected' value the <select> is loaded with.
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
NOTE: Because i lack reputation to add my answer (below) to the general thread on this topic, here the solution i got to using javascript, to set an option to be the option displayed/selected in the selector. This can also be a <%= value %> from a database.
Use value property to set new selected value using JavaScript
document.getElementById('selector').value="2";
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
<script>
let options = document.getElementsByTagName('option');
for(i=0; i<options.length; i++){
if (options[i].value === "<%= or_some_string %>"){
options[i].selected = true;
}
}
</script>
We get all the options (this is an html collection) and iterate over it to check if any option is equal to the "String" or "<%=string_value_from_database%>". And set it's .selected to true.
NOTE - MAYBE BETTER - DEFFO SHORTER: with help in the comments:
<script>
let to_select = document.getElementById('selector');
to_select.value = "<%= value %>";
</script>
Where to_select.value is either set to the value you want, or to a database value. Do note, you may or may not need the ".." around the value you set, depending on the setup of the <select> and how you stored your data.
use this
document.getElementById("selector").selectedIndex = 3;
original

Pushing data values of a multiple select Only pushes the first clicked option multiple times

I came accross a problem while using Javascript . I have a multiple select who I want to get all the data-type selected then push it to an array . But I got stuck in the first step of getting the data selected. It only Gets the first option selected then when i click on the other one it pushes again the same first value.
Here is my code :
<select multiple id="boox" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>
My Javascript Code :
var options = [];
$('#box').change(function() {
options.push($('#box').find("option:selected").data("type"));
console.log(options);
});
For example if I select item 2 it returns in the console :
22
Then If I click on item 3 , it returns :
22,22
I Hope someone could clarify what I am doing wrong.I will appreciate it !
Basically you need to loop through all the selected options and push the value to your options array. In below code I use jQuery each() function to loop through all the selected options and store their value in options array:
var options =[];
$('#box').change(function(){
options =[];
$('#box').find("option:selected").each(function(){
options.push($(this).data("type"));
})
console.log(options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple id="box" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>
Do it like this. Use change event and then access value.
var optVal = [];
var tempVal = [];
$(".box").change(function() {
$(".box option").each(function() {
var val = $(this).val();
var tempVal = $(".box").val();
if(tempVal.indexOf(val) >= 0 && optVal.indexOf(val) < 0) {
optVal.push(val);
console.log("Opt: " + optVal);
} else if(tempVal.indexOf(val) < 0 && optVal.indexOf(val) >= 0) {
optVal.splice(optVal.indexOf(val) , 1);
console.log("Opt: " + optVal);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<select multiple class="box" name="box[]" class="selectpicker form-control" data-live-search="true" data-size="4" required>
<option value="1" data-type="11">item 1 </option>
<option value="2" data-type="22">item 2 </option>
<option value="3" data-type="33">item 3 </option>
<option value="4" data-type="44">item 4 </option>
</select>

not allow select same value with two dropdown

I want to prevent the user from selecting the same value twice in this form
<select name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<option> Applied Information and Communication Technology</option>
<option> Arabic</option>
<option> Art and Design</option>
<option> Biology</option>
<option> Business Studies</option>
</select>
<select name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<option> Applied Information and Communication Technology</option>
<option> Arabic</option>
<option> Art and Design</option>
<option> Biology</option>
<option> Business Studies</option>
</select>
I'm not sure how you're selecting the elements, so I'll give them an ID for simplicity.
Example: http://jsfiddle.net/x4E5Q/1/
function preventDupes( select, index ) {
var options = select.options,
len = options.length;
while( len-- ) {
options[ len ].disabled = false;
}
select.options[ index ].disabled = true;
if( index === select.selectedIndex ) {
alert('You\'ve already selected the item "' + select.options[index].text + '".\n\nPlease choose another.');
this.selectedIndex = 0;
}
}
var select1 = select = document.getElementById( 'select1' );
var select2 = select = document.getElementById( 'select2' );
select1.onchange = function() {
preventDupes.call(this, select2, this.selectedIndex );
};
select2.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
};
html
<select id="select1" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<!-- ...and so on... -->
<select id="select2" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<!-- ...and so on... -->
EDIT: Changed to deal with browsers that don't support .disabled. Credit to #Zoidberg.
Ultimately, if you can afford the real-estate i would use Radio buttons instead, or checkboxes and only allow them to select 2 check boxes at the most. To me drop downs don't work in this situation
However, if you don't have the real-estate and you must use dropdowns, then your best bet, is once they have selected a value in the first drop down, disable or remove it in the second dropdown, and vice versa (incase they select a value in the first one). I would recommend disabling as opposed to removing, as it will be more apparent to the user what is going on.
<select id="subject1" onchange="updateSelect(this,'subject2');" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>
<select id="subject2" name="indication_subject[]" onchange="updateSelect(this,'subject1');" >
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>
Then the js that goes with it
function updateSelect(changedSelect, selectId) {
var otherSelect = document.getElementById(selectId);
for (var i = 0; i < otherSelect.options.length; ++i) {
otherSelect.options[i].disabled = false;
}
if (changedSelect.selectedIndex == 0) {
return;
}
otherSelect.options[changedSelect.selectedIndex].disabled = true;
}
The only problem is, IE 7 and earlier doesn't support disabled. If this is a deal breaker than you will have to go with removing the option from the Other Select, and then replace it later. Only issue with this is that it will change the order of options, unless you refresh the whole list. To refresh the whole list, you will need to store the options and values in an array (kinda like a model) that never changes and is used to update the selects when the change event occurs.
try this, add id="indication_subject1" in select 1.
and id="indication_subject2" in select 2.
Javascript:
$('#indication_subject1').change(function(){
var indication_subject1 = $('#indication_subject1').val();
var indication_subject2 = $('#indication_subject2').val();
if (indication_subject1 == indication_subject1)
{
$('#indication_subject2').prop('selectedIndex',0);// val = "" selected, or you can add alert('Can't select same value!')
}
});
$('#indication_subject2').change(function(){
var indication_subject1 = $('#indication_subject1').val();
var indication_subject2 = $('#indication_subject2').val();
if (indication_subject2 == indication_subject1)
{
$('#indication_subject1').prop('selectedIndex',0);
}
});

Categories

Resources