How to put an Application's value as a variable in javascript? - javascript

I have a counter that updates itself everytime the page loads. I want to use that counter's value as a variable in javascript so that I could use it. How do I do this?
if (Application["counter"] == null)
{
Application["counter"] = 0;
}
if (Application["counter"] != null)
{
if (Request.Form["sub1"]==null)
{
Response.Write("<script>alert('You must Enter Number')</script>");
}
if (Request.Form["sub1"] != null)
{
Application["counter"] =(int)Application["counter"]+ 1;
Response.Write(Application["counter"]);
}
}
this is the code for the counter in the cs page.
Whenever I go to write Javascript and try to save it as a variable it gives me an error: Error 16 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.
var y=<%Application["counter"];>%;

For the server side code, you can use it like below. Just a recommendation. And for front end side, you have typos.
// Server side code - Correct usage
if (Application["counter"] == null) {
Application["counter"] = 0;
}
// there's no need to check Application["counter"] after the code above
if (Request.Form["sub1"] == null)
{
Response.Write("<script>alert('You must Enter Number')</script>");
}
// also, you can use else in here instead of another if, because there isn't any other condition.
else {
Application["counter"] = (int)Application["counter"] + 1;
Response.Write(Application["counter"]);
}
// JS Code
var y = <%= Application["counter"] %>;

Related

Can I automate the calculate process and direct update to the table using Laravel Framework?

