Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.
Related
On the top of my server's doPost I collect the parameter names arriving and iterate through them to collect their values using request.getParameterValues(pName). That has been well tested and is currently producing this for my new transaction:
NodeID : []
function : [modify]
This tells me that the parameter 'NodeID' is being sent, but no value is coming through. I put in an alert just before form submission to see what the form looked like in the developer's DOM display, and it appears as so:
<form id="modify" action="/BackToTech/server?function=modify" method="post">
<input name="NodeID" value="28" />
</form>
This is the javascript function producing and submitting the form.
function modify(nodeID) {
alert("node.id = " + nodeID);
var root = document.body;
var form = $('<FORM>')
.attr('action', "/BackToTech/server?function=modify")
.attr('method', "post")
.attr('id', "modify")
.appendTo(root);
$('<INPUT>')
.attr('name', 'NodeID')
.attr('value', nodeID)
.appendTo(form);
//alert('delay');
$('#modify').submit();
}
The first alert reports nodeID is 28.
Any errors jump out at you? I thought I did the same thing recently for a delete transaction and got it working before replacing it with an ajax call instead, so I have confidence in the approach. I guess I might as well include the top of my server's doPost:
Enumeration<String> pNames = request.getParameterNames();
ArrayList<String> parameterNames = new ArrayList<String>();
while(pNames.hasMoreElements())
parameterNames.add(pNames.nextElement());
Object[] orderedNames = parameterNames.toArray();
Arrays.sort(orderedNames); //.sort(parameterNames)
for(int i=0; i<orderedNames.length; i++) {
String pName = orderedNames[i].toString();
for(int v=0; v<(25-pName.length()); v++) {
System.out.print(' ');
}
System.out.println(pName + " : " + Arrays.asList(request.getParameterValues(pName)));
}
Found it. Had a form I'd forgotten about in the navigation pane with the same name. Submission was being done on that path to this transaction, where no one had selected a NodeID from an accompanying select box.
I have an Input that takes a name, and I want to take that name from input and set the url accordingly .. Here's the code, and an example
.form-group
%input.form-control{'type':'name','placeholder':'Name',id:'wisher_name'}
%input.form-control{'type':'name','placeholder':'Special Message'}
%button.btn.btn.btn-success{'id':'wisher_btn'} Wish
Javascript
$(document).ready(function() {
$(document).on('click', '#wisher_btn', function() {
var e = document.getElementById("wisher_name");
var diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali/" + diwali_wisher);
});
});
But the last statement is never reached, I don't know why?
This is a very basic problem, but I am a beginner so need some help.
You need to use a full url, like https://stackoverflow.com.
Add the http protocol.
diwali_wisher= Input parameter name in receiver function
diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali?diwali_wisher=" + diwali_wisher);
I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"
DISCLAIMER: total beginner with regards to browser extensions and javascript.
BACKGROUND:
I'm trying to develop a proof-of-concept Chrome extension that picks up the text from the input fields in the HTML form of the web page loaded into one tab, and enters the same text on analogous fields of the page in another tab.
In my particular example, the source page is a minimal, local HTML file with two input fields ("user name" and "password"), and the destination is the login page for Apple's Developer Website (https://developer.apple.com/account/).
Reading the official guides and questions here, I've put together some code that seems to work.
THE PROBLEM:
Only text consisting of digits (e.g.: "111111") gets copied from one tab to the other. As soon as my input field contains letters (e.g.: "111111a"), nothing happens.
This is the source page (local file:///):
<html>
<head>
<title>Source Page</title>
<meta charset="utf-8" />
<script src="popup.js"></script>
</head>
<body>
<form>
<input id="accountname_src" name="appleId" placeholder="Apple ID" /><br />
<input id="accountpassword_src" name="password" placeholder="Password" />
</form>
</body>
</html>
The destination HTML (Apple's page) has similar input fields with element ids of accountname and accountpassword, respectively.
My extension's script is as follows:
document.addEventListener('DOMContentLoaded', function(){
// The button in the browser action popup:
var button = document.getElementById('autofill');
var sourceTabID = null;
var destTabID = null;
// Get the SOURCE tab id:
chrome.tabs.query({'title': 'Source Page'}, function(tabArray){
sourceTabID = tabArray[0].id;
});
// Get the DESTINATION tab id:
chrome.tabs.query({'title': 'Sign in with your Apple ID - Apple Developer'}, function(tabArray){
destTabID = tabArray[0].id;
});
if (button !== null){
button.addEventListener('click', function(){
// Get entered text from Source page:
chrome.tabs.executeScript(sourceTabID, {file: "read_input.js"}, function(results){
var credentials = results[0];
var userName = String(credentials[0]);
var password = String(credentials[1]);
// Pass values to Apple login page:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
var autofillCode = insertUserNameCode + insertPasswordCode;
chrome.tabs.executeScript(destTabID, {code:autofillCode});
});
//window.close();
});
}
});
of course, the contents of read_input.js are:
var userName = document.getElementById("accountname_src").value;
var password = document.getElementById("accountpassword_src").value;
var attributes = [userName, password];
attributes // (Final expression, passed to callback of executeScript() as 'results')
It feels like there could be a type inference problem somewhere, but can't tell where.
Bonus Question:
I can read the input fields in the source page using an external script (read_input.js above) and the method chrome.tabs.executeScript(..., file:...; but when I try to write the values to the destination tab using a similar approach, the script does not run (that is why I'm using chrome.tabs.executeScript(..., code:... in my code). Any idea what can be happening?
Silly me (again)... Some console.logging led me in the right direction...
I was not escaping the value in the script; these lines:
var insertUserNameCode = "document.getElementById('accountname').value = " + userName + ";"
var insertPasswordCode = "document.getElementById('accountpassword').value = " + password + ";"
...should be:
var insertUserNameCode = "document.getElementById('accountname').value = '" + userName + "';"
var insertPasswordCode = "document.getElementById('accountpassword').value = '" + password + "';"
(added single ticks around the values)
...so that the code ends up as:
document.getElementById('accountname').value = '111111a';
...instead of:
document.getElementById('accountname').value = 111111a;
Still not sure why a numbers-only value works, though.
My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}