I'm trying to create something to refresh the list of dates to all users every 30 seconds.
I dynamically create a table with the list of dates in my database using AJAX, the thing is that the refresh removes what the user was writing in the moment of the refresh so I'm saving what the user writes in javascript global variables, calling the refresh function, then filling the inputs with the information in the variables and focusing the input the user was on.
The thing is the inputs aren't filled nor focused.
this is my relevant code here:
var identificacionc = "";
var nombresc = "";
var apellidosc = "";
var telefonoc = "";
var posicionc = 0;
var ladoc = 0;
//This is called on input onfocus to record the id
function recuerdo(posicion, lado)
{
posicionc = posicion;
ladoc = lado;
}
function actualizar()
{
//This line is not relevant
listaragenda();
if (document.getElementById("datepicker").value != "")
{
//put the info in the global variables and it works even if they're dynamically created
identificacionc = document.getElementById("txtidentificacion" + posicionc).value;
nombresc = document.getElementById("txtnombres" + posicionc).value;
apellidosc = document.getElementById("txtapellidos" + posicionc).value;
telefonoc = document.getElementById("txttelefono" + posicionc).value;
//Here is where I call the function to refresh dates
listarcitas();
}
}
function listarcitas()
{
var objAjax = crearObjeto();
var fecha = document.getElementById("datepicker").value;
objAjax.open("POST", "clases/listarcitas.php", true);
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
objAjax.onreadystatechange = function()
{
if (objAjax.readyState == 4 && objAjax.status == 200)
{
document.getElementById("citaslistadas").innerHTML = objAjax.responseText;
//Checks if any global variable is not empty to start to fill them with the info
//nothing inside this If works
//posicionc and ladoc have the correct values
if (identificacionc != "")
{
document.getElementById("txtidentificacion" + posicionc).value = identificacionc;
document.getElementById("txtnombres" + posicionc).value = nombresc;
document.getElementById("txtapellidos" + posicionc).value = apellidosc;
document.getElementById("txttelefono" + posicionc).value = telefonoc;
if (ladoc == 1)
{
document.getElementById("txtidentificacion" + posicionc).focus();
}
else if (ladoc == 2)
{
document.getElementById("txtnombres" + posicionc).focus();
}
else if (ladoc == 3)
{
document.getElementById("txtapellidos" + posicionc).focus();
}
else if (ladoc == 4)
{
document.getElementById("txttelefono" + posicionc).focus();
}
}
}
}
objAjax.send("fecha=" + fecha);
}
//the interval every 30s
window.setInterval("actualizar()", 30000);
Everything retrieved from AJAX works fine everything is listed, even in the web browser console I make alerts of the variables, set the values and focus the dynamically created inputs, everything works fine.
But why this is not working in the code?
Thanks in advance
Related
I want a notification/email when a cell value in column 5 of the spreasheet changes to 'Buy' which is based on formula =IF(AND(B2>D2),"Buy","Skip"). Attachment Link provided below. The Sheet autorefreshes based on Googlefinance data.
I have tried the below script, but it triggers notification/Email only when I change the cell manually. I am not a code writer, but have managed to find below script and added some tweaks of my own.
Can somebody please help me in resolving this or provide an alternate solution?
Also script written on third Party apps will be appreciated.
function triggerOnEdit(e)
{
showMessageOnUpdate(e);
}
function showMessageOnUpdate(e)
{
var range = e.range;
SpreadsheetApp.getUi().alert("range updated " + range.getA1Notation());
}
function checkStatusIsBuy(e)
{
var range = e.range;
if(range.getColumn() <= 5 &&
range.getLastColumn() >=5 )
{
var edited_row = range.getRow();
var strongBuy = SpreadsheetApp.getActiveSheet().getRange(edited_row,5).getValue();
if(strongBuy == 'Buy')
{
return edited_row;
}
}
return 0;
}
function triggerOnEdit(e)
{
showMessageOnBuy(e);
}
function showMessageOnBuy(e)
{
var edited_row = checkStatusIsBuy(e);
if(edited_row > 0)
{
SpreadsheetApp.getUi().alert("Row # "+edited_row+"Buy!");
}
}
function sendEmailOnBuy(e)
{
var buy_row = checkStatusIsBuy(e);
if(buy_row <= 0)
{
return;
}
sendEmailByRow(buy_row);
}
function sendEmailByRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row,1,row,5).getValues();
var row_values = values[0];
var mail = composeBuyEmail(row_values);
SpreadsheetApp.getUi().alert(" subject is "+mail.subject+"\n message "+mail.message);
}
function composeBuyEmail(row_values)
{
var stock_name = row_values[0];
var cmp = row_values[1];
var volume = row_values[2];
var message = "The Status has changed: "+stock_name+" "+cmp+
" Volume "+volume;
var subject = "Strong Buy "+stock_name+" "+cmp
return({message:message,subject:subject});
}
function triggerOnEdit(e)
{
sendEmailOnBuy(e);
}
var admin_email='sendemail#gmail.com';
function sendEmailByRow(row)
{
var values = SpreadsheetApp.getActiveSheet().getRange(row,1,row,5).getValues();
var row_values = values[0];
var mail = composeBuyEmail(row_values);
SpreadsheetApp.getUi().alert(" subject is "+mail.subject+"\n message "+mail.message);
[https://docs.google.com/spreadsheets/d/12k5DF8rvuKex77B8uRWpx1FoMmSNaMdGvhNEEbXKCFc/edit?usp=sharing][1]
Apps script triggers cannot be trigerred by non manual input as specified in the documentation:
Script executions and API requests do not cause triggers to run. For example, calling Range.setValue() to edit a cell does not cause the spreadsheet's onEdit trigger to run.
What you can do instead is to set up a time-based trigger that scans your column 5 at regular interval and sends you an email if a cell contains 'Buy':
function sendEmailOnUpdate() {
var range = SpreadsheetApp.getActive().getRange('E2:E').getValues();
for (i = 0; i < range.length; i++) {
var cell = range[i];
if (cell == 'Buy') {
// Send email using Gmail
}
}
}
To set the trigger, head to Triggers and select time-based:
If you don't want to receive more emails for a cell you receive an alert for, make sure to make apps script change its value once the email has been sent.
In my entity (A) has 50 option set. If the user select 10 optionsset value and not selected remaining one, and he/she click save button. In that situation i need to alert user "To fill all the option set". I don't want to get the Schema name for the optionset individually, i need to get all the option set schema name dynamically.
Is it possible? Help me.
I have not tested this function, but you can try this and make changes if needed.
function IsFormValidForSaving(){
var valid = true;
var message = "Following fields are required fields: \n";
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
if (attribute.getRequiredLevel() == "required") {
if(attribute.getValue() == null){
var control = attribute.controls.get(0);
// Cheking if Control is an optionset and it is not hidden
if(control.getControlType() == "optionset" && control.getVisible() == true) {
message += control.getLabel() + "\n";
}
valid = false;
}
}
});
if(valid == false)
{
alert(message);
}
}
Ref: Microsoft Dynamics CRM 2011 Validate required form javascript
Required fields individual alert fire before the on save event. If you wish to prevent the single alert routine for all unfilled option sets you need to remove the requirement constraint and manage the constraint yourself, probably in your on save handler. I’m just writing the idea here (not tested).
// enter all optionsets ids
var OptionSets50 = ["new_optionset1","new_optionset2","new_optionset50"];
var dirtyOptions = [];
function MyOptionSet(id) {
var mos = this;
var Obj = Xrm.Page.getAttribute(id);
var Ctl = Xrm.Page.getControl(id);
Obj.addOnChange(
function () {
if (Obj.getValue() != null)
delete dirtyOptions[id];
else
dirtyOptions[id] = mos;
});
this.GetLabel = function() {
return Ctl.getLabel();
}
if (Obj.getValue() == null)
dirtyOptions[id] = mos;
}
function OnCrmPageLoad() {
for(var x in OptionSets50) {
OptionSets50 [x] = new MyOptionSet(OptionSets50 [x]);
}
Xrm.Page.data.entity.addOnSave(OnCrmPageSave);
}
//check for dirty options and alert
function OnCrmPageSave(execContext) {
var sMsg = "The following Optinsets Are Required: ";
var sLen = sMsg.length;
for(var os in dirtyOptions) {
sMsg += dirtyOptions[os].GetLabel() + "\n";
}
if (sMsg.length > sLen) {
execContext.getEventArgs().preventDefault();
alert(sMsg);
}
}
Im starting to do some small functions and tweaks on websites with javascript, but whats really bothers me is that I dont know how to run the javascript again after a function has run?
For instance if I call a function onclick which adds a user to an array that is shown in my website, the new user wont be displayed until the page is refreshed?
How do I work around this?
EXAMPLE:
if (!localStorage.myStorage) {
// CREATE LOCALSTORAGE
}else{
myArray = JSON.parse(localStorage.myStorage);
for (var i = 0; i < myArray.length; i++) {
if(myArray[i].id === 1){
$(".firstIdContainer").append("<p>" + myArray[i].userName + "</p>");
}
if(aUserLogin[i].id === 2) {
$(".secondIdContainer").append("<p>" + myArray[i].userName + "</p>");
}
}
}
$(document).on("click", ".btnRegisterUser", function() {
// ADD NEW USER TO LOCALSTORAGE
}
How do i make sure my new user i register will be shown immediately through my for loop displaying users.
Like:
if(!localStorage.myStorage){
// CREATE LOCALSTORAGE
}
function doIt(){
var myArray = JSON.parse(localStorage.myStorage);
for(var i in myArray){
var apd = '<p>' + myArray[i].userName + '</p>';
if(myArray[i].id === 1){
$(".firstIdContainer").append(apd);
}
else if(aUserLogin[i].id === 2) {
$(".secondIdContainer").append(apd);
}
}
}
}
doIt();
$('.btnRegisterUser').click(doIt);
Try creating a contentUpdate function that resets whatever is getting displayed and creates it again based on new variables (this would go at the bottom of a function to add the user, for example). The reason that variable changes aren't reflected in the DOM is that the DOM has no abstraction for how it was made; it's output, and it won't change itself based on what its input has done after it was put in.
If you just want to insert a new row into a table you don't need to refresh the page.
jsfiddle
html:
<table id="usertable">
<tr><td>user 1</td></tr>
</table>
<input id="newuser"></input>
<input id="adduser" type="submit"></input>
js:
var button = document.getElementById('adduser');
button.onclick = function(event) {
var user = document.getElementById('newuser').value
//add the user to your array here
//add a table row
var table = document.getElementById('usertable');
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = user;
event.preventDefault();
}
The following script worked in IE8 but not in IE9:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
if (document.findForm["cb_Row_PageAutoDelete_" + sub].checked) {
document.findForm["SHIP_QTY_" + sub].disabled=false ;
} else {
document.findForm["SHIP_QTY_" + sub].disabled=true ;
}
return true;
}
I can display the value of the SHIP_QTY field so I know it's on the page but the disable function does not work.
Thanks for your help.
If findForm is the name of the form, you want window.findForm rather than document.findForm. You can also just use the result of the other field's checked property directly rather than an if/else. So your code changes to:
function toggleSelect(fieldName)
{
var idx = fieldName.lastIndexOf("_");
var sub = fieldName.substring(19,idx);
window.findForm["SHIP_QTY_" + sub].disabled = window.findForm["cb_Row_PageAutoDelete_" + sub].checked;
return true;
}
I'm not too good on the whole JavaScript (I can do some basic validations) but this isn't my zone
I've got a piece of code below that I'm trying to understand what it does, I can read any code and understand a few parts, but this just stumped me.
Here:
function tm_search_click() {
if (document.getElementById('tm').value == 'Enter your trademark') {
document.getElementById('tm').style.backgroundColor = '#fcc';
return false;
} else {
window.location = '?tm=' + escape(document.getElementById('tm').value);
return true;
}
}
function qs(a) {
a = a.replace(/[[]/, "\[").replace(/[]]/, "\]");
var b = "[\?&]" + a + "=([^&#]*)";
var c = new RegExp(b);
var d = c.exec(window.location.href);
return d == null ? "" : decodeURIComponent(d[1]).replace(/+/g, " ")
}
if (qs("tm") != "") {
tm_trademark = document.getElementById("tm").value = unescape(qs("tm"));
tm_partner = "migu2008";
tm_frame_width = 630;
tm_frame_height = "auto";
tm_trademark_country_code = "GB";
tm_css_url = "http://remarqueble.com/api/theme/search_corporate.css";
document.getElementById("tmLoading").style.display = "block";
tm_on_search_result = function () {
document.getElementById("tmLoading").style.display = "none";
document.getElementById("tmLoaded").style.display = "block"
}
} else {
tm_search_method = "none"
}
That is all of it without the <script> tags.
Could I also edit this code so that it searches are made based on what option the user inputs?
I think it works like this (assuming that this is in tags inside html page)
Page loads.
The script checks if URL has 'tm' parameter. If it has, then it sets bunch of tm_.. parameters and callback function. I don't know how they are used.
User clicks something that triggers the tm_search_click
Script sets new URL for the page and browser starts loading that
Goto step 1.