VBA Excel run javascript form event - javascript

I’ve already tried to get the element by id, however, the html does not include it. As shown below, this is the script for the drop down that I am trying to change automatically. It will change the name with
appIE.Document.getElementById("supervisor").Value = "Sup_name"
However, it doesn’t fire the event that generates a list of people.
The top of the form also includes <form id='filterform' action="javascript:void(0);">
The JavaScript containing the function I need to call is below.
<script type="text/javascript">
$(function() {
$('#supervisor').change(function() {
document.getElementById('results').innerHTML = '<img src="/img/busy.gif" />';
var str = $('#filterform').serializeArray();
$.ajax({
url: 'ajax.php?p=agentrosters&mode=1&field=supervisor',
type: 'POST',
data: str,
success: function(j) {
//alert(j);
document.getElementById('results').innerHTML = j;
document.getElementById('lastsearch').value = 'supervisor';
resetscript('supervisor');
},
failure: function() {
document.getElementById('results').innerHTML = 'There has been an error, please try again';
resetscript('null');
}
})
})
})
</script>
Any Ideas on how I can get this to work?

If the element is part of a form you may to submit the form, alternatively you can use the onchange event on the element itself. So you may want to change appIE.Document.getElementById("supervisor").Value = "Sup_name" to
With appIE.document.getElementById("supervisor")
.Value = "Sup_name"
.onchange
End with
And if it is part of a form change the ".onchange" to
".parentElement.Submit"
This worked for me.

Related

Error when trying to populate a drop-down box with a javascript array generated by a REST API call

I have a page with a hidden drop-down box that appears when a checkbox is ticked via a JavaScript inner.HTML = command. As I'm aware I wouldn't be able to populate this from a document.onload function, I've got a <div>, that I'll be setting to style="display:none" when I have this working, where I have a drop-down box in for the options to be populated to, however I'm getting the error message 'Unable to set property 'innerHTML' of undefined or null reference' when attempting to do this. Is a <select> tag not able to have an ID or innerHTML value given to it?
Code is below:
var systemOptions = [];
var system = document.getElementById("systemstemp");
document.onload = getSystems();
function getSystems() {
$.ajax({
url: ".../_api/web/lists/getbytitle('Application List')/items?$select=Title",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
systemOptions = data.d.results;
for (var obj in systemOptions) {
system.innerHTML = "<option value='" + systemOptions[obj].Title + "'>" + systemOptions[obj].Title + "</option>";
}
}
});
}
<p><select id="systemstemp"></select></p>
systemOptions = [
{Title: "Call Platform"},
{Title: "CRM"},
{Title: "Email"},
{Title: "Monitoring"},
]
The problem is that when you do:
document.onload = getSystems();
you're actually calling getSystems function immediately and not when document.onload fires. In order to run getSystems when onload triggers, set the function without parenthesis:
document.onload = getSystems;
or assign the function directly to the document.onload:
document.onload = function() {
$.ajax({...});
}
EDIT
You should also use DOM API to create the select options like in this Q/A:
Adding options to select with javascript

Post to PHP backend from javascript code

I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?
Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')
Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

Fetch value of Dynamic textbox in javascript

I am dynamically creating a textbox at runtime using javascript and passing its value to my servlet page using a href(which is also created at run time along with the textbox) but somehow the value is being passed as "Null". I am not understanding it why..Can anyone help me on this ??
Here is my javascript code :
//here I am creating textbox
var td1 = document.createElement("TD");
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"in_name\" id =\"in_nm\" SIZE=\"18\" STYLE=\"height:24;border: 1 solid;margin:0;\">";
td1.innerHTML = strHtml1.replace(/!count!/g, count);
//Here I am fetching its value
var nm=document.getElementById("in_nm");//this value is being passed null
//Here I am passing it through a href tag
var strHtml3 = "<a id=\"link\" href=\"UserHandler?action=insert&&name="+nm+"\">Add Row</a>";
td3.innerHTML = strHtml3.replace(/!count!/g, count);
var dt=document.getElementById('in_dt');
You never put your HTML string into the document, so you can't fetch it from the document.
The DOM you have created never been placed in the document so you can't catch it.
In addition, if you immidietly catch the element it will be empty all the time.
You can append the input field to the body as hidden and then to fetch it.
strHtml1.style.display = 'hidden';
document.body.appendChild(strHtml1);
// At this point the dom is in the HTML and it is not visible and now you can use it.
Add it before your fetching the value.
For those who are facing similar problem as mine, I am posting the solution for their reference
The problem was solved by fetching the value onchange and passing request through ajax as :
$(".edit_trr").click(function() //edit_trr is my class of the dynamic row added
{
}).change(function()
{
var nam=$("#in_name").val(); //in_name is my id of the textfield
var datastr='name='+nam;
if(nam.length >0) //checks if there is value in textfield
{
$.ajax({
type: "POST",
url: "add.jsp", //link of my jsp page where data is added in database
data: datastr,
cache: false,
success: function(html)
{
alert('Inserted');
}
});
}
else
{
alert('Enter Something');
}
});
On JSP page request send can simply be fetched as :
request.getParameter("name");

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Categories

Resources