Force unique selections from three SELECT boxes - javascript

I have three simple SELECT boxes:
<select class="select_choice" id="1">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select><select class="select_choice" id="2">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select><select class="select_choice" id="3">
<option value="0">
-- Please select
</option>
<option data-cost="15" value="6">
Leisure Sports £15
</option>
<option data-cost="0" value="1">
Three Days at the Movies £0
</option>
<option data-cost="10" value="3">
Table Tennis Camp £10
</option>
<option data-cost="6" value="4">
Beach Sports £6
</option>
<option data-cost="22" value="5">
You CAN Teach an Old Dog new Tricks £22
</option>
</select>
As you can see, they're the same SELECT (in terms of attached OPTIONS) with a different ID.
These drop-downs are for students to pick their 3 preferred choices (in order, i.e. 1st choice is favourite, 2nd choice is 2nd favourite and so on).
What I'm trying to achieve is when a student selects "TABLE TENNIS CAMP", it sets that same option in the other SELECTs to "disabled".
I can do that well enough using the following code:
$(document).ready(function() {
$('.select_choice').change(function() {
var $mc = $('span#maximumCost');
var maximumCost = parseInt( $mc.text() );
var $o = $(this).find(":selected");
var clickedSelectID = $(this).attr("id");
var obj = {};
obj.id = $o.val();
obj.selectID = clickedSelectID;
obj.name = $o.text().split(/\u00A3/g)[0];
obj.cost = $o.data("cost");
$('#choice-' + clickedSelectID).text(obj.name);
$('#choice-' + clickedSelectID).data("challenge_id", obj.id);
if( obj.cost > maximumCost )
$mc.text(obj.cost);
$('.select_choice').not(this).each(function() {
$(this).find('option[value="' + obj.id + '"]').css('background-color', 'red');
});
});
});
What I can't get my head around is how to re-enable the relevant OPTIONs when a user un-selects a choice.
I've thought about storing some jQuery data() or an array about the states of the three SELECT boxes but I'm just not bright enough to figure out how to then check those states and update the SELECT boxes accordingly. I'm also not sure if that's necessary; I suspect there's a relatively straightforward answer here.
jsFiddle: http://jsfiddle.net/Lqu4c0eb/1/

As you said, you can use the data api to store the previous selection
$('.select_choice').not(this).find('option[value="' + obj.id + '"]').prop("disabled", true);
$('.select_choice').not(this).find('option[value="' +$(this).data('prev') + '"]').prop("disabled", false);
$(this).data('prev', obj.id)
Demo: Fiddle

Related

How to make a HTML Form Button place a Dropdown form list on the screen, which the user can input text to

Is there a way to make it so that I can have a HTML form which I can have a button within, which when the user of the website clicks that button, a <select> list appears for them to use, and then can input some text alongside that, which can work multiple times? (EDIT By this I mean I would like the whole process of selecting a day and inputting text to be able to be run multiple times, by clicking the button)
My code so far has a button and the dropdown to select from, but i'm not sure how to combine them to work together multiple times.
<br><label for='odays'> Open Days: </label><br>
<input type='button' onclick='' value='Add Day'><br>
<select id='odays'name='odays'>
<option value='monday'> Monday </option>
<option value='tuesday'> Tuesday </option>
<option value='wednesday'> Wednesday </option>
<option value='thursday'> Thursday </option>
<option value='friday'> Friday </option>
<option value='saturday'> Saturday </option>
<option value='sunday'> Sunday </option>
</select>
This is my code so far
EDIT:
To clarify, this is what my intended end result is:
End Result My hope is that I can make it so that when the user clicks the 'Add Day' button, it creates another row below, for them to select a day and write into the text input. If it helps the context of this is that it is for a businesses opening hours.
It would also be appreciated if answers could be kept as simple as possible, as I am very new to HTML and JS
You can do something like this:
document.querySelector('#newEvent').addEventListener('click', function() { // when "add day" clicked:
let chosenDay = odays.selectedOptions[0].value; // take the selected option from select box
document.querySelector('#newNote legend').textContent += ' '+chosenDay; // Here i use it as title but you can do what you want
document.querySelector('#newNote input').removeAttribute('disabled'); // since we disabled it initialy
document.querySelector('#newNote').removeAttribute('style'); // show input ready for note
});
<form>
<fieldset>
<legend>My Calendar</legend>
<label for='odays'> Open Days: </label>
<input type='button' id="newEvent" value='Add Day'><br>
<select id='odays'name='odays'>
<option value='monday'> Monday </option>
<option value='tuesday'> Tuesday </option>
<option value='wednesday'> Wednesday </option>
<option value='thursday'> Thursday </option>
<option value='friday'> Friday </option>
<option value='saturday'> Saturday </option>
<option value='sunday'> Sunday </option>
</select>
</fieldset>
<fieldset id="newNote" style="display: none;">
<legend>Note For</legend>
<input type="text" placeholder="add some text" disabled>
<button type="submit">Submit</button>
</fieldset>
</form>
you can also use a prompt box
let daysPlan = "";
function updateMyday() {
var selectBox = document.getElementById("odays");
var div = document.getElementById("daysUp");
//var selectOption = selectBox.options[selectBox.selectedIndex];
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
event = window.prompt("what's up that day ?");
// to show on the page somewhere
var newDay = document.createElement("div");
newDay.textContent = selectedValue + " : " + event;
div.appendChild(newDay);
// end show
// store it , a variable, a localstorge, else ?
daysPlan += selectedValue + " : " + event + "\n"
console.log(daysPlan) // to use and send once submitting
}
#odays {
display: none;/* not sure i understood that part*/
}
form {
float: left;
}
#daysUp {
white-space: pre;
}
<form><label for='odays'> Open Days: </label><br>
<input type='button' onclick='let e =document.getElementById("odays"); e.style.display="block";' value='Add Day'><br>
<select id='odays' name='odays' onchange="updateMyday()">
<option>Choose a day </option>
<option value='monday '> Monday </option>
<option value='tuesday '> Tuesday </option>
<option value='wednesday'> Wednesday </option>
<option value='thursday '> Thursday </option>
<option value='friday '> Friday </option>
<option value='saturday '> Saturday </option>
<option value='sunday '> Sunday </option>
</select>
</form>
<div id="daysUp">
</div>

