Get a value from Javascript - javascript

I want to get the value that I entered in the prompt, and save it in a variable to use it to update a DB later .. I try this but is does not work !!
#{
var fileName = "";
var db = Database.Open( "GP" );
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
<html lang="en">
<body>
<script>
function myFunction() {
newName = prompt("Please enter new file name :");
if (newName != null)
{
#fileName = newName;
}
}
</script>
</body>
</html>

JavaScript is client side language. You can't updated db with it. You can send request to your server side script, which will update something in datatable.
You can find example of doing this here or just use google.

Try this code:
$(document).ready(function() {
var fileName = '';
var newName = prompt('Please enter a new file name');
if(newName != null) {
fileName = newName;
console.log(fileName);
}
});
Its getting the value you entered through javascript.
Demo here

From your question is not clear what is your goal.
If you want to store a value in your page waiting to use it when the page is posted, you could use a hidden input field.
In my example the value inputed when the page is loaded is stored until the user clicks the submit button:
#{
if(IsPost){
var fileName = Request["fileName"];
var db = Database.Open("GP");
var sqlupdate = "Update rc_Files set fileName=#0 Where fileID= 5";
db.Execute(sqlupdate, fileName);
}
}
<html lang="en">
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<form method="post">
<input type="hidden" name="fileName" id="fileName" value="" />
<input type="submit" />
</form>
<script>
$(document).ready(function () {
var newName = prompt('Please enter a new file name');
$('#fileName').val(newName);
});
</script>
</body>
</html>
Else, if you want to update your database without submitting your page, you should use Ajax. This article could help you: Posting Data With jQuery AJAX In ASP.NET Razor Web Pages.

Related

Update a JS array value with a global variable based on checkbox (true/false) form input

I'm using a WorldPay JS function to create a payment form. This function creates a TOKEN that can be reusable or not. I need to update the 'reusable' flag based on a form input (checkbox) but I can't get the global variable (reuse) to update. I've created a function CHECKED that updates the variable but the WorldPay JS just ignores it. I think is due the window.onload status, but I don't know how to fix it. Any help would be greatly appreciated.
<?php
include('./header.php');
require_once('./init.php');
?>
<html>
<head>
<title></title>
<meta charset="UTF-8" />
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type='text/javascript'>
var reuse = false;
function Checked(){
reuse = document.getElementById('check').checked;
Worldpay.submitTemplateForm();
}
window.onload = function() {
Worldpay.useTemplateForm({
'clientKey':'ENTER CLIENT KEY',
'form':'paymentForm',
'paymentSection':'paymentSection',
'display':'inline',
'type':'card',
'reusable': reuse,
'saveButton':false,
'callback':function(obj){
if (obj && obj.token && obj.paymentMethod) {
var _el = document.createElement('input');
_el.value = obj.token;
_el.type = 'hidden';
_el.name = 'token';
document.getElementById('paymentForm').appendChild(_el);
var _name = document.createElement('input');
_name.value = obj.paymentMethod.name;
_name.type = 'hidden';
_name.name = 'customer';
document.getElementById('paymentForm').appendChild(_name);
document.getElementById('paymentForm').submit();
}
}
});
}
</script>
</head>
<body>
<form action="./test.php" id="paymentForm" method="post">
<!-- all other fields you want to collect, e.g. name and shipping address -->
<div id='paymentSection'></div>
<div>
<input type="checkbox" id='check'>
<input type="submit" value="Place Order" onclick="Checked()" />
</div>
</form>
</body>
</html>
NOTE: I've removed the client ID so the code won't run.
Have you tried to use function "checked" on window.onload like this:
window.onload = function() {
Worldpay.useTemplateForm({
//code....
)}
function Checked(){
//code....
}

Email validation function not working properly with form button

I am working on my final project for my JS class. I have reached a bit of a roadblock, and was hoping for a little guidance.
I am looking to take the input (all coding needs to be done in JS) for email and validate. If the email is validated, then it should send the input to be written on a new webpage. If the the input is not valid, there should be an alert and the user should then reenter a proper email address.
This is just a portion of the project. I am creating having the user enter input information for a resume to written on the new page.
With the current state of the code, it is popping up the alert box that the email is not valid (even when it is). I have gotten it write if I take away the validation portion. However, it writes "undefined".
//html
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>
//JS email
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail(inputEmail) {
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open("");
openWindow.document.write(inputEmail);
}
}
If anybody would be so kind as to advise on this issue, I would be grateful. Thank you.
The issue was simply that you were passing inputEmail as the argument to test() when what you actually want to test is inputEmail.value. Demonstration below should work:
const validateEmail = (e, inputEmail) => {
e.preventDefault();
if (/^[^\s#]+#[^\s#]+\.[^\s#]+$/.test(inputEmail.value)) {
console.log(`${inputEmail.value} is a VALID email address :)`);
return true;
}
console.log(`${inputEmail.value} is an INVALID e-mail address. Please fix!`);
return false;
};
const init = () => {
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
document.querySelector('form').addEventListener('submit', e => validateEmail(e, inputEmail));
};
init();
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src="projectJS.js"></script>
<br><br>
<form>
<input type="submit" value="Create Resume">
</form>
</body>
add .value to get Input email like this:
var testRe = re.test(inputEmail.value);
I've solved your problem. Now it's working. Check it.
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail() {
var inputEmail = document.getElementById('email').value; //get email id
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open();
openWindow.document.write(inputEmail);
}
}
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>

Using AJAX to send and receive info from a server

