I have a simple registration form. As soon as the user types his phone number and leaves the textbox (onblur), a few of the other fields get auto populated, using an Ajax call to a php script, and this piece works fine. Now, I'm trying to add another onblur() event ON A DIFFERENT TEXT FIELD that has nothing to do with the ajax call or the fields populated but is in the same form. However, when I create this function in java script, the event does not get fired. More over, the original ajax call also stops working i.e., the onblur event for the phone number field also does not get fired (I've confirmed this by putting a few alert messages in place). I'm stuck and given that I'm a novice web developer, it has been an irritable ride. So any help or a nudge in the right direction would be appreciated.
My java script code is in the same file as my HTML code, i.e., between the tags. When I create both the functions between the same script tags, none work, but when I put them in separate script tags, the first function (ajax call behind Phone number) gets fired on blur but the second one does not. The functions in point are: vldtnPhNo() and enabtnRegCmplt().
<script type="text/javascript">
function vldtnPhNo()
{
var xhr;
var dvPhNo = document.getElementById("divPhNo");
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
var FoneNumb = document.getElementById("txtPhNo").value;
xhr.open("POST", "verify.php", true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
document.getElementById("txtRegInv").value = xhr.responseText;
var rstOftheTxt = xhr.responseText;
document.getElementById("txtPhNo").value=rstOftheTxt;
document.getElementById("txtPhPop").value=rstOftheTxt;
}
else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}
xhr.send("txtPhNo=" + FoneNumb);
}
else
{
throw new Error("Ajax is not supported by this browser");
}
}
function enabtnRegCmplt(){
If(txtRegInv.value!="")
{
var UsrNm;
var Psswd;
var RePsw;
var PostBackInfo;
UsrNm = document.getElementById('txtUsrNm');
Psswd = document.getElementById('txtPsw');
RePsw = document.getElementById('txtrePsw');
txtRegInv = document.getElementById('txtRegInv');
If (RePsw.value!="" && Psswd.value!="" && UsrNm.value!="" && RePsw.value==Psswd.value)
{
document.getElementById('btnRegCmplt').disabled="False";
}
else if(UsrNm.value=="")
{
UsrNm.value="Please Enter UserName";
}
else if(Psswd.value=="")
{
Psswd.value="Please Enter Password";
}
else if(RePsw.value=="")
{
RePsw.value="Does not match";
}
}
}
</script>
Your code is very messy. One of the reason why it's necessary to write neat code. Your brackets are wrong, thus the whole code isn't executed (else statement is connected with function).
The If statement doesn't exist, try if instead (lowercase I).
Other things:
use onkeyup instead.
2:
For the vars you could do:
var UsrNm,
Psswd,
RePsw,
PostBackInfo
;
OR
var UsrNm = document.getElementById('txtUsrNm'),
etc.
Syntax mistake
An extra brace }
`else
{
document.getElementById("txtPhNo").value='waiting';
document.getElementById("txtPhPop").value='waiting';
}
}
}`
Remove one brace after the else condition
Related
I have the following code. There is a button in the UI that when clicked executes the if statement. I pass in a URL from a database and compare it to the current URL the user is on. If they match I want to run the code below, else I want to open the correct tab then run the code below.
With this code below I mean everything below starting from $('#sceanrioDropdownList').change(function () {...}. The code then checks a drop down and gets the selected Id from which an AJAX call is made to my web API that uses that Id in a stored procedure to return the results. The returned data is then iterated over and stored in variables which I am using to append to specific inputs, buttons and drop downs.
This is what I have so far and I think I have developed this correctly. The issue that I am currently having is that the UI wants everything from ... to be run if the if statement is true. I have tried CTRL+C and CTRL+V to copy the code into the if statement. I have also tried putting it in a new function and referencing that function n the if statement. Both do not work and I was using console.log to inspect the returned data.
It does however when I attempt to call it from inside i statement it doesn't return any data or error. It just doesn't seem to fire.
Is there a way in which I can achieve the functionality I desire? Do you have any suggestions as to if I have done something wrong. Thanks in advance.
$('#automate').click(automateButton);
function automateButton() {
if (webpageUrl == activeTabUrl) {
// do nothing
} else {
// Window opens
window.open(webpageUrl);
}
}
$('#scenarioDropdownList').change(function() {
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
function getData(scenarioId) {
$.ajax({
type: "GET",
url: 'http://localhost:54442/api/scenariodatas/GetScenarioData',
data: {
scenarioId: scenarioId
},
dataType: 'JSON',
success: scenarioData,
error: function() {
console.log("There has been an error retrieving the data");
}
});
}
function scenarioData(response) {
$.each(response, function(key, val) {
var fieldType = val.fieldType;
var fieldName = val.fieldName;
var fieldValue = val.fieldValue;
var field = $(fieldName);
if (field != undefined) {
switch (fieldType) {
case "Input":
$(field).val(fieldValue);
break;
case "Button":
$(field).click();
break;
case "Select":
$(field).val(fieldValue);
break;
}
}
})
}
onChange don´t work well with buttons because onChange detect a change in the value of your component, because of this, it´s highly recommended to use onClick when you use a button.
$('#scenarioDropdownList').click(function() {
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
I recommend you to put alerts when you are trying to test this sort of JS
EJM:
$('#scenarioDropdownList').change(function() {
alert('button active');
var scenarioId = $('#scenarioDropdownList option:selected').prop('id');
getData(scenarioId);
});
this alert allow you to know if the code is firing or not
Here's the problem. I'm making a callback to the server that receives an MVC partial page. It's been working great, it calls the success function and all that. However, I'm calling a function after which iterates through specific elements:
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(...)
Inside this, I'm checking for a specific attribute (custom one using data-) which is also working great; however; the iterator never finishes. No error messages are given, the program doesn't hold up. It just quits.
Here's the function with the iterator
function HideShow() {
$(".tool-fields.in div.collapse, .common-fields div.collapse").each(function () {
if (IsDataYesNoHide(this)) {
$(this).collapse("show");
}
else
$(this).collapse("hide");
});
alert("test");
}
Here's the function called in that, "IsDataYesNoHide":
function IsDataYesNoHide(element) {
var $element = $(element);
var datayesnohide = $element.attr("data-yes-no-hide");
if (datayesnohide !== undefined) {
var array = datayesnohide.split(";");
var returnAnswer = true;
for (var i in array) {
var answer = array[i].split("=")[1];
returnAnswer = returnAnswer && (answer.toLowerCase() === "true");
}
return returnAnswer;
}
else {
return false;
}
}
This is the way the attribute appears
data-yes-no-hide="pKanban_Val=true;pTwoBoxSystem_Val=true;"
EDIT: Per request, here is the jquery $.post
$.post(path + conPath + '/GrabDetails', $.param({ data: dataArr }, true), function (data) {
ToggleLoader(false); //Page load finished so the spinner should stop
if (data !== "") { //if we got anything back of if there wasn't a ghost record
$container.find(".container").first().append(data); //add the content
var $changes = $("#Changes"); //grab the changes
var $details = $("#details"); //grab the current
SplitPage($container, $details, $changes); //Just CSS changes
MoveApproveReject($changes); //Moves buttons to the left of the screen
MarkAsDifferent($changes, $details) //Adds the data- attribute and colors differences
}
else {
$(".Details .modal-content").removeClass("extra-wide"); //Normal page
$(".Details input[type=radio]").each(function () {
CheckOptionalFields(this);
});
}
HideShow(); //Hide or show fields by business logic
});
For a while, I thought the jquery collapse was breaking, but putting the simple alert('test') showed me what was happening. It just was never finishing.
Are there specific lengths of time a callback function can be called from a jquery postback? I'm loading everything in modal views which would indicate "oh maybe jquery is included twice", but I've already had that problem for other things and have made sure that it only ever includes once. As in the include is only once in the entire app and the layout is only applied to the main page.
I'm open to any possibilities.
Thanks!
~Brandon
Found the problem. I had a variable that was sometimes being set as undefined cause it to silently crash. I have no idea why there was no error message.
i need following function to be execute in Firefox.., but it is working fine in chrome. the problem was when i do 'Inspect Element With Firebug' it is working fine. the method 'EditEncounterBillStatus' is also hitting correctly. but when i don't use 'Inspect Element With Firebug' the method EditEncounterBillStatus is not hitting.. i tried a lot to sort out this. but still i can't can any one help me to find solution thanks in advance.
else if (element.trim() == "Approved") {
var TestPin = prompt("Please Enter your PIN");
if (TestPin != null) {
if (isNaN(TestPin)) {
alert("Please Enter a Valid Pin");
return;
}
else if (TestPin == pin) {
var postVisitData = { VisitId: vid};
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
});
window.location = "/Emr/Patients/Show?PID=" + pid;
}
else {
alert("Your Entered PIN Is Incorrect");
}
}
else {
return;
}
}
I would recommend doing it like this
else if (TestPin == pin) {
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid }, function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
return; // in case of side effects in unseen code
}
i.e. wait until the $.post has finished before changing the window.location
As the rest of your code is unseen there could be side effects of performing this in this way - hence the return where it is - but even then, not knowing the full call stack there could still be side effects - you have been warned
You should change location upon the success of the post call, so put that in your callback function body:
$.post("/Emr/WaitingRoom/EditEncounterBillStatus", { VisitId: vid },
function (data) {
window.location = "/Emr/Patients/Show?PID=" + pid;
});
This way you are sure you only change location when the post action was executed. Otherwise you risk that you change location before the post happens. In debug mode, and certainly when you step through the code, there is enough time for the post to finish in time, and so your original code then works.
Essentially what I need is to run some JavaScript after a record has been saved. This will pick up a guid from a field which has been populated by a plugin. My code looks like;
Xrm.Page.data.entity.save();
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
The problem is the code runs past the call to save() and continues executing before a plugin has populated the "new_copyguid" field. Is there a way to wait for the plugin to complete before continuing with the javascript? I have tried AddOnSave() without success. Any javascript callback seems to execute before the plugin finishes as well. The plugin is set to run synchronously.
I am performing this javascript from a button on the form. The button sets a field value and then saves the record, triggering the plugin. The button is a "Copy Entity" button which creates a clone. I need to open this new record in the browser.
I have read that this does not work either, as it happens before the save;
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
Any pointers would be great!
I think you'll have to run your logic in the OnLoad section. The save should force a refresh and your onload logic will run again. You'll need to do some check to see if the modified on date is within a certain time frame.
Other option is you perform the update manually through a rest call or Soap call, then you can read the value from the plugin in another call.
You can just wait for some seconds by putting this code.
function YourFunction()
{
Xrm.Page.data.entity.save();
OpenForm();
}
Its a new function.
function OpenForm()
{
setTimeout(function () {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
}, 3000);
}
Try this:
function onPageLoad() {
var formType = Xrm.Page.ui.getFormType();
if (formType == 0 || formType == 1) { // 0 = Undefined, 1 = Create
// If form is in Create Mode then
if (Xrm.Page.data != null && Xrm.Page.data.entity != null) {
Xrm.Page.data.entity.addOnSave(onSaveDoThis);
}
}
}
function onSaveDoThis() {
setTimeout(onFormSaveSuccess, 300);
}
function onFormSaveSuccess() {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
if (newguid == "") {
onSaveDoThis();
} else {
// Don't need to trigger the function onSaveDoThis anymore
Xrm.Page.data.entity.removeOnSave(onSaveDoThis);
Xrm.Utility.openEntityForm("new_myentity", newguid);
}
}
Try this:
function OpenForm()
{
setTimeout(function () {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
}, 3000);
}
I know this has been asked multiple times, but neither of the answers seem to help me.
I've been almost two days trying to get around this but I haven't been able to figure out what's going on.
I have the following code:
alert('Before document.ready');
$(document).ready(function () {
alert('Actual document.ready');
addNumberValidation($("#quantity"), $("#quantityError"));
addNumberValidation($("#price"), $("#priceError"));
$("#form").submit(function(){
var quantityValid = validar( $("#quantity"), $("#quantityError") );
var priceValid= validar( $("#price"), $("#priceError"));
var formValid = quantityValid && priceValid;
return formValid ;
});
});
function addNumberValidation(mainElement, errorElement) {
mainElement.keyup(function () {
validate($(this), errorElement);
});
}
function validate( mainElement, errorElement) {
var regex = /^[0-9]+$/;
var result = false;
if ( mainElement.val().match(regex)) {
errorElement.text('');
result = true;
} else {
errorElement.text('Must be a number');
result = true;
}
return result;
}
The script is getting loaded correctly because the "Before document.ready" alert is getting called correctly. Also, jQuery is getting loaded as well because other js code is executing properly.
My console shows no error whatsoever and the script under the sources tab in Chrome is complete.
I documented the functions to see if there was something wrong with that and it still didn't work.
Any insights of what could be going on?
Found the issue. Another library was making a conflict that avoided the document.ready to get called