I'm new in programming, and I'm currently working on a rubric assessment module with Laravel Framework.
This is my code to handle the calculation of the marks in the Controller. However, I would like to update the calculation in real time without refreshing the page. Due to I'm lacking of knowledge in Javascript and JQuery, I would like to ask is there any way or sample code to perform the process in real time?
foreach ($rubricArtifactDetails as $rubricArtifactDetail) {
foreach ($rubricCriteriaDetails as $rubricCriteriaDetail) {
if ($rubricArtifactDetail['rubricArtifactId'] == $rubricCriteriaDetail['rubricArtifactId']) {
$finalMark = 0;
if ($rubricCriteriaDetail['markSupervisor'] !== null && $rubricCriteriaDetail['markModerator'] !== null) {
$finalMark = ($rubricCriteriaDetail['markSupervisor'] + $rubricCriteriaDetail['markModerator']) / 2;
} elseif ($rubricCriteriaDetail['markSupervisor'] === 0 || $rubricCriteriaDetail['markModerator'] === 0) {
$finalMark = ($rubricCriteriaDetail['markSupervisor'] + $rubricCriteriaDetail['markModerator']) / 2;
} elseif ($rubricCriteriaDetail['markSupervisor'] === null && $rubricCriteriaDetail['markModerator'] === null) {
$finalMark = 0;
} elseif ($rubricCriteriaDetail['markSupervisor'] === null) {
$finalMark = $rubricCriteriaDetail['markModerator'] / 2;
} elseif ($rubricCriteriaDetail['markModerator'] === null) {
$finalMark = $rubricCriteriaDetail['markSupervisor'] / 2;
}
$finalMarkArray[$t] = $finalMark;
$t++;
}
}
}
This is my sample output for the rubrics, however it only update the marks by clicking the submit button.
https://imgur.com/a/36Ui93K
The only way to achieve this in realtime, you need to use AJAX.
jQuery's $.ajax is one of the simplest method to perform this task.
Create an independent web route for calculation and link it to the respective controller's method.
Create a $.ajax function in your view or script file. (Though *.blade.php is better place to execute this function as you'll be able to access the variables much easily.)
// Javascript part
$.ajax({
url: `{{ route() }}`,
method: 'GET/POST/PUT/DELETE',
data: {
// If you want to send some params to the controller.
// You will receive the contents in `$request` object.
},
done: result => {
// This callback is only called when your request succeeds.
// This is the place where you need to update your HTML via DOM manipulation.
},
fail: result => {
// This callback is only called when your request fails.
},
always: () => {
// This callback is always called after a specific request is completed.
}
});
<?php
class TestController extends Controller {
public function calculate(Request $request) {
// DO YOUR CALCULATION
// Instead of returning view, return a JSON from here.
return response()->json(['status' => true, 'result' => 'YOUR_RESULT']);
}
}
?>
jQuery API Documentation: https://api.jquery.com/jquery.ajax/
Laravel JSON Response Documentation: https://laravel.com/docs/7.x/responses#json-responses

Having problems with Javascript Else If statement in Node Red

I have been fighting this problem all day. Heres a snippet of my code, 5 lines down in the else if is where things get screwy. I am also new to Javascript so that may be the reason I am unable to spot the mistake, but from what I have seen elsewhere, this code should work. Also the comments on lines 5 and 6 are swapped.
if (msg.payload.License_Plate !== null) {
// This portion checks for a valid number plate
if (readlpr == dblpr); { // we have a direct match, open the gate
opengate = 1; // will send open signal to gpio
} else if(readlpr !== null); { // from here on, we are checking for a partial plate match
validdigits = 0; // make sure we have data before continuing, as may be a rfid match
{
if (!context.count); { // check to see if counter already used, if not initialise it
context.count = 0;
Image of error message
You have a few errors:
if (readlpr == dblpr); {
...
} else if(readlpr !== null); {
...
if (!context.count); {
And also an extra opening-brace.
These shouldn't have a semi colon on the end:
if (readlpr == dblpr) {
...
} else if(readlpr !== null) {
...
if (!context.count) {
In the end it should look something like this:
if (msg.payload.License_Plate !== null) {
if (readlpr == dblpr) {
opengate = 1;
} else if(readlpr !== null) {
validdigits = 0;
// { <!-- Remove this as well, it's an extra brace
if (!context.count) {
context.count = 0;

How to check if all controls on the page are empty?

I have a method that is supposed to loop over all of the controls on my page and return false if any one of them has a value other than empty string / null. This gets called as part of an OnSaveValidation. If the form is empty, they should be able to save.
function IsFormEmpty()
{
var ancestor = document.getElementById('PAIQIFunc'); //PAIQIFunc is the id of a div
var descendents = ancestor.getElementsByTagName('*');
var i = 0;
for (i = 0; i < descendents.length; ++i)
{
var e = descendents[i];
try
{
var eVal = $("#" + e).val();
// just check to make sure eVal has *some* value
if (eVal != '' || eVal != undefined || eVal != null)
return false;
}
catch (err){
//simply move on to next control...
}
}
return true;
}
Code sourced from Loop through all descendants of a div - JS only
In most cases, var eVal = $("#" + e).val(); throws an exception because it's a div or something like that. I'm only interested in the 108 drop down menus and 1 textbox on my form.
I set a breakpoint on my if statement and it was never hit. But descendents has like 1200 elements in it; I couldn't possibly step through it all trying to find what I'm looking for...
How else could I modify the code to check each control on the page?
EDIT: I should note that the web application is a C# / ASP.NET project using Razor views and we're using Telerik's Kendo web UI controls, not "vanilla" .NET controls if that makes a difference. So all of the controls are defined in the .cshtml file like so:
#(Html.Kendo().DropDownListFor(m => m.SomeProperty).HtmlAttributes(new { id = "cmbSomeProperty", #class = "k-dropdown-width-30", #tabIndex = "1", style = "width:60px" }).BindTo(ViewBag.SomePropertyDataSource).OptionLabel(" "))
You could try the following:
var hasValue = false;
var div = document.getElementById('PAIQIFunc');
$(div).find('input')
.each(function() { // iterates over all input fields found
if($.trim($(this).val()).length != 0) {
hasValue = true; // if field found with content
break;
}
});
if(hasValue === false) {
// save logic here
}
Hope this helps.

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

CRM Xrm.Page.ui.formSelector.items.get() Returning Null

I wrote javascript code and added it as a form on load event of entity(contact). In that Code I want to navigate from the opening form to another form.
For previous developments, I'm trying to get the id of the opening form which I need in order to navigate.
Code as shown below.
var id = Xrm.Page.ui.formSelector.getCurrentItem().getId();
if (itemid != null)
Xrm.Page.ui.formSelector.items.get(id).navigate();
Xrm.Page.ui.formSelector.getCurrentItem() function returns a null value. It doesn't get the item so I can't get the value. What's wrong with that code, what am I missing?
Thanks for replies in advance.
You are assigning the value to id variable but checking itemid in your IF condition.
In if condition just replace the if (itemid != null) with if (id != null)
To test your JavaScript. You can run following function:
var formItem = Xrm.Page.ui.formSelector.getCurrentItem();
if (formItem != null)
{
var itemId = formItem.getId();
var itemLabel = formItem.getLabel();
alert(itemId + " | " itemLabel);
}
else
{
alert("Unable to get current form");
}
Finally, to switch between form, following is very useful function which takes the form name as parameter. you can make changes to use form Id if you like.
function redirectToForm(formName) {
var currentForm = Xrm.Page.ui.formSelector.getCurrentItem();
if (currentForm != null) {
if (currentForm.getLabel().toLowerCase() != formName.toLowerCase()) { //make sure it's not already this form
var availableForms = Xrm.Page.ui.formSelector.items.get();
for (var i in availableForms) {
var form = availableForms[i];
if (form.getLabel().toLowerCase() == formName.toLowerCase()) {
form.navigate();
}
}
}
}
}
In My case, i prefer send the form name as parameter of a kind function such as constructor via load form function.
in the javascript code:
var Formname = "Default";
function Initialize(formname)
{
Formname = formname;
}
In customization of Form, in the onload function, you set this variable and this way remove the dependece from for selector component.
I hope that this solution can help many.
I took it up a notch and wrote the following post. You might find it interesting.
http://totbcrm.blogspot.co.il/2014/08/working-with-multiple-forms.html

Categories

Resources