JavaScript did not receive value in this.form - javascript

I am using a three part code below:
First part of the code: Basically a javascript function changeSearchEngine will be triggered when user select Google.
<p id="searchbox">This paragraph will change once javascript is triggered</p>
<form align=right>
<select name="searchengine" onchange="changeSearchEngine(this.form)">
<option value="google">Google</option>
</select>
</form>
This is my changeSearchEngine function in javascript.
function changeSearchEngine(form)
{
var searchEngine=form.searchengine.value;
if (searchEngine=="google")
{
var url_google='<form method="get" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="" /><input type="submit" value="Google Search"/></form>';
document.getElementById("searchbox").innerHTML=url_google;
}
}
At this point of time, all is working well. When I select Google, the searchbox for google appears. I can search and everything.
Notice there is a onsubmit="submitGoogle(this.form)" right? I need to save what the user search terms into SQL table. So I have this javascript function below to capture what user have type:
function submitGoogle(form)
{
alert("Inside submitGoogle function");
var searchterm=form.q.value;
alert(searchterm); //to test. this part didnt capture the value.
}
I managed to invoke the submitGoogle function BUT however I can't retrieve the value of q despite using searchterm=form.q.value. What did I do wrong here?

In your onsubmit handler, you are passing this.form. But, this already refers to the form since it is the form itself that triggers the submit event. Form fields have a form property, but the form itself does not have a form property. So, just change your handler to pass this instead of this.form.
http://jsfiddle.net/fmqNj/
onsubmit="submitGoogle(this)"

Okay I found one possible solution. Let me answer my own question.
In changeSearchEngine(form) function, i change to this:
var url_google='<form method="get" name="googleform" action="http://www.google.com/search" onsubmit="submitGoogle(this.form)" target="_blank"><input type="text" name="q" size="31" maxlength="255" value="hello" /><input type="submit" value="Google Search"/></form>';
In submitGoogle(form) function, i change to this:
var searchterm=document.googleform.q.value;
But I still like others to comment on my solution whether it is not elegant or not within the practice. :D

Related

Pass a javascript variable to another page when form is submitted. with just html and Javascript

Good day, I am trying to pass a java script variable along with 2 user inputs. I am unable to get the code to work the email and name go to HighScore.php just fine, but I keep getting zero for the hidden field. highscore1 is the name of the variable. I don't know J Query, so I need a HTML java-script solution. Thank you for looking.
<form method="post" name="form" action="HighScore.php">
<input type="text" placeholder="Enter Name" name="username">
<input type="text" placeholder="Enter Email" name="email">
<input type="hidden" name="highscore1" id="hidden_score" value= highscore1>
<input type="submit" name="add" value=Enter>
</form>
I think in your case, you should first use javascript to get/set hidden_score input, you can use it anywhere in your html page, as long as you ensure that input is fully rendered, you can simply add it inside of $(function() { /*you can put your code here*/ }) for jQuery version, and document.addEventListener('DOMContentLoaded', function(event) { /*you can put your code here*/ })for javascript version
<script>
document.getElementById("hidden_score").value = "Set value here";
</script>
And then, in your HighScore.php, you can use this for getting that value depend on form method: $_POST['hidden_score'] for post and $_GET['hidden_score'] for get
function setHighScore()
{
document.getElementById("hidden_score").value = "Set value here";
}
now you can call the above function on any event that meets your requirement

How to Submit a Javascript Value in an Input Field

Simply, how can I do this?
<input type="hidden" value="some javascript value" />
I have a form whereby when a user clicks on Add More, more input fields are added via javascript.
I'm also using javascript-declared values to track and limit the number of fields a user can add.
I need a way for my php code to retrieve these javascript values.
Use append
$('#hidden').val('my Text');
input field should be
<input type="hidden" id="hidden"/>
the question is a bit vague, but i will give it a go
try adding a name as an array and then you can use get or post
<input name="myjavascriptinputs[]" type="hidden" value="some javascript value" />
in your php you will be able to use
foreach($_GET['myjavascriptinputs'] as $ajavascriptinput)
From the button you must be calling a javascript to add these fields dynamically. Simply append the code to that function to hand over these values to the field.
<input id="myinputfield[]" type="hidden" value="" />
<script>
function addOneMore(){
var newField = // code to add one more field
newField.value = newValue;
}
</script>
Will solve your purpose.

Form value to be empty if no change by user