I'm working on a page that is supposed to interact with the server via AJAX, but my experience with AJAX is extremely limited. Here's how the page is supposed to work.
When the button is clicked, if the "test" radio button is clicked, just display a pop up saying the input was valid.
When the button is clicked, if the "live" radio button is clicked, the program is supposed to send a request to the server using the URL "http://cs.sfasu.edu/rball/351/exam2.php" with the contents of the input box being the value for the "name" parameter.
The page will then send back a JSON object that I need to parse into a regular variable.
I'll leave the rest of the JSON stuff alone since that's not what I asked.
So far I have the design of the page done, but like I said I don't really know what I'm doing with the AJAX stuff. I have some code written for it, but not sure that it's right.
Here is my code:
<html>
<head>
<title>anner, Taylor</title>
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type = "text/javascript">
window.onload = function() {
var TTcanvas = document.getElementById("myCanvas");
var TTcontext = TTcanvas.getContext("2d");
TTcontext.strokeStyle = "red";
TTcontext.fillStyle = "red";
TTcontext.fillRect(250,50,100,100);
TTcontext.stroke();
TTcontext.beginPath();
TTcontext.moveTo(600, 0);
TTcontext.lineTo(0, 200);
TTcontext.lineWidth = 5;
TTcontext.strokeStyle = "black";
TTcontext.stroke();
}
function validate() {
var TTinput = document.getElementById("3letters").value;
if(TTinput.length < 3 || TTinput.length > 3) {
alert("Please enter 3 letters");
}
var TTtest = document.getElementById("test");
var TTlive = document.getElementById("live");
if(TTtest.checked == true) {
alert("Input is valid");
}
else if(TTlive.checked == true) {
return ajaxStuff();
}
}
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
var TTresponse = TTrequest.responseText;
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML.TTresponse;
}
}
}
</script>
</head>
<body>
<h1>Tanner, Taylor</h1>
<canvas id = "myCanvas" width = "600" height = "200"></canvas> <br>
<form>
Enter 3 letters: <input type="text" id="3letters"> <br>
<input type = "radio" id = "test" value = "test">Test
<input type = "radio" id = "live" value = "live">Live <br>
<input type = "button" id = "check" value = "Send" onclick="validate()">
</form>
<div id="myDiv">
</div>
</body>
</html>
And here is a link to my page on our server:
cs.sfasu.edu/cs351121/exam2.html
Also, I know it says exam, but this is actually just a review we were given for the actual exam that's next week. I'm just trying to figure out how this works but don't know what I'm doing wrong.
I'm not sure what the problem is. The code is correct
Ok now i get the problem. You are calling the request variable outside the scope. You are declaring the request variable inside your ajaxStuff function so its only accessible in that area. Thats why it is undefined. Try this:
function ajaxStuff() {
var TTrequest = new XMLHttpRequest();
TTrequest.open("GET", "http://cs.sfasu.edu/rball/351/exam2.php?name=TTinput.value", true);
TTrequest.send();
TTrequest.onreadystatechange=function() {
if(TTrequest.readyState==4 && TTrequest.status==200) {
document.getElementById("myDiv").innerHTML=TTrequest.responseText;
}
}
}
to get the result just do this
TTrequest.send();
var response=TTrequest.responseText;
I know, I do not see the jQuery tag, but consider it if there are no framework restrictions.
Example:
$("button").click(function(){
$.ajax({url:"demo_test.txt",success:function(result){
$("#div1").html(result);
}});
});

In an AMT HTML Questio. for batch, how to generate all inputs

So I've been trying to generate the contents mturk_form using the DOM model for a Amazon Mechanical Turk HTML question. I ran into an interesting error when I generated ALL inputs using the script: I get the error Dhtml template must contain a question.
This error can be hacked around by putting an unnamed hidden input in the top of the page, like the example below. Remove the <input type="hidden" /> and the error comes back. Does anyone have a better way?
<p><input type="hidden" /> <script>
window.onload = create_form;
function validate()
{
var checkbox = document.getElementById("testbox");
if (checkbox.checked)
{
return true;
}
else
{
alert("failed validation");
return false;
}
}
function create_form()
{
var turkform = document.forms[0];
var testbox = document.createElement('input');
testbox.type="checkbox";
testbox.name="testbox";
testbox.id="testbox";
testbox.innerHTML="check to be valid";
turkform.appendChild(testbox);
turkform.appendChild(document.createTextNode('check to be valid'));
var submitbutton = document.getElementById("submitButton");
submitbutton .onclick=validate;
turkform.appendChild(submitbutton);
}
</script></p>

Populate Drop down from Text box in Javascript

I have an asp.net drop down list box and I want to populate it based on the value of the text box via javascript. The value is passed to the stored procedure which I created and the results will be populated in the drop down.
I did my research but I can't seem to find the right solution to this.
Need help please.
[UPDATE]
Here's the source code which I initially did:
HTML:
<asp:DropDownList runat="server" id="cboPriceID" AutoPostBack="true" onblur="LoadPrice()"/>
And I have a dataTable which is retrieved from the stored procedure. What I currently have is a javascript code which populates the textbox.
function LoadPart_CallBack(response) {
//if the server-side code threw an exception
debugger;
if (response.error != null) {
//we should probably do better than this
alert(response.error);
return;
}
var ResponseValue = response.value;
var al = ResponseValue.split(":");
var errormsg = al[0];
var partname = al[1];
if (errormsg == "") {
document.getElementById("<%=txtPartName.ClientID%>").value = partname;
}
}
Need help on how to populate it.
<html>
<body>
<input type="text" id="data" name="data"/>
<input type="button" value="Add" onclick="addData()"><br/>
<select id="choice">
</select>
<script type="text/javascript">
function addData()
{
var txt=document.getElementById("data").value;
if(txt!="")
{
var newcontent = document.createElement('option');
newcontent.innerHTML = txt;
document.getElementById("choice").appendChild(newcontent);
document.getElementById("data").value="";
}
}
</script>
</body>
</html>

Categories

Resources