I am trying to write some Javascript (not Jquery) that when the address dropdown field is clicked it will trigger an event to check the value in the 'ship state' field.
<script>
var addressDropdown = document.querySelector('#address-id');
var shipstateDropdown = document.querySelector('#shipstate-id');
var SelectedShipState;
addressDropdown.addEventListener('click', (addressEvent) => {
if (shipstateDropdown.options[shipstateDropdown.selectedIndex].value === "CA") {
SelectedShipState = "CA";
RunRule();
}
})
</script>
I resolved my issue. I first had to set the event handler for the address drop down which when this occurred it triggered a function. That function then gets the value from the ship state dropdown.
I also added in a setTimeout because the act of triggering the address handler was grabbing the ship state before the value could arrive resulting in a value that was delayed or null.
// Global defined variables //
var SelectedShipState
var selectElement = document.getElementById('ship-state-id');
var addressBook = document.getElementById('address-book-id');
// Change Event: When an address from the address book is selected ...
addressBook.addEventListener('change', (addressEvent) => {
// ... run this function to get the ship state.
setTimeout(addressFunction, 1000);
})
// When this function runs ...
function addressFunction() {
// ... get the value from the ship state select option.
SelectedShipState = this.selectElement.options[selectElement.selectedIndex].value;
RunRule();
}
// Change Event : Get the option each time it is selected //
selectElement.addEventListener('change', (changeEvent) => {
SelectedShipState = `${changeEvent.target.value}`;
RunRule();
})
function RunRule () {
// do something ...
}
Related
onPress of submit button, I want to validate all SimpleForms' fields (ComboBox, Input, DatePicker, etc.) that are
required &
visible
to see if they are null or blank (""). If a targeted (required & visible) field is null/blank, set that control's state to "Error" and display an error message. If no targeted field is null/blank, pop up a success dialog box.
This method is automated so in the future, any fields added later will automatically be checked without need of manual additions to controller code.
Controller code:
requiredAndVisible: function(oControl) {
if (typeof oControl.getRequired === "function") { //certain ctrls like toolbars dont have getRequired as a method, so we want to skim those out, else itll throw an error later in the next check
if (oControl.getRequired() === true && oControl.getVisible() === true) {
return oControl;
}
}
},
onSubmit: function() {
var valid = true,
oView = this.getView(),
aFormInitial = oView.byId("formInitial").getContent(), // get all the controls of SimpleForm1
aFormConfig = oView.byId("formConfiguration").getContent(), // get all controls of SimpleForm2
aControls = aFormInitial.concat(aFormConfig), // combine the 2arrays together into 1
aFilteredControls = aControls.filter(this.requiredAndVisible); // check each element if it required & visible using the 1st function. return only the controls that are both req'd & visible
aFilteredControls.forEach(function(oControl) { // in resultant array, check each element if...
if (!oControl.getValue() || oControl.getValue().length < 1) { // its value is null or blank
oControl.setValueState("Error");
valid = false; // set valid to false if it is
} else {
oControl.setValueState("None");
}
});
if (valid === false) {
// **replace this code with w/e error handling code u want**
oView.byId("errorMsgStrip").setVisible(true);
} else if (valid === true) {
// **replace this code with whatever success handling code u want**
var oDialogConfirm = new sap.ui.xmlfragment("dialogID", "dialog.address.here", this);
oDialogConfirm.open();
}
},
I have inspect the element in app that run local in HCP, the id is application-MaintainMasterData-display-component---addRoute--form, but when I deploy to cloud, the id changed to application-MaintainFleet-Display-component---addRoute--form
The app name changed, and the display in the upper class way, which makes my sap.ui.getCore().byId() failed in cloud. I was confussing why this happens.
I've read the ref, I was in a Event handler, I need the oEvent scope, so this.getView().byId() and this.createId() won't works for me.
Ref:
sap.ui.getCore().byId() returns no element
https://sapui5.netweaver.ondemand.com/sdk/#docs/guide/91f28be26f4d1014b6dd926db0e91070.html
=========UPDATE=========
I also tried sap.ui.getCore().byId("application-MaintainMasterData-display-component---addRoute").byId("form") , but the same issue , view id is application-MaintainFleet-Display-component---addRoute in cloud.
The IDs are dynamically generated. So you cannot rely on them. That's why you should not use sap.ui.getCore().byId(). Even the separators -- and --- may change in the future.
You should always use the byId() method of the nearest view or component to resolve local ids. You can chain the calls: component.byId("myView").byId("myControl")
In your eventhandler this should refer to the controller. For XMLViews this should be the case without further doing.
So i guess you are using JSViews? If you attach an eventhandler in code you can always supply a second argument to the attachWhatever() functions: The Object that becomes this in the event handler.
Controller.extend("myView", {
onInit:function(){
var button = this.byId("button1");
button.attachPress(this.onButtonPress, this); //The second parameter will become 'this' in the onButtonPress function
},
onButtonPress: function(oEvent){
console.log(this); //this is the controller
var buttonPressed = oEvent.getSource(); //get the control that triggered the event.
var otherControl = this.byId("table"); //access other controls by id
var view = this.getView(); //access the view
}
});
If you are using the settings-object-syntax you can supply an array for the events. It should contain the handler function and the object that should become this:
createContent:function(oController){
return new Button({
text: "Hello World",
press: [
function(oEvent){ console.log(this); }, //the event handler
oController //oController will be 'this' in the function above
]
});
If you are attaching to a non-UI5-event you can always use a closure to supply the view or controller to the handler function:
onInit:function(){
var that = this; //save controller reference in local variable
something.on("event", function(){ console.log(that); });
//you can use that local variable inside the eventhandler functions code.
}
I create an object that returns textBox(), which could change their properties depending on the user's actions. However, once I put the function doChange(e) inside the object as a method like this:
function textBoxExt() {
...
this.doChange = function(e) {...}
...
}
my code returns an error: Cannot find a function doChange()...
I tried different ways to declare a function as a method in my object, but none of them worked. Please tell me, how do I modify the code below to move doChange(e) inside the object as a method. It is possible for functions that calls by handlers?
var style = {
modified: {color: 'black', backgroundColor: 'yellow', },
};
function textBoxExt() {
var app = UiApp.getActiveApplication();
var changeHandler = app.createServerHandler('doChange');
var box = app.createTextBox();
box.addValueChangeHandler(changeHandler);
this.init = function(id) {
return box.setId(id);
}
}
var doChange = function(e){
var app = UiApp.getActiveApplication();
app.getElementById(e.parameter.source).setStyleAttributes(style.modified);
return app;
}
function doGet() {
var app = UiApp.createApplication();
app.add(new textBoxExt().init('box1').setText('text1'));
return app;
}
You cant do this with gas. Handlers are passed as text. Besides objects only exist during the current handler so it cant possibly be attached to an object from a previous server call.
The click seems to fire the event and set the cookies but pressing enter to submit doesn't set the cookies and instead the page redirects without the cookies.
function locationAuto() {
$('.search-location').focus(function () {
autocomplete = new google.maps.places.Autocomplete(this);
searchbox = this;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var thisplace = autocomplete.getPlace();
if (thisplace.geometry.location != null) {
$.cookie.raw = true;
$.cookie('location', searchbox.value, { expires: 1 });
$.cookie('geo', thisplace.geometry.location, { expires: 1 });
}
});
});
The .search-location is a class on multiple textboxes.
There is a submit button that takes the values from the cookies and redirects (server side)
Adapted from Jonathan Caulfield's answer:
$('.search-location').keypress(function(e) {
if (e.which == 13) {
google.maps.event.trigger(autocomplete, 'place_changed');
return false;
}
});
I've encountered this problem as well, and came up with a good solution. In my website I wanted to save the autocomplete.getPlace().formatted_address in a hidden input prior to submission. This worked as expected when clicking the form's submit button, but not when pressing the Enter key on the selection in the autocomplete's dropdown menu. My solution was as follows:
$(document).ready(function() {
// Empty the value on page load
$("#formattedAddress").val("");
// variable to indicate whether or not enter has been pressed on the input
var enterPressedInForm = false;
var input = document.getElementById("inputName");
var options = {
componentRestrictions: {country: 'uk'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
$("#formName").submit(function(e) {
// Only submit the form if information has been stored in our hidden input
return $("#formattedAddress").val().length > 0;
});
$("#inputName").bind("keypress", function(e) {
if(e.keyCode == 13) {
// Note that simply triggering the 'place_changed' event in here would not suffice, as this would just create an object with the name as typed in the input field, and no other information, as that has still not been retrieved at this point.
// We change this variable to indicate that enter has been pressed in our input field
enterPressedInForm = true;
}
});
// This event seems to fire twice when pressing enter on a search result. The first time getPlace() is undefined, and the next time it has the data. This is why the following logic has been added.
google.maps.event.addListener(autocomplete, 'place_changed', function () {
// If getPlace() is not undefined (so if it exists), store the formatted_address (or whatever data is relevant to you) in the hidden input.
if(autocomplete.getPlace() !== undefined) {
$("#formattedAddress").val(autocomplete.getPlace().formatted_address);
}
// If enter has been pressed, submit the form.
if(enterPressedInForm) {
$("#formName").submit();
}
});
});
This solution seems to work well.
Both of the above responses are good answers for the general question of firing a question when the user presses "enter." However - I ran into a more specific problem when using Google Places Autocomplete, which might have been part of the OP's problem. For the place_changed event to do anything useful, the user needs to have selected one of the autocomplete options. If you just trigger 'place_changed', the if () block is skipped and the cookie isn't set.
There's a very good answer to the second part of the question here:
https://stackoverflow.com/a/11703018/1314762
NOTE: amirnissim's answer, not the chosen answer, is the one to use for reasons you'll run into if you have more than one autocomplete input on the same page.
Maybe not the most user friendly solution but you could use JQuery to disable the enter key press.
Something like this...
$('.search-location').keypress(function(e) {
if (e.which == 13) {
return false;
}
});
I would like to add onDblClick event to codemirror 2. I found that onCursorActivity does not deliverer the event so there is no way for me from this method to filter the events.
How can I implement onDbClick event on Codemirror ?
Thanks in advance.
You can call on method on object returned by CodeMirror:
var cm = CodeMirror.fromTextArea(document.querySelector('textarea'));
cm.on('dblclick', function() {
alert('You double click the editor');
});
You can find the list of all available events in documentation.
Register a handler on the element returned by the getWrapperElement() method. Unless you want to not just detect double-clicks, but also prevent the default (select word under mouse cursor) from occurring... in that case I guess some modification of the core code is needed.
http://jsfiddle.net/yusafkhaliq/NZF53/1/
Since codemirror renders inside the element specified you can add an ondblclick event to the element, like below the highlighter renders without line numbers once double clicked that specific elements will display line numbers
var codeelems = document.getElementsByClassName("code");
for (i = 0; i < codeelems.length; i++) {
(function ($this) {
var value = $this.innerHTML;
$this.innerHTML = "";
var editor = CodeMirror($this, {
value: value,
mode: "text/javascript",
lineNumbers: false
});
$this.ondblclick = function () {
editor.setOption("lineNumbers", true);
}
})(codeelems[i]);
}