Getting duplicate values in select box, Need to remove duplicate options from select box

I want to first remove the duplicate value from the deselected values
in php or is it possible in jquery/javascript?
I'm working on edit page on my website where I need to show a SELECT box
where some values should be selected and some should be not.
I have following code after getting data from database
<select name="tour_category[]" multiple="multiple" style="height:300px;">
<option value="1" selected>Family</option>
<option value="3" selected>Wildlife</option>
<option value="4" selected>Cuisine (Food Tours & Food Walks)</option>
<option value="1">Family</option>
<option value="1">Family</option>
<option value="2">Religion & Spirituality</option>
<option value="2">Religion & Spirituality</option>
<option value="2">Religion & Spirituality</option>
<option value="3">Wildlife</option>
<option value="3">Wildlife</option>
<option value="4">Cuisine (Food Tours & Food Walks)</option>
<option value="4">Cuisine (Food Tours & Food Walks)</option>
<option value="5">Boat Trips</option>
<option value="5">Boat Trips</option>
<option value="5">Boat Trips</option>
<option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>
<option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>
<option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions)</option>
<option value="7">Weekend Gateways</option>
<option value="7">Weekend Gateways</option>
<option value="7">Weekend Gateways</option> </select>
but I need to show following output:
<select name="tour_category[]" multiple="multiple" style="height:200px;">
<option value="1" selected>Family</option>
<option value="2" selected>Religion & Spirituality</option>
<option value="3" selected>Wildlife</option>
<option value="4">Cuisine (Food Tours & Food Walks)</option>
<option value="5">Boat Trips</option>
<option value="6">Short Tours (Half Day tours/Walking Tours/Day Excursions</option>
<option value="7">Weekend Gateways</option>
</select>
If you want to achieve this, I suggest you show the option tags using a for loop or map, and you remove duplicates from the array your are mapping over. You can achieve this with ES6 by using Set.
So assume you have the following code :
const array = ['Family', 'Family', 'Wildelife', 'Wildlife'];
const uniqueSet= new Set(array);
const uniqueArray = [...uniqueSet];
//the new array will be ['Family', 'Wildlife']
Add an attribute id="tour_category" in select tag and try
$(document).ready( function(){
var a = new Array();
$("#tour_category").children("option").each(function(x){
test = false;
b = a[x] = $(this).val();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) {
test =true;
}
}
if (test) {
$(this).remove();
}
})
});

Select drop down show hide (add remove element)on I.E Browser

