html
<select ng-model="selectedName" ng-change="retrieveSelectedClass(selectedName, '{{selectedName}}')" ng-options="item.name group by item.groupName for item in names"
class="code-helper" id="code-helperId">
<option value="">Select Option</option>
</select>
JavaScript
$scope.retrieveSelectedClass = function(newValue, oldValue) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
oldValue = JSON.parse(oldValue);
var oldValueObject = {
name: oldValue.name,
id: oldValue.id,
groupName: oldValue.groupName,
lineNumberError : oldValue.lineNumberError,
isCompilationError : oldValue.isCompilationError,
dataNotMatching : oldValue.dataNotMatching,
timeStampNotMatching : oldValue.timeStampNotMatching
};
$scope.selectedName = oldValueObject;
$scope.isPaneShown = false;
return;
}
}
}
So what the js does, it checks if the editor is clear then alerts the user. If the user selects cancel, then the selected value in the ng-select should remain as old value and not the new value which got selected by the user.
But the selected value in ng-select becomes blank when the user clicks cancel?
And idea where am I making mistake? Or how to implement this?
Because in angularjs an object has an objectHash (named $$objectHash you see that if you debug). It's an identifier, and you can't assign to select an object that isn't in select options.
I write a Plunker with an example. I think this would be helpful to you
https://plnkr.co/edit/YpwhgKSy24kFyYtjRKsv
$scope.retrieveSelectedClass = function(newValue, oldValue){
// your control, i do simple control because i don't understand exatly what you need
if(angular.isUndefined(oldValueSelected.id) && oldValue.indexOf('"id"') !== -1){
oldValueSelected = JSON.parse(oldValue);
}
}
$scope.clearSelect = function(){
// check if old value isn't empty
if(angular.isDefined(oldValueSelected.id)){
// filter names array and get object of old value
var possibleOldValues = $filter('filter')($scope.names, {id: oldValueSelected.id}, true);
if(possibleOldValues.length > 0){
$scope.selectedName = possibleOldValues[0];
}
}
else{
$scope.selectedName = {};
}
}
Related
I am trying to set multiple select options to selected, based on the corresponding localstorage value.
Storing the values in an array in localstorage is working, but I need help selecting the options in a form based on these values..
The values in localstorage are collected from checkboxes like so:
jQuery(document).ready(function(){
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
checkboxes = jQuery(".add-selectie :checkbox");
checkboxes.on("change", function(){
checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
jQuery.each(checkboxValues, function(key, value) {
jQuery('#' + key).prop('checked', value);
});
});
This saves the values in an array with the key "checkboxValues" in localstorage like so:
{"value1":true,"value2":true,"value3":false}
But how do I pre populate select options in a form if the value is found in localstorage AND set to true?
I made this pen containing all above code + a demo form. Any help would be greatly appreciated!
The code below should give you snippets to update selected state of option elements by reading values from localStorage.
Please note that there is a security issue in using localStorage in stackoverflow execution context so
I created a custom singleton/static class CustomLocalStorage having similar methods.
Additionally I've used a complete object OptionValueObject to back
the properties of checkbox and select elements.
var CustomLocalStorage = (function() {
var items = {};
function getItem(itemKey) {
for (var _itemKey in items) {
if (_itemKey === itemKey) {
return JSON.parse(items[itemKey]);
}
}
return null;
}
function setItem(itemKey, itemValue) {
items[itemKey] = JSON.stringify(itemValue);
}
return {
getItem: getItem,
setItem: setItem
}
})();
function OptionValueObject(id, label, value) {
this.id = id; // Used to identify checkboxes
this.label = label; // Not used in this example
this.value = value; // To bind it to select > option > value property
this.checked = true; // To bind it to checkbox > checked property
}
$(document).ready(function() {
function initialize() {
initializeData();
initializeUi();
}
function initializeData() {
var optionValueObjects = [];
optionValueObjects.push(new OptionValueObject(1, 'Label of option 1', 'value1'));
optionValueObjects.push(new OptionValueObject(2, 'Label of option 2', 'value2'));
optionValueObjects.push(new OptionValueObject(3, 'Label of option 3', 'value3'));
CustomLocalStorage.setItem('options', optionValueObjects);
}
function initializeUi() {
var optionValueObjects = CustomLocalStorage.getItem('options');
for (var i = 0; i < optionValueObjects.length; i++) {
var optionValueObject = optionValueObjects[i];
var id = optionValueObject.id;
// Checkbox: Identify element and set UI related property
var checkboxElement = $('#checkbox' + id);
checkboxElement.prop('checked', optionValueObject.checked);
console.log(optionValueObject.value);
// Option: Identify element and set UI related property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
}
}
function handleEvents() {
function checkboxChangeHandler() {
// Get the object, update the checked property and save it back
// 1. Get the object
var id = $(this).prop('id');
var optionValueObjects = CustomLocalStorage.getItem('options');
var optionValueObject = optionValueObjects.filter(function(optionValueObject) {
if (('checkbox' + optionValueObject.id) === id) {
return optionValueObject;
}
})[0];
// 2. Update the checked property
var checked = $(this).prop('checked');
optionValueObject.checked = checked;
// Bind the checked property to options selected property
var optionElement = $("#optionsSelect > option[value='"+ optionValueObject.value +"']");
optionElement.prop('selected', optionValueObject.checked);
// 3. Save it back
CustomLocalStorage.setItem('options', optionValueObjects);
}
$('#checkbox1').change(checkboxChangeHandler);
$('#checkbox2').change(checkboxChangeHandler);
$('#checkbox3').change(checkboxChangeHandler);
}
initialize();
handleEvents();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add-selectie">
<input id="checkbox1" class="selector" type="checkbox"><label for="checkbox1">Value 1</label>
<input id="checkbox2" class="selector" type="checkbox"><label for="checkbox2">Value 2</label>
<input id="checkbox3" class="selector" type="checkbox"><label for="checkbox3">Value 3</label>
</div>
<form>
<select id="optionsSelect" multiple="multiple">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
</form>
I've created a jsfiddle for this question, here: http://jsfiddle.net/navyjax2/9xpbyodq/
HTML
<span title="Fruit" class="ms-RadioText">
<input id="groupType_0" type="checkbox" checked="checked"/>
<label>Fruit</label>
</span><br>
<span title="Pies" class="ms-RadioText">
<input id="groupType_1" type="checkbox" />
<label>Pies</label>
</span>
<br><br>
<select id="Use_d8ffe43">
<option value="Apples">Apples</option>
<option value="Grapes">Grapes</option>
<option value="Both">Both</option>
</select><BR><BR>
JavaScript
$(document).ready(function () {
var whatSelected = new Array();
var piesOnly = false;
whatSelected.push('fruit'); // initial preset
var groupTypeField = $('input[id*="groupType"]');
groupTypeField.on('change', function () {
//alert(this.id);
var thisId = this.id.split('groupType_')[1];
//alert(thisId);
var thisChecked = this.checked;
var key = "";
if (thisId == 0)
key = "fruit";
else
key = "pies";
//alert(key);
if (whatSelected.indexOf(key) == -1 && thisChecked) {
whatSelected.push(key);
//alert('push: ' + key);
}
if (whatSelected.indexOf(key) != -1 && !thisChecked) {
//alert('pull: ' + key);
var index = whatSelected.indexOf(key);
//alert('index: ' + index);
if (index != -1) {
whatSelected.splice(index, 1);
//alert('pulled ' + key);
}
}
alert('after alteration: ' + whatSelected);
if (whatSelected.indexOf('pies') != -1) { // Pies checked
if (whatSelected.indexOf('fruit') != -1) { // Fruit checked, so not Pies only
piesOnly = false;
// Add "Grapes" and "Both" back, if gone
var exists = false;
$('select[id*="Use"] option').each(function () {
if (this.value == "Grapes") {
exists = true;
}
});
if (!exists) {
alert('added');
$('select[id*="Use"]').append('<option val="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option val="Both">Both</option>');
}
} else { // Fruit not checked
piesOnly = true;
// Remove Grapes and Both from dropdown
$('select[id*="Use"]').find('option[value="Grapes"]').remove(); $('select[id*="Use"]').find('option[value="Both"]').remove();
alert('removed');
}
} else { // Pies not checked
if (whatSelected.indexOf('fruit') != -1) { // Fruit checked, so not pies only
piesOnly = false;
} else {// nothing selected, revert to Fruit
alert('Must select an option.');
$('span[title*="Fruit"]').children(0).prop('checked', true);
$('span[title*="Pies"]').children(0).prop('checked', false);
piesOnly = false;
whatSelected.push('fruit'); // add it back
}
// Add "Grapes" and "Both" back to dropdown, if gone
var exists = false;
$('select[id*="Use"] option').each(function () {
if (this.value == "Grapes") {
exists = true;
}
});
if (!exists) {
alert('added');
$('select[id*="Use"]').append('<option value="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option value="Both">Both</option>');
}
}
});
});
Say I have 2 checkboxes, Fruit and Pies.
Say I have a dropdown, options: Apples, Grapes, Both
So if "Fruit" is selected, I expect all options to appear in the dropdown.
If "Pies" is selected, I only want "Apples", since who ever heard of a "Grape" pie? (or pie with "Both"?)
Fruit is the default selection, and at least one checkbox must be selected at all times. I have an array, "whatSelected", that tracks what checkboxes have been selected.
My code works to remove "Grapes" and "Both" from the dropdown if I select "Pies" and unselect "Fruit". (leaves "Apples" in the dropdown)
If I then re-select "Fruit", the options are all added back, correctly, through code I use to re-append the options using jQuery.
My issue is then, if I unselect "Fruit", it then DOES NOT remove "Grapes" and "Both", which are my appended options, on the dropdown. How can I remove these appended options? Thanks.
Actually I found my bug.... I have to do the appending in two places -- once if Fruit and Pies are selected, and another place, when Pie is not selected, but Fruit is. In one of the locations, I had...
$('select[id*="Use"]').append('<option val="Grapes">Grapes</option>');
$('select[id*="Use"]').append('<option val="Both">Both</option>');
Instead of val, I needed to use value. This solved my problem.
Rather than leave my jsfiddle broken, I updated it with this fix. But the code above is the original.
I thought about deleting this question, but thought there could be a lot of benefit to the coding community if I left this, since a lot of what is here are things often asked and could drive someone a little nutty on how to implement some of the things I did, here.
How do I get the previous value of my AUTO-Generated dropdown menu after an onchange event? Example
<select class="form-control" name="Diabetes_UK_3147" id="Diabetes_UK_3147" onchange="return verifyUpdateResponseGross(this);">
<option value="Yes">Yes</option>
<option value="Possibly">Possibly</option>
<option value="">N/A</option>
</select>
and I have this function
function verifyUpdateResponseGross(val)
{
var updated_response = val.value;
var colheader = val.name
var before_gross = $('#new_gross').val();
$.ajax({
url: "qa/api/crm/getquestion",
type: 'GET',
data: {'colheader':colheader},
success: function(result){
// var costperlead = result;
// if(updated_response != "")
// {
// var new_gross_amount = parseFloat(before_gross) + parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// else
// {
// var new_gross_amount = parseFloat(before_gross) - parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// console.log(costperlead);
}});
}
The reason I want to get the previous value is I need a checking that if the dropdown value is empty (N/A) then I need to perform some operation and if the value is not empty then I need perform another operation, But when the value gis not empty but the same from the previous value, then do nothing.
Those operation are those in comments. Thanks
UPDATE The id and name is autogenerated. That's why I have a
onchange="return verifyUpdateResponseGross(this);"
This will handle the change and do necessary operation.
This is it is autogenerated
Best way to do it by jquery :
$(document).ready(function(){
var previous;
$("#Diabetes_UK_3147").on("focus click",function () {
previous = this.value; // Old vaue
}).change(function() {
var value = this.value; // New Value
$('span').text('Old Value : '+previous+' New Value : '+value)
});
})
here the fiddle http://jsfiddle.net/Laa2hL3b/
Edited : in auto-Generated dropdown you can add a custom class for example "myselectbox"
<select class="form-control myselectbox"
and make change here
$(".myselectbox").on(/* other code remain same */
Use data to store the data instead a global variable:
$("#Diabetes_UK_3147").on("focus",function(){
$(this).data('previous',$(this).val());
}
Then you can access previous value by $("#Diabetes_UK_3147").data('previous');
jQuery data
Use data-* as below. Also, remove the inline event handler onchange="return verifyUpdateResponseGross(this);" and do it the unobtrusive way.
var $select = $("#Diabetes_UK_3147");
$select.data("previous-val", $select.val());
$select.on("change", function() {
var current_value = $(this).val();
if (current_value == "") {
//Do stuff when empty
} else if ( current_value != $(this).data("previousVal") && current_value != "" ) {
//Do stuff when not empty and current value != previous value
}
});
var $select = $("#my-select");
$select.data("prevVal", $select.val()).data("currVal", $select.val()).on("change", function () {
var $this = $(this);
$this.data("prevVal", $this.data("currVal")).data("currVal", $this.val());
// do your staff here. Previous value is available in $this.data("prevVal")
});
I have the following HTML code:
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value1</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value2</option>
</select>
<Select name=test[]>
<option value="">--Please Select--</option>
<option value="a">Test Value3</option>
</select>
Now before submitting the form I want to do the following
Check if any of the above is selected.
If selected retrieve its value.
I believe I need to loop around but I am unable to find the initial syntax with which I can first grab all the values.
I know how to check if any value is selected when 'id' is given for a select element. But in this case I have the 'name' attribute which is an array.
I tried looking at different places but I haven't really come across a good solution. Probably I missed something.
Please let me know if any further information is required.
using map function
var selected = $('select[name="test[]"]').map(function(){
if ($(this).val())
return $(this).val();
}).get();
console.log(selected);
This isn't a complete solution, but may hopefully point you in the right direction (assuming your using jQuery)
The below code should loop through your selects (when they have the name='test[]') and add any values (that aren't blank) to the result array.
var results = [];
$("select[name='test[]']").each(function(){
var val = $(this).val();
if(val !== '') results.push(val);
});
console.log(results);
Demo: http://jsfiddle.net/W2Mam/
The following will let you iterate through select tags which has any selected value other than default "". You can adjust it to any other unwanted values etc.
$("select[name='test[]']").each(function(){
if($(this).val()!='')
{
//doStuff
}
});
you can check and save boxes values this way
var results = [];
$("select[name='test[]']").each(function(index, val)
{
if ($(val).val() == "") {
//Not selected
}
else
{
//Selected
}
//Save results in an array based on the index of selects
results[index] = $(val).val();
});
then you can iter through the array and check values based on index (or you can just check it above on the .each() function)
Try to do this way:
$("select[name='test[]']").on('change', function(){
if(this.value != ""){
alert(this.value);
}else{
alert('no values selected');
return false;
}
});
You have to get values on the event of change so get the elems with attribute selectors and then you can get the values of target elem.
If you use this :
var values = $('select[name^="test["]').map(function(){
if(this.value !== "") return this.value;
})
You'll have an array of values.
To check if one is selected, just check the length : values.length
You can use filter() to return only the selects which have a value, and then map() to get their values:
var values = $('select[name="test[]"]').filter(function() {
return $.trim(this.value).length;
}).map(function() {
return this.value;
}).get();
Obviously with this you won't know which select has which value, if you need to know, you'd have to use the elements' index as that's its only unique identifier (given your markup).
The following would return an array of objects containing the elements' index, and its value:
var values = $('select[name="test[]"]').filter(function() {
return $.trim(this.value).length;
}).map(function() {
return { index: $(this).index(), value: this.value };
}).get();
To check if anything was selected, you'd just check values.length:
if (!values.length) {
alert('Nothing was selected');
}
Here's a fiddle
I implement jquery multiselect and its working properly now i need to add extra feature that when a user select another option in dropdown ( check another checkbox ) then i want to get the value of the related option
in above picture in did not insert checkbox it is automatically inserted by jquery now i want that if i select the check =box with XYZ then i want to get the value of XYZ which is the id of XYZ
here is how i implemented it
<select multiple="multiple" id="CParent" name="parent" class="box2 required">
#foreach (var item in Model.Categories.OrderBy(c => c.Name))
{
if (Model.Coupon.Categoryid.Id == item.Id)
{
<option selected="selected" value="#item.Id">#item.Name</option>
}
else
{
<option value="#item.Id">#item.Name</option>
}
}
</select>
and it is how it looks like after rendering in browser source
Thanks in advance for helping me .
what i tried yet
$('#CParent input:checked').change(function () {
var parentid = $(this).val()+'';
var array = parentid.split(",");
alert(array);
getchildcat(array[array.length -1]);
});
});
Edit
Code to initialize multiselect
$("#CParent").multiselect({
header: "Choose only THREE items!",
click: function () {
if ($(this).multiselect("widget").find("input:checked").length > 3) {
$(warning).show();
warning.addClass("error").removeClass("success").html("You can only check three checkboxes!");
return false;
}
else if ($(this).multiselect("widget").find("input:checked").length <= 3) {
if ($(warning).is(":visible")) {
$(warning).hide();
}
}
}
});
try this
$('#CParent').val();
this will give you the selectbox value
OR
from docs
var array_of_checked_values = $("#CParent").multiselect("getChecked").map(function(){
return this.value;
}).get();