How to link two dynamically populated select boxes? - javascript

I have two dynamically populated selectboxes with data coming from same json object within the page. What I want to achieve is to link the two boxes so that whenever there is a change in one select box the same option in other select box gets automatically disabled.
So suppose Xiomi and the corresponding second value Xiomi Redme is selected in first selectboxes then the same option Xiomi Redme should not be available for selection in the other select box
<div>
<select id="brand-select" name="Brand">
<option value=''>Select Brand</option>
<option value='300'>Xiomi</option>
<option value='147'>HTC</option>
</select>
</div>
<div>
<select id='mobile_model_select' name='Mobile_Brand_Models' style='width:208px;'></select>
</div>
<div>
<select id="brand-select_product2" name="Brand">
<option value=''>Select Brand</option>
<option value='300'>Xiomi</option>
<option value='147'>HTC</option>
</select>
</div>
<div>
<select id='mobile_model_select_product2' name='Mobile_Brand_Models_For_Product2' style='width:208px;'></select>
</div>
Here is my jquery code
$(document).ready(function(){
var modelData = {
"300":{
"MI3_16GB":"XIAOMI Mi3 (16GB)",
"REDMI_NOTE":"XIAOMI REDMI NOTE",
"REDMI":"XIAOMI Redmi ",
"REDMI_1S":"XIAOMI REDMI 1S"
},
"147":{
"ONE_M8":"HTC One (M8)",
"DESIRE_610":"HTC Desire 610",
"ONE_E8":"HTC ONE E8"
}
};
$('#brand_select').change(function(){
correspondingId = $(this).find(":selected").val();
var correspondingIdObject = modelData[correspondingId];
$('#mobile_model_select option').remove();
$.each(correspondingIdObject, function(key, value){
$('#mobile_model_select').append($("<option>").text(value).attr('value',key));
});
$('#brand_select_product2').change(function(){ //
correspondingSelectedIdObject = $(this).find(":selected").val();
$('#mobile_model_select_product2 option').remove();
$.each(correspondingSelectedIdObject, function(key, value){
$('#mobile_model_select_product2').append($("<option>").text(value).attr('value',key));
});
});
My problem is how to link the two onchange functions so that whenever the value is changed in one the same option in the other select box is disabled.

for (var i=0; i<selects.length; i++) {
$(selects[i]).find('option').removeAttr('disabled');
for (var j=0; j<vals.length; j++) {
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
have a look at this fiddle .. hope this helps u ...
JSFiddle
credits : #Skwal

Related

How to get my javascript to look for class or anything other than val

I have a javascript script that looks for the value and of dropdown and changes the next dropdown menu based on what the value is, however this will no longer work for me as i need to pass the value back to ruby so i can save it in sessions.
$(document).ready(function() {
$('#Exposures').bind('change', function() {
var elements = $('div.exposures').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if something is selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
$('.second-level-select').bind('change', function() {
var elements = $('div.second-level-container').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if something is selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select class="pmmargin3 exp" size="1" id="Exposures" title="" name="exposures_pt1">
<option selected disabled hidden style='display:none' value=''>-Please select an option-</option>
<option value="1">thing1</option>
<option value="1">thing2</option>
<option value="2">thing3</option>
<option value="1">thing4</option>
<option value="3">thing5</option>
</select>
<div class="container exposures leftmargin exp">
<div class="1">
<select class="second-level-select" name="exposures_pt2a">
<option selected disabled hidden style='display:none' value=''>- Please select an option-</option>
<option value="guardrail_system">thing1</option>
<option value="personal_fall">thing2</option>
<option value="safety_net">thing3</option>
</select>
</div>
<div class="2">
<select class="second-level-select" name="exposures_pt2b">
<option selected disabled hidden style='display:none' value=''>-Please select an option-</option>
<option value="guardrail_system">thing1</option>
<option value="personal_fall">thing2</option>
<option value="safety_net">thing3</option>
<option value="infeasibility_option">thing4</option>
</select>
</div>
<div class="3">
<select class="second-level-select" name="exposures_pt2c">
<option selected disabled hidden style='display:none' value=''>-Please select an option-</option>
<option value="current_subpart">thing5</option>
<option value="proposed_subpart">thing6</option>
</select>
</div>
</div>
Thank you for any help, I'm fairly new to Javascript and am trying my best but still need some guidance.
As per what I understood. You want to send data selected in first dropdown to ruby to save it in Session.
If that is the case, on every select you can trigger AJAX call with cookies and update the session object accordingly and also subsequently display it in second dropdown as well.
Though, onChange AJAX is not a really good suggestion, in that scenario you can save selected option into browser sessionStorage and later add it to session object by a single ajax to your server at the end of your selection(dropdown) cycle.
Well i figured out how to get my results back and keep the value the same in my code so nothing else breaks here is how i did it.
$(document).ready(function() {
$('#Exposures').bind('change', function() {
var elements = $('div.exposures').children().hide(); // hide all the elements
var value = $(this).val();
*added* var exposuredd = document.getElementById("Exposures");
*added* var selectedText = exposuredd.options[exposuredd.selectedIndex].text;
*added* document.getElementById("exp1").innerHTML="<input type='text' name='exposures_pt1' value='"+selectedText+"' >";
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
$('.second-level-select').bind('change', function() {
var elements = $('div.second-level-container').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});
this needs to be in the erb im using this in
<p hidden id="exp1"></p>
So now i can pass whatever text is in my options to ruby such as...."Hey Here I am"
<option value="1">Hey Here I am</option>

remove selected value from select box using jquery but It's need to display current selected value in select box?

I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>

how do I show all the selected options in the text field

how do I get my javascript to show more than one selected in de text field I am planning on adding way more 's so I don't want to make a insane long array
function myFunction() {
var skilllist = document.getElementById("skilllist");
console.log(skilllist.selectedIndex);
document.getElementById("skillfield").value = skilllist.options[skilllist.selectedIndex].text;
}
<form>
Select your favorite browser:
<select name="skillist[]" id="skilllist" multiple>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="Javascript">Javascript</option>
<option value="PHP">PHP</option>
<option value="Laravel">Laravel</option>
<option value="Wordpress">wordpress</option>
</select>
<p>jouw skills zijn: <input type="text" id="skillfield" size="50"></p>
</form>
</div>
I suggest adding an event handler on blur event to the select element.
With such an approach you are able to select one or more list items and dynamically render their text content.
document.getElementById("skilllist").addEventListener('blur', function(e){
var options = e.target.options,
selected_content = "";
for (var i = 0; i < options.length; i++) {
if (options[i].selected) selected_content += options[i].textContent + ", ";
}
document.getElementById("skillfield").value = selected_content;
});
https://jsfiddle.net/zLyw7vhd/
For mobile devices : try to replace event name 'blur' to 'focusout'
(or 'change') in addEventListener function

Button to add selected="selected" from outside form

I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.
Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>
For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>
Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.

enable or disable option from select

I am trying to make an option either selectable OR non-selectable based on whether or not they chose another option. For example, if there is options 1-6 and they have NOT chosen option 1 in their first select box, then in that SAME select box and any other in the form, then option 6 could NOT be chosen.
I looked around, but everything is about clicking a button to achieve this.
This is the code I have (I have also tried onclick)
<script type="text/javascript">
function makeDisable(){
var x=document.getElementById("mySelect2");
x.disabled=true
}
function makeEnable(){
var x=document.getElementById("mySelect2");
x.disabled=false
}</script>
<form>
<select class="mySelect" id="mySelect">
<option onchange="makeEnable()" value="Enable list">Apple</option>
<option onchange="makeDisable()" value="Disable list">Banana</option>
<option id="mySelect2" disabled="true">Orange</option>
</select>
</form>
Option elements don't have event "onchange", but Select elements do.
I've quickly wrote a code snippet below. You may add more select items. When you choose an option in one of those select elements, you shouldn't choose options at same index in other select elements.
function toggleDisability(selectElement) {
//Getting all select elements
var arraySelects = document.getElementsByClassName('mySelect');
//Getting selected index
var selectedOption = selectElement.selectedIndex;
//Disabling options at same index in other select elements
for (var i = 0; i < arraySelects.length; i++) {
if (arraySelects[i] == selectElement)
continue; //Passing the selected Select Element
arraySelects[i].options[selectedOption].disabled = true;
}
}
<form>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect1">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
<option>Hamburger</option>
<option>Pizza</option>
<option>Cola</option>
</select>
</form>

Categories