autoselect select options with javascript / jquery - javascript

I am working on a function in Javascript/jQuery.
The function will search for usernames in the "select" element "Y" and selects them whene you copied a bunch of usernames in the textarea "X" with ', ', ',', ';' or ' ' as separator and also if you do it the other way around:
javascript/jQuery:
$(document).ready(function() {
$("dd#id-element select#id").attr({"multiple": "multiple", "size": 25, "name": "id[]"});
});
$(function() {
$("select#id").change(function() {
var selected_id = $(this).val(),
selected_name = new Array();
$(this).find("option:selected").each(function() {
selected_name.push($(this).text());
});
$("textarea#id_field").val(selected_id);
$("textarea#name_field").val(selected_name);
console.log(selected_id, selected_name);
});
$("textarea#name_field").keyup(function() {
$("select#id option").removeAttr("selected");
var names_raw = $(this).val(),
names = names_raw.replace(/(, | |,)/gi, ";"),
selected_name = names.split(";"),
selected_id = new Array();
$.each(selected_name, function(i, value) {
if (value != "" && value != null) {
$("select#id option[label='" + value + "']").attr("selected", true);
selected_id.push($("select#id option[label='" + value + "']").val());
}
});
});
});
HTML code:
<select name="id" id="id">
<option value="1092" label="00lara00">00lara00</option>
<option value="5105" label="010201e">010201e</option>
<option value="1725" label="0411dennis">0411dennis</option>
<option value="1795" label="051259">051259</option>
<option value="2281" label="0815Timmey">0815Timmey</option>
<option value="3337" label="0vlinder0">0vlinder0</option>
<option value="127" label="1001gece">1001gece</option>
<option value="3693" label="111nizza">111nizza</option>
<option value="821" label="114helen">114helen</option>
<option value="2887" label="1212whopper">1212whopper</option>
<option value="5564" label="123boo">123boo</option>
</select>
<textarea name="name_field" id="name_field"></textarea>
when i select some usernames in the select element, it works fine, the usernames are copied to the textarea.
when i paste some usernames in the textarea, everything is deselected like it should, but there is nothing new selected

I finally got it working. This is how I did it
Javascript:
$(document).ready(function() {
$("dd#id-element select#id").attr({"size": 25});
});
$(function() {
$("select#id").change(function() {
var selected_id = $(this).val(),
selected_name = new Array();
$(this).find("option:selected").each(function() {
selected_name.push($(this).text());
$(this).addClass("checked");
});
$("textarea#name_field").val(selected_name);
$("textarea#name_field").keyup();
});
$("textarea#name_field").keyup(function() {
$("select#id option.checked").attr("checked", null).attr("selected", null).removeClass("checked");
var names_raw = filterValue($(this).val()),
names = names_raw.replace(/(, | |,|\s)/gi, ";"),
selected_name = names.split(";"),
selected_id = new Array();
$(this).val(names_raw)
$.each(selected_name, function(i, value) {
if (value != "" && value != null) {
if ($("select#id option[label='" + value + "']").length > 0) {
$("select#id option[label='" + value + "']").attr('checked', 'checked').attr('selected', 'selected').addClass("checked").focus();
selected_id.push($("select#id option[label='" + value + "']").val());
}
}
});
$("select#id").val(selected_id);
});
});
html code:
<select name="id[]" id="id" multiple="multiple">
<option value="1092" label="00lara00">00lara00</option>
<option value="5105" label="010201e">010201e</option>
<option value="1725" label="0411dennis">0411dennis</option>
<option value="1795" label="051259">051259</option>
<option value="2281" label="0815Timmey">0815Timmey</option>
<option value="3337" label="0vlinder0">0vlinder0</option>
<option value="127" label="1001gece">1001gece</option>
<option value="3693" label="111nizza">111nizza</option>
<option value="821" label="114helen">114helen</option>
<option value="2887" label="1212whopper">1212whopper</option>
<option value="5564" label="123boo">123boo</option>
</select>
<textarea name="name_field" id="name_field"></textarea>

Related

Append options to select box depend on extracted part from array

