Reputation: 27
I'm having trouble getting this code to work. I am trying to create a URL from any text put into the form. For instance, if you submit "Hello" in the text field, it will result in "http://www.Hello.com." Any indicators as to why this isn't working would be appreciated.
Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body>
<form name="search" action="jsTest.html" onsubmit="return URL()" method="post">
Query: <input type="text" id="query" name="query"/><br>
Submit: <input type="submit" value="Submit"/>
</form>
<script type="text/javascript">
function URL()
{
var x = document.search.query.val();
document.write("http://www.");
document.write(x);
document.write(".com/");
return false;
}
</script>
</body>
</html>
Upvotes: 0
Views: 100
Reputation: 2615
Answer:
<form>
Query: <input type="text" id="query" name="query"/><br>
Submit: <input type="submit" value="Submit" onclick="getURL()"/>
</form>
<script type="text/javascript">
function getURL()
{
var x = document.getElementById("query").value;
alert(x); //Debug statement
}
</script>
Righteo. No idea what's happening here, so I rewrote it from scratch. This works, I tested it, at the very least, to use the alert
box.
What may have been happening:
I think that javascript functions might need to start with a lowercase letter.
From w3schools:
JavaScript is case sensitive. The function keyword must be written in lowercase letters, and the function must be called with the same capitals as used in the function name.
I removed the action
from the form, because it was most likely trying to find that file and activate the javascript code in that file. I removed post
because that was screwing up on my computer, probably because it was running in offline browser mode (ie, not actually using HTTP requests like POST wants)
onclick
is all lowercase, not camelcase, which might have been causing some issues too. I always use onclick
rather than using form onsubmit
because generally your form will want to link to a .PHP
file, whereas using the button's onclick
allows for extra flexibility.
Upvotes: 1
Reputation: 19792
Use .value
not val()
, which is jQuery.
See: http://jsfiddle.net/wCS9d/
Upvotes: 0
Reputation: 3682
You can modify your javascript. I suggest you to using jQuery.
function modify_url(){
var q = $('input[name="query"]');
q.val('http://www.' + q.val() + '.com');
return true;
}
Upvotes: 0
Reputation: 27247
You set the x
variable but refer to the undefined query
variable. Keep your names consistent.
Upvotes: 1