I have select dropdown i have 2 different shipping methods available in that dropdown. If i select sipping 1 i want to hide the Rest fexex shipping options
& vice versa if i selected any of the fedex method i want to hide freeshipping
please check js fiddle below
<fieldset>
<select name="shipping_method" id="shipping_method" style="width:250px;" class="required-entry">
<option value="">Please select a shipping method...</option>
<optgroup label="Free Shipping" style="font-style:normal;">
<option value="freeshipping_freeshipping">
Shipping1 - $0.00
</option>
</optgroup>
<optgroup label="FedEx" style="font-style:normal;">
<option value="fedex_FEDEX_GROUND">
Fedex1 - $18.07
</option>
<option value="fedex_FEDEX_2_DAY">
Fedex2 - $30.62
</option>
<option value="fedex_STANDARD_OVERNIGHT">
Fedex3 - $81.34
</option>
</optgroup>
</select>
</fieldset>
Clear Shipping Selection
<p class="actions">
<button id="update_shipping_method_submit" type="submit" class="button" style="display: none;"><span><span>Update Shipping Method</span></span></button>
</p>
jsfiddle
Try something like this(not tested)
$('select').on('change', function() {
var arr1 = $('#shipping_method option:not(:selected)');
for (var i = 0; i < arr1.length; i++) {
$("#shipping_method").children("optgroup[label='" + arr1[i].value + "']").remove();
console.log("removed");
}
})

Having problems selecting values from a <select> to put into JavaScript

This is my code. I am attempting to get values from the drop down menu and text, put them into the equation. What am I doing wrong so that the function is stopping half way through. I know it is probably really easy to solve but I cannot find a solution anywhere. Please help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h3> Question 6 </h3>
<h4> How long can you safely tan for? </h4>
<script language="javascript">
function calculate5() {
var skin = document.getElementById("skinselect");
var skinselect = Math.floor(skinselect.options[skinselect.selectedIndex].value);
var cloud = document.getElementById("cloudselect");
var cloudselect = Math.floor(cloudselect.options[cloudselect.selectedIndex].value);
var temp = Math.floor(document.getElementById("temp").value);
var time = ((skinselect + cloudselect) * temp) - 50;
alert("Your safe sunbaking time is " + time + " minutes");
}
</script>
<select id="skinselect">
<option value="error">Skin type: 0 is light, 5 is dark </option>
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
<select id="cloudselect">
<option value="error">Cloud Cover: 0 is clear, 5 is overcast </option>
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
</select>
<input type="text" value="Temperature (C)" id="temp" size="16">
<input type="button" value="Calculate" onClick="calculate5()">
</body>
</html>
inside your function you need to access option from select id
var skin = document.getElementById("skinselect");
var skinselect = Math.floor(skin.options[skin.selectedIndex].value);
var cloud = document.getElementById("cloudselect");
var cloudselect = Math.floor(cloud.options[cloud.selectedIndex].value);
var temp = Math.floor(document.getElementById("temp").value);
var time = ((skinselect + cloudselect) * temp) - 50;
you can refer
Get selected value in dropdown list using JavaScript?
In your function:
var skinselect = Math.floor(skin.options[skin.selectedIndex].value);
and
var cloudselect = Math.floor(cloud.options[cloud.selectedIndex].value);
document.getElementById("skinselect").value contains its selected option value.
Set a default value in case any option hasn't already been selected.
Eg.
<select id="skinselect" value="error">
(because error is the default value due to the fact it's on the top of the options list)

How to Pass innerHTML Argument? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript retrieving the text of the selected option in select element
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1"> Option1 </option>
<option value="2"> Option2 </option>
<option value="3"> Option3 </option>
<option value="4"> Option4 </option>
</select>
From the above example, the integer value is being passed to the showUser function by the use of this.value. If instead of passing the value, I wanted to pass the contents of whatever is inside the option tag, like "Option1", how would I do this? I have tried using
showUser(this.innerHTML)
but that doesn't seem to work, or perhaps I'm approaching it incorrectly. I've looked online at options to use getElementByID but then I think I would need a unique ID for every option.
You'd use:
showUser(this.selectedIndex >= 0 ? this.options[this.selectedIndex].text : '');
See the DOM2 HTML specification's documentation of HTMLSelectElement and HTMLOptionsElement.
HTML:
<select name="users" onchange="showUser(this)">
<option value="">Select a person:</option>
<option value="1"> Option1 </option>
<option value="2"> Option2 </option>
<option value="3"> Option3 </option>
<option value="4"> Option4 </option>
</select>
javascript:
function showUser(obj){
alert(obj.options[obj.selectedIndex].innerHTML);
}
fiddle : http://jsfiddle.net/vPhq3/1/
In this context, this refers to the <select> element, not the selected <option>. I think you want to do showUser(this.options[this.selectedIndex].innerHTML)

Categories