I have a form with two inputs:
<input type="text" name="keyword" value="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" onfocus="wipe(this)"/>
and my JavaScript which gets rid of the pre-set value in form field as soon as you click it with your mouse is:
function wipe(obj)
{
obj.value="";
}
My question is, say the user doesn't type anything in the city field, how do I make it so that when the form is submitted the value for that field is empty and not the word City?
placeholder is a good attribute which can solve your problem its a past time history when we are used to using value for showing for which this textbox we have
<input type="text" name="keyword" placeholder="Search" />
if you still want to use java script modify your code something like this
<input type="text" name="keyword" value="Search" onfocus="wipe(this,'Search')" onblur="wipe2(this,'Search')"/>
<input type="text" name="city" value="City" onfocus="wipe(this,'City')" onblur="wipe2(this,'City')"/>
script function for second approch
function wipe(obj, str)
{
if(obj.value!=str){
obj.value="";}
}
function wipe2(obj, str)
{if(obj.value==""){
obj.value=str;}
}
You are using the wrong technique here. you should be using placeholder which is supported by most major browsers with the regular exception of IE. So if this is not a concern for you, you should definitely be using that. Especially, if you have a label element for that field. Otherwise you'd need to be checking for that input value on submission and see if it equals the string city
Just Declare a variable hasChanged and set it true when wipe function is called.Then call a function say 'SubmitFunction()'on the onclick function of Submit button.
<input type="text" name="keyword" value="Search" id="Search" onfocus="wipe(this)"/>
<input type="text" name="city" value="City" id="City" onfocus="wipe(this)"/>
<input type="submit" name="submit" value="submit" onclick="SubmitFunction();"/>
var hasChanged=false;
function wipe(obj)
{
hasChanged=true;
obj.value="";
}
function SubmitFunction()
{
if(hasChanged==false)
{
$("#City").val('');
}
}
at the time of submit why not check for value='city'
if(obj.value!='city')
{
//your code here
}
or if you have no problem in using jquery use watermark plugin this will handle browser compatibility problem also
Jquery Watermark
try this:
if($('input[name="city"]').val() && $('input[name="city"]').val() != 'city') { yourform.submit(); }
See How to prepopulate input text fields with prompting text which disappears on typing (jQuery) for some solutions to this. If you're okay with using HTML5, the best solution is probably to use "placeholder" instead of "value".
You should add one more attribute(eg. default <input type="text" name="keyword" default="Search" value="Search" onfocus="wipe(this)"/>) with value same as value attribute.
in on submit compare each form fields
function onSubmit(){
for (var fields in form)
if(form[fields].value== form[fields].getAttribute("default")){
form[fields].value = "";
}
}
}

Javascript login form doesn't submit when user hits Enter

