Get previous value of dropdown after onchange event jQuery - javascript

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")
});

Related

Set multi select options from stored localstorage values

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>

Not abled to assign old value for ng-select?

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 = {};
}
}

HTML Select Menu - modify Javascript variable on change

I have a Javascript that stores a variable for a default phone number, but I would like users to be able to override this based on the options in a select menu. If they make a selection from the menu I would like the Javascript variable to be updated with the new value from the selected option.
Here's the script:
$("#callContact1").click(function() {
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber=0412345678&type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
I would like to edit the value of the 'recipientNumber=0412345678' in the url of the AJAX request function whenever this select menu is changed:
<select class="form-control" name="callBackNumber" id="callBackNumber">
<option value=""></option>
<option value="0418468103" selected>Mobile (0412345678)</option>
<option value="0294846565">Work (0299887766)</option>
<option value="0233445566">Home (0233445566)</option>
</select>
I'm not sure if this is possible or if there is a better way to construct this to achieve the same result?
Create a global variable with your defaultPhoneNumber.
var defaultPhoneNumber = $("#callBackNumber").val();
Update that variable on change of dropdownlist.
$("#callBackNumber").change(function(){
defaultPhoneNumber = $(this).val();
});
And use updated value in URL
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber="+ defaultPhoneNumber +"&type=makecall",
data: {},
type: "GET"
});
Use $("#callBackNumber").on("change", function() { and pass the this.value number
$("#callBackNumber").on("change", function() {
var number = this.value;
if(!number) {
return console.log("Please select a number!"); //
}
// Now let's use that number
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber="+ number +"&type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="callBackNumber" id="callBackNumber">
<option value=""></option>
<option value="0418468103" selected>Mobile (0412345678)</option>
<option value="0294846565">Work (0299887766)</option>
<option value="0233445566">Home (0233445566)</option>
</select>
Sure it is possible, and You have done something similar ;)
select element support's change event, which fires after selecting option from dropdown.
$('#callBackNumber').on('change', (event) => {
const value = event.target.value
fireCallback(value)
})
ofc You have to write fireCallback function, which will do the thing
This is how I would do it:
var phoneNum = "0412345678";
$("#callBackNumber").change(function() {
phoneNum = $(this).val();
});
Here is the JSFiddle demo
Create a global variable, always concatenate it in the ajax URL. Update the value of the variable whenever the dropdown is changed. You will always have latest value in your variable and hence in your ajax URL.

Change Javascript function from checkbox to select

I have a function that based on a checkbox id determines a price value. This works fine except I need to change the checkbox to a select. I tried to change the line:
if(peo14.checked==true)
To this:
if(peo14.select==Yes)
This did not work...how do I alter this to a Yes/No select?
function peoPrice()
{
var peoPrice=0;
//Get a reference to the form id="quicksheet"
var theForm = document.forms["quicksheet"];
//Get a reference to the checkbox id
var peo14 = theForm.elements["peo14"];
//If they checked the box set peoPrice to value
if(peo14.checked==true)
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}
You have to use the .options property and choose the selected index, then get the value of that index.
if (peo14.options[ peo14.selectedIndex ].value === 'Yes') {
peoPrice = 199;
}
Select Box
<select id="peo14" name='peo14' >
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
function peoPrice()
{
var peoPrice=0;
var e = document.getElementById("peo14");
var peo14val = e.options[e.selectedIndex].value;
if(peo14val=="Yes")
{
peoPrice=199;
}
//finally we return the peoPrice
return peoPrice;
}

How do i manipulate select box using jquery?

I have some select boxes like the following:
<select id="my_box1" rel="cal_10">
<option value="A"></option>
</select>
<select id="my_box2" rel="cal_10.50">
<option value="A"></option>
</select>
....
<select id="my_boxn">
<option value="B"></option>
</select>
On changing, I want to add the related value (that is 10 and 10.50) only when the select boxes has the same option value.
For Example: if the first and second select box has option value as A, then I want to add it.
How can I do this using jQuery?
Well, I really can't tell exactly what you're asking, so I'll just guess.
I'm guessing that when a select element receives a change event, we should find all other selects where the selected value is the same, and sum the numeric portion of the rel attribute.
If so, you can do this:
var boxes = $('select[id^="my_box"]');
boxes.on('change', function() {
var n = 0,
val = this.value;
boxes.each(function() {
if( this.value === val ) {
n += +$(this).attr('rel').replace('cal_','');
}
});
alert( n );
});
If you're using a version of jQuery older than 1.7, then use boxes.bind instead of boxes.on.
Something like this, I believe:
$(function() {
$('select#my_box1, select#my_box2').bind('change', function() {
if ($('select#my_box1').val() == $('select#my_box2').val())
$('select#my_box2').append('<option value="10">10</option><option value="10.50">10.50</option>');
else $('select#my_box2').find('option[value="10"], option[value="10.50"]').remove();
});
});
I tried by below code,
$('select').change(function(){
var totalWeight = 0;
var post_array = [];
var actual_val = value;
//alert(actual_val);
var x=0;
$("select").each(function(index, selectedObj) {
current = $(this).val();
var combined = $(this).attr('rel');
if(combined!=undefined)
{
combined = combined.split("_");
var is_combined = combined[0];
var combined_pid = combined[1];
if(actual_val == current && is_combined == "cal"){
post_array[x++] = combined_pid ;
totalWeight+=parseFloat(combined_pid);
}
}
});
alert(totalWeight);
});
I will get my total value in totalWeight

Categories

Resources