Select child elements when parent ID is selected - javascript

I made a multi-choice select box. I used select2.
I want all child elements to be selected when Parent is selected.
For example, when ex1 is selected, every element should be selected.
When ex2 is selected, 4,5,7,8,9 and itself should be selected.
I tried to create a loop for this, but it just didn't make sense because there could be too many elements under each other.
jsfiddle link here https://jsfiddle.net/ph40eomt/2/
Thanks for the help in advance.
$('.js-select2-custom').select2({
"minimumResultsForSearch": "Infinity",
"singleMultiple": true,
})
function selectNumber() {
let select = $('.js-select2-custom')
select.next('span.select2').find('ul').html(function() {
let count = select.select2('data').length
return "<li style='font-size: 14px;line-height: 26px;color: black;'>" + count + " units Selected" + "</li>"
})
}
selectNumber()
$('.js-select2-custom').on('select2:close', function() {
let select = $(this)
$(this).next('span.select2').find('ul').html(function() {
let count = select.select2('data').length
return "<li style='font-size: 14px;line-height: 26px;color: black;'>" + count + " units Selected" + "</li>"
})
})
$('.js-select2-custom').on('select2:select', function(e) {
var data = e.params.data;
var userArrOptions = $("select[name='organizationUnitSelect'] option")
var i;
for (i = 0; i < userArrOptions.length; i++) {
var childId = $(userArrOptions[i]).attr("data-parent-id")
var selectedChildId = []
if (data.id == childId) {
var selectedOption = $('.js-select2-custom option[data-parent-id=' + childId + ']')
selectedOption.prop('selected', true);
}
}
$('.js-select2-custom').select2({
"minimumResultsForSearch": "Infinity",
"singleMultiple": true,
})
selectNumber()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<select class="js-select2-custom form-control" multiple name="organizationUnitSelect">
<option class="options" value="1" data-parent-id="">ex1</option>
<option class="options" value="2" data-parent-id="1">ex2</option>
<option class="options" value="3" data-parent-id="1">ex3</option>
<option class="options" value="4" data-parent-id="2">ex4</option>
<option class="options" value="5" data-parent-id="2">ex5</option>
<option class="options" value="6" data-parent-id="3">ex6</option>
<option class="options" value="7" data-parent-id="4">ex7</option>
<option class="options" value="8" data-parent-id="4">ex8</option>
<option class="options" value="9" data-parent-id="7">ex9</option>
</select>
</div>

Related

Get custom attribute value from select

I'm trying to clone a select options into another select. At the moment I'm able to do it but now the original option contains a custom attribute. So my question is how can I access to the custom attribute? This is what I have for now:
var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
var id = parseInt($(options[i]).val(), 10);
var text = $(options[i]).text() || '[select a type]';
arrayOptions.push('<option value="' + id + ' data-custom="' + options[i]["data-custom"] + '">' + text + '</option>');
}
console.log(arrayOptions);
<select id="sel1">
<option value="1" data-custom="abc1">Hello 1</option>
<option value="2" data-custom="abc2">Hello 2</option>
<option value="3" data-custom="abc3">Hello 3</option>
</select>
Right now options[i]["data-custom"] is setting undefined instead of abc1, abc2, etc.
Here is a fiddle.
You can use dataset.custom
var options = $('#sel1 option');
var arrayOptions = [];
for (var i = 0; i < options.length; i++) {
var id = parseInt($(options[i]).val(), 10);
var text = $(options[i]).text() || '[select a type]';
arrayOptions.push('<option value="' + id + ' data-custom="' + options[i].dataset.custom + '">' + text + '</option>');
}
$('#result').text(arrayOptions.join("\n"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel1">
<option value="1" data-custom="abc1">Hello 1</option>
<option value="2" data-custom="abc2">Hello 2</option>
<option value="3" data-custom="abc3">Hello 3</option>
</select>
<pre id="result"></pre>
this way
const arrayOptions =
[...document.querySelectorAll('#sel1 option')]
.map( opt => `<option value="${opt.id}" `
+ `data-custom"${opt.dataset.custom}">`
+ `${opt.textContent}"</option>`
)
console.log(arrayOptions);
<select id="sel1">
<option value="1" data-custom="abc1">Hello 1</option>
<option value="2" data-custom="abc2">Hello 2</option>
<option value="3" data-custom="abc3">Hello 3</option>
</select>

Trigger change for custom attr select 2

I have a select option that uses select 2 plugin like this
<select id ="temp">
<option value="1" data-width="24" data-length="12">First</option>
<option value="3" data-width="32" data-length="24" >Second</option>
<option value="1" data-width="16" data-length="16" >Third</option>
<option value="1" data-width="8" data-length="4" >Fourth</option>
</select>
I want to get data width and length from user inputs from keyboard. I call them is customWidth and customLength.
Expert results:
When user type true customWidth and customLength select2 trigger
change selected value. Example: customWidth = 8 and customLength =
4, select 2 should be trigger selected this option
<option value="1" data-width="8" data-length="4" >Fourth</option>
Thank you for help.
You can achieve this by finding an option that has same width and length by data attribute the, if found select it then trigger change so the slect2 take new val .
See below working snippet :
$(function() {
$customWidth = $("#customwidth");
$customLength = $("#customlength");
$customWidth.on("input", function(e) {
if( $customLength.val() && this.value ) {
var el = $("#temp").find('option[data-width=' + this.value + '][data-length=' + $customLength.val() + ']');
if (el.length > 0)
el.attr('selected', 'selected').trigger("change");
}
});
$customLength.on("input", function(e) {
if( $customWidth.val() && this.value ) {
var el = $("#temp").find('option[data-width=' + $customWidth.val() + '][data-length=' + this.value + ']');
if (el.length > 0)
el.attr('selected', 'selected').trigger("change");
}
});
$('#temp').select2({
placeholder: 'Select'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
customWidth : <input id="customwidth" /><br/><br/> customLength : <input id="customlength" /><br/><br/>
<select id="temp" style="width: 300px">
<option></option>
<option value="1" data-width="24" data-length="12">First</option>
<option value="3" data-width="32" data-length="24">Second</option>
<option value="1" data-width="16" data-length="16">Third</option>
<option value="1" data-width="8" data-length="4">Fourth</option>
</select>
This is perfectly working only for width. Try yourself to implement length too.
HTML
<select id ="temp">
<option value="1" data-width="24" data-length="12">First</option>
<option value="3" data-width="32" data-length="24" >Second</option>
<option value="1" data-width="16" data-length="16" >Third</option>
<option value="1" data-width="8" data-length="4" >Fourth</option>
</select>
<input type="text" id="width">
JQUERY
$('#temp').select2({
});
$('#width').keyup(function(){
var widthVal= $(this).val()
$("#temp option").each(function(){
if($(this).attr('data-width')==widthVal){
$('#temp option[data-width="'+widthVal+'"]').prop('selected','selected').change()
}
})
})

select option based on all values in an input

I have a simple reservation form. In this form, I have two input box and I change number of each room based on value of input hidden with class name "rooms", moreover there is another input that shows
numbers like this: 1 ,8*1 ,11
the first digit shows a count of person and the second digit after comma shows the age of that person in the first room.
I separated first and second rooms with a star between them. the digits after star shows count and age of each person in the second room as well.
my question is how can I use these digits for selecting my select boxes?
for example, I want to use the first digit for select box child. if that number was 1. i would choose 1 in first room for my child . also second number for age of first child in my first room and etc.
I wrote the below code with function fillchild but it does not work .
here is my snippet :
$(document).ready(function() {
$('#rooms').val($('.rooms').val());
$('#rooms').change()
})
$("#rooms").change(function() {
countRoom = $(this).val();
$(".numberTravelers").empty()
for (i = 1; i <= countRoom; i++) {
$(".numberTravelers").css("width", "100%").append('<div class="countRoom"><div class="numberOfRooms">room' + i + '</div><div class="col-xs-4">child<select name="childcount" class="childcount" onchange="childAge(this)"><option value="0"> 0 </option><option value="1"> 1 </option> <option value="2"> 2 </option></select></div><div class="selectAge col-xs-4"></div><input type="hidden" name="_root.rooms__' + i + '.childcountandage" class="childcountandage"/></div>')
}
});
function childAge(a) {
$(a).each(function() {
age = $(a).val();
$(a).closest(".countRoom").find(".selectAge").empty();
for (var j = 1; j <= age; j++) {
$(a).closest(".countRoom").css("width", "100%").find(".selectAge").append('<div class="age"><label>child age' + j + '</label><select name="childage" class="childage form-control"><option value="1">till 1 year</option><option value="2">1-2 year</option><option value="3">2-3 year</option><option value="4">3-4 year</option></select></div>');
}
fillchild();
});
}
function fillchild() {
var childCounts = $('.childage').val().split(',');
var ageCounts = $('.childage').val().split('*');
childCounts.forEach((childage, index) => {
var selectname = '_root.rooms__' + (index + 1) + '.childcountandage';
var selectElement = $('input[name="' + selectname + '"]');
if (selectElement.length > 0) {
$(selectElement).val(childage);
}
})
}
.numberOfRooms {
border: 1px solid red;
}
.childage {
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="researchii">
<input type="hidden" class="rooms" value="2" />
<input type="text" class="childage" value="1 ,8*1 ,11" readonly />
<div class="col-xs-4">
<span class="itemlable">rooms: </span>
<select name="rooms" id="rooms">
<option value="1" class="btn2"> 1 </option>
<option value="2" class="btn2"> 2 </option>
</select>
</div>
<div class="numberTravelers">
<div class="countRoom">
<div class="col-xs-4">
<span class="itemlable">child</span>
<select name="childcount" class="childcount" onChange="childAge(this)">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div class="selectAge col-xs-4"></div>
<input type="hidden" name="_root.rooms__1.childcountandage" class="childcountandage" />
</div>
</div>
</div>
I have made it dynamic so that it still works for 2 child with age 3 and 4. You can see that example below.
$(document).ready(function() {
$('#rooms').val($('.rooms').val());
$('#rooms').change()
})
$("#rooms").change(function() {
countRoom = $(this).val();
$(".numberTravelers").empty()
for (i = 1; i <= countRoom; i++) {
$(".numberTravelers").css("width", "100%").append('<div class="countRoom"><div class="numberOfRooms">room' + i + '</div><div class="col-xs-4">child<select name="childcount" class="childcount" onchange="childAge(this)"><option value="0"> 0 </option><option value="1"> 1 </option> <option value="2"> 2 </option></select></div><div class="selectAge col-xs-4"></div><input type="hidden" name="_root.rooms__' + i + '.childcountandage" class="childcountandage"/></div>')
}
fillchild();
});
var ageGlobal ='';
function childAge(a) {
$(a).each(function() {
age = $(a).val();
ageGlobal = ageGlobal.split(',');
$(a).closest(".countRoom").find(".selectAge").empty();
for (var j = 1; j <= age; j++) {
$(a).closest(".countRoom").css("width", "100%").find(".selectAge").append('<div class="age"><label>child age' + j + '</label><select name="childage" class="childage form-control"><option value="1">till 1 year</option><option value="2">1-2 year</option><option value="3">2-3 year</option><option value="4">3-4 year</option></select></div>');
var ageVal = ageGlobal[j-1] || "1";
//set the value of age dropdown
$(a).closest(".countRoom")
.find("select[name='childage']:eq("+(j-1)+")")
.val(ageVal);
}
});
//reset ageGlobal so that it works when child is changed
ageGlobal = "1";
}
function fillchild() {
var roomChildAge = $('.childage').val().split('*');
roomChildAge.forEach((childAge, index) => {
//find the child dropdown for the room
var childElement = $($('.countRoom')[index]).find('.childcount');
//element for child exist
if (childElement.length > 0) {
//get the child and age values using substring
var childCount;
//when there is no child and its age
if(childAge.trim()==="0"){
childCount = "0";
ageGlobal ='';
}else{
childCount = childAge.substring(0, childAge.indexOf(','));
ageGlobal = childAge.substring(childAge.indexOf(',')+1, childAge.length);
}
$(childElement).val(childCount.trim());
//trigger change eveny so that age select box is pre-selected
$(childElement).trigger('change');
}
})
}
.numberOfRooms {
border: 1px solid red;
}
.childage {
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="researchii">
<input type="hidden" class="rooms" value="2" />
<input type="text" class="childage" value="2 ,3,4*0" readonly />
<div class="col-xs-4">
<span class="itemlable">rooms: </span>
<select name="rooms" id="rooms">
<option value="1" class="btn2"> 1 </option>
<option value="2" class="btn2"> 2 </option>
</select>
</div>
<div class="numberTravelers">
<div class="countRoom">
<div class="col-xs-4">
<span class="itemlable">child</span>
<select name="childcount" class="childcount" onChange="childAge(this)">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div class="selectAge col-xs-4"></div>
<input type="hidden" name="_root.rooms__1.childcountandage" class="childcountandage" />
</div>
</div>
</div>

Add Extra Count When Select

i have simple reservation form, in a main input type text . that i show the final result of each select box on it. my problem is when i select 2 room . the number of adult changes to 2 , while i never choose 2 adult and i can not change this value in input type text. if you change the value of room count to 2. you can see the value of adult changes too. and it is not correct.
here is my snippet :
$(document).ready(function(e) {
$('body').on('change', 'select', function(){
var rcount = $('select[name*=roomCount]').toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
var acount = $('select[name*=adultcount]').toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
var ccount = $('.childcount').toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
$('#allcount').val('room:'+rcount+'adult:'+acount+' child:'+ccount);
});
$("#roomCount").change(function() {
//
countRoom = $(this).val();
$(".numberTravelers").empty()
for (i = 1; i <= countRoom; i++) {
$(".numberTravelers").css("width", "100%").append('<div class="countRoom"><div class="numberOfRooms">room</div> <div class="inner-items" style="margin-left: 5px; width: 49%;"><div class="title-item">adult</div><select name="_root.rooms__' + i + '.adultcount"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></div><div class="inner-items style="width: 49%;""><div class="title-item">child(</div><select name="childcount" class="childcount" onchange="childAge(this)"><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></select></div><div class="selectAge"></div><input type="hidden" name="_root.rooms__' + i + '.childcountandage" class="childcountandage"/></div><div class="clr"></div>')
}
});
$(".submit").click(function() {
$(".countRoom").each(function(index, element) {
var childCount = $(this).find(".childcount").val();
var childAge = " ";
$(this).find(".childage").each(function(index, element) {
childAge = childAge + ',' + $(this).val();
});
//childAge=childAge.substring(0,childAge.length - 1);
$(this).find(".childcountandage").val(childCount + childAge);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="allcount" value="room:1 ,adult:1 , child :1" />
<div class="title-item">room count</div>
<select name="roomCount" id="roomCount">
<option value="1" class="btn2"> 1 </option>
<option value="2" class="btn2"> 2 </option>
</select>
<div class="numberTravelers">
<div class="countRoom">
<div class="inner-items" style="margin-left: 5px;">
<div class="title-item">adult</div>
<select name="_root.rooms__1.adultcount">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div class="inner-items">
<div class="title-item">Child</div>
<select name="childcount" class="childcount" onChange="childAge(this)">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div class="selectAge"></div>
<input type="hidden" name="_root.rooms__1.childcountandage" class="childcountandage" />
</div>
<div class="clr"></div>
</div>
I had create some sample, i not sure what is this childAge as the sample did not include on it, hopefully this give you some idea on how it work, attached is the jsfiddle
https://jsfiddle.net/pq1qhggu/3/
the issue here is due to the fire event on body change, hence all the select is being fired at the same time, so i adding a kinda hardcoded name check, if name is the same, then do a calculation
$(document).on('change', 'select', function(){
var $this = $(this);
var $name = $this.attr('name');
if ($name === 'roomCount'){
rCount = $this.toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
}else if ($name === '_root.rooms__1.adultcount'){
aCount = $this.toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
}else if ($name === 'childcount'){
cCount = $this.toArray().reduce(function(prev, current){
prev += parseInt($(current).val());
return prev;
},0);
}
$('#allcount').val('room:'+rCount+'adult:'+aCount+' child:'+cCount);
});
and i also change from
$("#roomcount")
to
$("#allcount")
not sure why you only fired when roomcount is change instead of the allcount?

dropbox onchange with jquery-ui

I'm trying to get a onselect and then javascript function but it doesn't work.
It only works when I take away jquery-ui script, but then I get ugly forms.
<select id="productkleur" style="width: 200px;" onchange="productkleurchange()" data-theme="c" data-native-menu="true">
<option value="1" id="1">Zwart</option>
<option value="2" id="2">Rood</option>
<option value="3" id="3">Groen</option>
<option value="4" id="4">Paars</option>
<option value="5" id="5">Blauw</option>
<option value="6" id="6">Geel</option>
</select>
I tried this:
$("#productkleur").combobox({
select: function (event, ui) {
alert("the select event has fired!");
var productid = $("#productid").val();
var kleur = $("#productkleur").val();
var voorraad = $("#productcolourstock").val();
var what = "add";
console.log("change "+kleur+" to "+productid+" stock "+voorraad);
}
}
);
I tried this
function productkleurchange() {
var productid = $("#productid").val();
var kleur = $("#productkleur").val();
var voorraad = $("#productcolourstock").val();
var what = "add";
console.log("change "+kleur+" to "+productid+" stock "+voorraad);
};
The last one works fine when I remove jquery-ui, but when I don't nothing happens.
Anyone knows why or how to fix this?
Try the working code using jquery
$( "#productkleur" ).change(function() {
var productid = $("#productid").val();
var kleur = $("#productkleur").val();
var voorraad = $("#productcolourstock").val();
var what = "add";
console.log("change "+kleur+" to "+productid+" stock "+voorraad);
});
Remove onchange="productkleurchange()" from the HTML before trying with the above code.
Just remove onChange event in `select' it should work.
<select id="productkleur" style="width: 200px;" data-theme="c" data-native-menu="true">
<option value="1" id="1">Zwart</option>
<option value="2" id="2">Rood</option>
<option value="3" id="3">Groen</option>
<option value="4" id="4">Paars</option>
<option value="5" id="5">Blauw</option>
<option value="6" id="6">Geel</option>
</select>
Demo
Also try this,
$('#productkleur').on('change', function() {
var productid = $("#productid").val();
var kleur = $("#productkleur").val();
var voorraad = $("#productcolourstock").val();
var what = "add";
console.log("change " + kleur + " to " + productid + " stock " + voorraad);
});

Categories