I have 4 selectboxs moduleName, submoduleName, ProgrameName and last selectbox has all data for username, module, submodule and programe name merged and splited with ";" between each other, I need: when user select module name from moduleName Selectbox it filters values in all data selectbox and splites submoduleNames under this moduleName and append it as options to submoduleName Selectbox, also the same when user select from submoduleName selectbox it filters programeNames under this module and subModuleNames and append it as options in programeName selectbox. I tried to splite each line in allData selectbox but i failed to continue. here what i tried but it is not working.
Thank you for your help.
$(document).ready(function(){
function check(){
var lines = $('#splitedOptions').val().split(/\n/);
var texts = [];
for (var i=1; i < lines.length; i++) {
texts.push(lines[i]);
}
for (var i=0; i < texts.length; i++) {
var extractedPart = texts[i].split(';'),
ModuleNameVal = $("#moduleName option:selected").val();
if(extractedPart[1] == ModuleNameVal){
var newOption = "<option value='"+extractedPart[2]+"'>"+extractedPart[2]+"</option>";
$('#SubModuleName').append(newOption);
}
}
}
function c1() {
var optionsCount = $('#allData').find('option').size();
var textArea ="";
for (var i = 1; i <= optionsCount; i++) {
if(i!=1){
textArea += '\n';
}
var xItem = $('#allData').find('option:nth-child(' + (i) + ')').text();
textArea += xItem ;
}
$('#splitedOptions').val('');
$('#splitedOptions').val(textArea);
check();
}
$('#moduleName').change(function(){
c1()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions" ></textarea>
One way to achieve above is to filter the options from allData select-box and get only those option which has the value which user has selected using value*="yourvalue".
Then , onces you get the options you need to know which select-box has been change so that we can get required value only when we do split and pass required index .
Lastly , we need to loop through the options which we have got from filtering select-box .Suppose user select Master so there are Master in many places so to avoid getting data from all option i have check the value of select with the first select-box as well if matches apppend only those options.
Demo Code :
$('select').change(function() {
//get value
var name = $(this).val();
//filter option and get only option which has the value which user has slected
var s = $("#allData").find('option').filter('[value*=' + name + ']').each(function(ele) {
return $(this).val();
});
var module_namess;
var index;
//check the id of select-box
if ($(this).attr("id") == "moduleName") {
module_namess = "SubModuleName";
index = 2;//set index
} else if ($(this).attr("id") == "SubModuleName") {
name = $("#moduleName").val()
module_namess = "programeName"
index = 3
}
$("#" + module_namess).empty()
$('#' + module_namess).append("<option >Select one</option>")
var valuess = ''
//loop through options
for (var i = 0; i < s.length; i++) {
valuess += $(s[i]).val()
//if first value is same
if ($(s[i]).val().split(";")[1] == name) {
var sub_value = $(s[i]).val().split(";")[index]//get the value
var newOption = "<option value='" + sub_value + "'>" + sub_value + "</option>";
$('#' + module_namess).append(newOption);//append
}
}
$('#splitedOptions').val(valuess);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions"></textarea>

Jquery function is not working with select form

I am using the following select form and function to select the transport type first and I would like to have a list of cars or motorcycles in the second form depending on my choice at the first stage. I will really appreciate if you can let me know why my function is not working and what I am missing
<!doctype html>
<html>
<body>
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
</body>
<script>
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
addEvent(type, 'change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars') {
return cars;
} else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
</script>
`
Use addEventListener. Check this working snippet
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
type.addEventListener('change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars')
{
return cars;
}
else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />

How can i save this script to Local Storage

I want simply save changes that i've made with main text heading, changed color/font-size/font using Local Storage. So after page reload changes will stay at browser. How could i make this?
Html:
<div class="main_text">
<h1>Change Headings</h1>
</div>
<select id="selection">
<option value="h1">H1</option>
<option value="h2">H2</option>
<option value="h3">H3</option>
<option value="h4">H4</option>
<option value="h5">H5</option>
</select>
<div class="color_picker">
<h3>Choose Text Color</h3>
<input type="color" id="color_picker">
</div>
<div class="change_font">
<h3>Change Font</h3>
<select id="select_font">
<option value="Sans-serif">Sans-serif</option>
<option value="Monospace">Monospace</option>
<option value="Serif">Serif</option>
<option value="Fantasy">Fantasy</option>
<option value="Verdana">Verdana</option>
<option value="Impact">Impact</option>
</select>
</div>
<div class="change_size">
<h3>Font Size</h3>
<select id="change_font_size">
<option value="14">14</option>
<option value="18">18</option>
<option value="22">22</option>
<option value="24">24</option>
<option value="26">26</option>
</select>
</div>
JQuery:
$('#selection').change(function () {
var tag = $(this).val();
$(".main_text").html("<" + tag + ">Change Headings</" + tag + ">");
});
$('#color_picker').change(function() {
var color_p = $(this).val();
$('.main_text').css("color", color_p);
});
$('#select_font').change(function () {
var change_font = $(this).val();
$(".main_text").css("font-family", change_font);
});
$("#change_font_size").change(function() {
var font_size = $(this).val();
$('.main_text > *').css("font-size", font_size + "px");
});
JSfiddle
DEMO
$(document).ready(function () {
var tag = localStorage.tag || $('#selection').val();
var color = localStorage.color || $('#color_picker').val();
var font = localStorage.font || $('#select_font').val();
var size = localStorage.font_size || $('#change_font_size').val();
$('.main_text').css({
"color": color,
"font-family": font,
"font-size": size
}).html("<" + tag + ">Change Headings</" + tag + ">");
$('#selection').val(tag);
$('#color_picker').val(color);
$('#select_font').val(font);
$('#change_font_size').val(size);
$('#selection').change(function () {
var tag = $(this).val();
localStorage.tag = tag;
$(".main_text").html("<" + tag + ">Change Headings</" + tag + ">");
});
$('#color_picker').change(function () {
var color_p = $(this).val();
localStorage.color = color_p;
$('.main_text').css("color", color_p);
});
$('#select_font').change(function () {
var change_font = $(this).val();
localStorage.font = change_font;
$(".main_text").css("font-family", change_font);
});
$("#change_font_size").change(function () {
var font_size = $(this).val();
localStorage.font_size = font_size;
$('.main_text > *').css("font-size", font_size + "px");
});
});
Add this code after your JS code:
$(document).ready(function () {
//load values if found
if (localStorage.getItem("selection") != null) {
$('#selection').val(localStorage.getItem("selection")).trigger("change");
}
if (localStorage.getItem("color_picker") != null) {
$('#color_picker').val(localStorage.getItem("color_picker")).trigger("change");
}
if (localStorage.getItem("select_font") != null) {
$('#select_font').val(localStorage.getItem("select_font")).trigger("change");
}
if (localStorage.getItem("change_font_size") != null) {
$('#change_font_size').val(localStorage.getItem("change_font_size")).trigger("change");
}
});
Here is the JSFiddle demo

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

What is wrong with that select options?

I am just trying to make a simple calculation with the values of selected options, however I get false result:
pickUp 9 and returnTime 10, it gives no (which must be yea)
but pickUp time 11 and returnTime 14, it gives yea(which is right) so it gives the right result with some specific numbers and with some numbers not..
Here is the (pickUp)select options:
<select id="ophalenUur" class="timePicker selectOption">
<option value="-">Kies Tijd</option>
<option value="8">08.00</option>
<option value="8.5">08.30</option>
<option value="9">09.00</option>
<option value="9.5">09.30</option>
<option value="10">10.00</option>
<option value="10.5">10.30</option>
<option value="11">11.00</option>
<option value="11.5">11.30</option>
<option value="12">12.00</option>
<option value="12.5">12.30</option>
<option value="13">13.00</option>
<option value="13.5">13.30</option>
<option value="14">14.00</option>
<option value="14.5">14.30</option>
<option value="15.">15.00</option>
<option value="15.5">15.30</option>
<option value="16">16.00</option>
<option value="16.5">16.30</option>
<option value="17">17.00</option>
<option value="17.5">17.30</option>
<option value="18">18.00</option>
<option value="18.5">18.30</option>
<option value="19">19.00</option>
<option value="19.5">19.30</option>
<option value="20">20.00</option>
</select>
and js:
var pickUp = 0;
var returnTime =0;
$('#ophalenUur').change(function() {
pickUp = $('#ophalenUur option:selected').val();
$('.pickUp').text("PickUp: " + pickUp);
});
$('#inleverenUur').change(function() {
returnTime = $('#inleverenUur option:selected').val();
$('.returntime').text("return: " + returnTime);
if(returnTime > pickUp){ alert("yea");
} else { alert("no"); }
});
Fiddle: http://jsfiddle.net/jLAaq/27/
What is wrong here? I am looking for hours and I can't see:/
because you are doing a string comparison
var pickUp = 0;
var returnTime = 0;
var totalExtra = 0;
$('#ophalenUur').change(function () {
//conver the value string to number by prfixing it with + or you can use parseFloat(this.value)
pickUp = +this.value;
$('.pickUp').text("PickUp: " + pickUp);
});
$('#inleverenUur').change(function () {
returnTime = +this.value;
$('.returntime').text("return: " + returnTime);
if (returnTime > pickUp) {
alert("yea");
} else {
alert("no");
}
});
Demo: Fiddle
I think the reason could be returnTime and pickUp is string. so "9">"10".
Try to use parseFloat function to parse returnTime and pickUp.
You were comparing the integer as string. You can use the parseFloat method
Demo Link
CODE:
var pickUp = 0;
var returnTime =0;
var totalExtra = 0;
$('#ophalenUur').change(function() {
pickUp = $('#ophalenUur option:selected').val();
$('.pickUp').text("PickUp: " + pickUp);
});
$('#inleverenUur').change(function() {
returnTime = $('#inleverenUur option:selected').val();
$('.returntime').text("return: " + returnTime);
if(parseFloat(returnTime) > parseFloat(pickUp)){
alert("yea");
}else{
alert("no");
}
});

Categories

Resources