I'm working on a simple javascript login for a site, and have come up with this:
<form id="loginwindow">
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="button" value="Check In" name="Submit" onclick=javascript:validate(text2.value,"username",text1.value,"password") />
</p>
</form>
<script language = "javascript">
function validate(text1,text2,text3,text4)
{
if (text1==text2 && text3==text4)
load('album.html');
else
{
load('failure.html');
}
}
function load(url)
{
location.href=url;
}
</script>
...which works except for one thing: hitting enter to submit the form doesn't do anything. I have a feeling it's cause I've used "onclick" but I'm not sure what to use instead. Thoughts?
Okay yeah so I'm well aware of how flimsy this is security-wise. It's not for anything particularly top secret, so it's not a huge issue, but if you guys could elaborate on your thoughts with code, I'd love to see your ideas. the code i listed is literally all I'm working with at this point, so I can start from scratch if need be.
There are several topics being discussed at once here. Let's try to clarify.
1. Your Immediate Concern:
(Why won't the input button work when ENTER is pressed?)
Use the submit button type.
<input type="submit".../>
..instead of
<input type="button".../>
Your problem doesn't really have anything to do with having used an onclick attribute. Instead, you're not getting the behavior you want because you've used the button input type, which simply doesn't behave the same way that submit buttons do.
In HTML and XHTML, there are default behaviors for certain elements. Input buttons on forms are often of type "submit". In most browsers, "submit" buttons fire by default when ENTER is pressed from a focused element in the same form element. The "button" input type does not. If you'd like to take advantage of that default behavior, you can change your input type to "submit".
For example:
<form action="/post.php" method="post">
<!--
...
-->
<input type="submit" value="go"/>
</form>
2. Security concerns:
#Ady mentioned a security concern. There are a whole bucket of security concerns associated with doing a login in javascript. These are probably outside of the domain of this question, especially since you've indicated that you aren't particularly worried about it, and the fact that your login method was actually just setting the location.href to a new html page (indicating that you probably don't have any real security mechanism in place).
Instead of drudging that up, here are links to related topics on SO, if anyone is interested in those questions directly.
Is there some way I can do a user validation client-side?
Encrypting Ajax calls for authentication in jQuery
3. Other Issues:
Here's a quick cleanup of your code, which just follows some best practices. It doesn't address the security concern that folks have mentioned. Instead, I'm including it simply to illustrate some healthy habits. If you have specific questions about why I've written something a certain way, feel free to ask. Also, browse the stack for related topics (as your question may have already been discussed here).
The main thing to notice is the removal of the event attributes (onclick="", onsubmit="", or onkeypress="") from the HTML. Those belong in javascript, and it's considered a best practice to keep the javascript events out of the markup.
<form action="#" method="post" id="loginwindow">
<h3>Login to view!</h3>
<label>User ID: <input type="text" id="userid"></label>
<label>Password: <input type="password" id="pass"></label>
<input type="submit" value="Check In" />
</form>
<script type="text/javascript">
window.onload = function () {
var loginForm = document.getElementById('loginwindow');
if ( loginwindow ) {
loginwindow.onsubmit = function () {
var userid = document.getElementById('userid');
var pass = document.getElementById('pass');
// Make sure javascript found the nodes:
if (!userid || !pass ) {
return false;
}
// Actually check values, however you'd like this to be done:
if (pass.value !== "secret") {
location.href = 'failure.html';
}
location.href = 'album.html';
return false;
};
}
};
</script>
Put the script directly in your html document. Change the onclick value with the function you want to use. The script in the html will tell the form to submit when the user hits enter or press the submit button.
<form id="Form-v2" action="#">
<input type="text" name="search_field" placeholder="Enter a movie" value=""
id="search_field" title="Enter a movie here" class="blink search-field" />
<input type="submit" onclick="" value="GO!" class="search-button" />
</form>
<script>
//submit the form
$( "#Form-v2" ).submit(function( event ) {
event.preventDefault();
});
</script>
Instead of <input type="button">, use <input type="submit">. You can put your validation code in your form onsubmit handler:
<form id="loginwindow" onsubmit="validate(...)">
it's because it's not a form submitting, so there's no event to be triggered when the user presses enter. An alternative to the above form submit options would be to add an event listener for the input form to detect if the user pressed enter.
<input type="password" name="text1" onkeypress="detectKey(event)">
Maybe you can try this:
<form id="loginwindow" onsubmit='validate(text2.value,"username",text1.value,"password")'>
<strong>Login to view!</strong>
<p><strong>User ID:</strong>
<input type="text" name="text2">
</p>
<p><strong>Password:</strong>
<input type="password" name="text1"><br>
<input type="submit" value="Check In"/>
</p>
</form>
As others have pointed out, there are other problems with your solution. But this should answer your question.
Surely this is too unsecure as everyone can crack it in a second ...
-- only pseudo-secure way to do js-logins are the like:
<form action="http://www.mySite.com/" method="post" onsubmit="this.action+=this.theName.value+this.thePassword.value;">
Name: <input type="text" name="theName"><br>
Password: <input type="password" name="thePassword"><br>
<input type="submit" value="Login now">
</form>
My Thought = Massive security hole. Anyone can view the username and password.
More relevant to your question: - You have two events happening.
User clicks button.
User presses enter.
The enter key submits the form, but does not click the button.
By placing your code in the onsubmit method of the form the code will run when the form is submitted. By changing the input type of the button to submit, the button will submit the form in the same way that the enter button does.
Your code will then run for both events.

How to get function to fire when buttonless form is submitted

I have a page with many forms on it. could be 1..200. None of these forms have buttons and they are built programatically. I am using jquery to submit all the forms that are checked.
function FakeName()
{
$("input:checked").parent("form").submit();
}
My forms look like:
<form name="FakeForm<%=i%>" action="javascript:void%200" onSubmit="processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Note: action is set to "javascript:void%200" so that it posts to a fake page. I want to handle my own posting in processRow.
OnSubmit never gets called and therefore ProcessRow never gets called.
Obviously all the names of the functions and variables have been changed to protect their identity :D
How can I get a function in each form to fire when I call submit programmatically.
The onsubmit handler is deliberately not triggered when you programatically submit the form. This is to avoid infinite recursion if an event handler would cause the event to be triggered again (and therefore the event handler to be called again)
However, of course you can call the processRow() function yourself in place of the .submit() call.
You're allowed to have inputs outside of forms. One school of thought is that a <form> shouldn't be a <form> if it's not intended to be submitted to the server via HTML.
Look up dispatchEvent and it's equivalent fireEvent. It's not the easiest thing in the world to use, but I think that's what you are looking for.
I'm surprised that there's no library that helps with this easily. Prototype (the one I've used the most) comes closest with a .fire() method on elements.
Looks like I may be able to do this:
<form name="FakeForm<%=i%>" action="javascript:processRow(<%=i%>)" method="post" style="margin:0px;">
<input type="checkbox" name="FakeNameCheck" value="FakeNameCheck"/>
<input type="hidden" name="FakeNum" value="<%= FakeNum%>"/>
<input type="hidden" name="FakeId" value="<%=FakeIdr%>"/>
<input type="hidden" name="FakeAmt" value="<%=FakeAmount%>"/>
<input type="hidden" name="FakeTrans" value="FakeTrans"/>
</form>
Are there any drawbacks to this?

Categories

Resources