I am not a Javascript Guru. But I found myself in a very tricky situation while writing a Jquery for one of Application.
Situation:
I have a form with different field. One of the field containing multiple values, say phone numbers. I am filling those numbers in a pop up - lightbox. Now, the problem I am facing is that I want to click the form button to submit my form but My numbers are coming from popup box. Ok let me try to describe the whole flow in points:-
Form has mutiple fields. For One field - number, I am showing the popup box.
I click a button on the popup box which sends me to the form. But I am not able to find those numbers in the form.
Final click is on the form button which sends all the information to the server side.
But I am not getting those value of numbers here on the form. So, Can any one suggest me the best way to resolve this issue?
Note: - I tried my best to put my question in a clear way. But If you guys could not find my words very clear, Sorry!
I'm not entirely sure I understand but I'll take a stab:
Option 1) Write all the values from the lightbox from back to the first form using $(selector).val();
Option 2) Copy the entire lightbox form into a hidden div inside the first form.
The popup box element is probably being added outside your form, so any input elements in the popup won't be submitted when you submit the form. To check this use a DOM Inspector (i.e. firebug in firefox or the dev tools in ie8 or chrome) to see where the element containing the lightbox is (it's usually at the end of the page).
To solve this you might be able to configure the lightbox to add it's div within the form, or else just use a bit of javascript to grab the value of the input element on the popup and populate a hidden input that's actually within the form before submitting.
Hi does this help
. It creates a popup there you can edit data then populate back into the main page which is referenced by opener just before closing the popup.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script type="text/javascript">
<!--
function fn() {
var popupwin = window.open("","","width=500,height=300");
popupwin.document.open();
popupwin.document.write("<html><head><script>function onOk(){opener.parent.document.getElementById('txtnumberfield').value=document.getElementById('txtpopup').value; window.close();}</script></head><body>Here are some popup values <input type='text' value='value from popup' name=txtpopup id=txtpopup />"+
"<input type=button onclick='onOk()' value='Done editing' /></body></html>");
popupwin.document.close();
}
//-->
</script>
<BODY>
<form action="#">
Number <input type="text" id="txtnumberfield" /> <input type="button" value="open popup" onclick="fn();" /><br/>
<input type="submit" />
</form>
</BODY>
</HTML>
If I understand your question correctly, one solution would be to set the control that closes your popup/lightbox to first populate some hidden fields on the underlying form. Grab the values from the form elements within the lightbox window:
$('#the_lightbox').find('.multiple_phone_fields')
.each( function(i,e){ // for each field
$('<input name=' + $(this).attr('name') + 'type="hidden"/>') // new, hidden
.val(this.value) // set hidden field value from this field
.appendTo('#the_main_form'); // and add to the underlying form
});
When you then submit #the_main_form, those hidden fields and values will come along. Obviously, you'll need to adjust the selectors for the specifics of your popup window or lightbox.
Related
I want to save the whole page in the background at certain intervals in order not to lose the existing form values in case of any problem (power outage etc.) for a project.
However, the html() method does not receive the values entered in the existing forms.
How can I output the entire page with the values entered in the forms?
Example
<html>
<body>
...
<form>
<input type="text" name="eq" value="XX">
</form>
...
</body>
</html>
I want to retain entered value in text box after navigation. I am explaining my code here.
**main.php**
<html>
<head></head>
<body>
<input type="text" id="myname" value="">
Next
</body>
</html>
**next.php**
Back
I don't want to use 'button' field here. On link navigation I want to retain the entered value in text box field. I am using php, html
you should save it in a cookie/session.
Or you can use localStorage too. Here's a link to read more
<form id="myform" name="myform" method="POST" action="next.php">
<input type="text" name="query" id="query">
Submit
</form>
<script type="text/javascript">
function submitform(){
// alert('form submit');
document.forms["myform"].submit();
} </script>
And in next.php
$_SESSION['last_search_term'] = $_REQUEST['query'];
echo $_SESSION['last_search_term'];
This will work . I have check it
I would use cookies. Note sessions and Opera back button do not work well together.
However if you want a cookieless solution you can use "window.name" string which is persistent i.e. its value is retained on navigation between pages. No need for a button as you required.
Just add this code before the closing </body> tag.
<script>
// on navigation to, or back: load users input from previous page (if any)
document.getElementById("myname").value = window.name;
// save value on navigation out
window.onbeforeunload = function() {
window.name = document.getElementById("myname").value;
return;
}
</script>
Assuming you give your text field the same id you can use the same js without modification on both/all pages.
The basic example code above should work with all modern browsers and most old browsers (even Opera since 2013). Modify it to use an event listener sanitize/check for empty values etc as required
Yes, I know that data sanitation and validation must be done server-side, but please stay with me.
Using the following script, stackoverflow.com will fail validation since a protocol is not given. If a URL is inputted without a protocol, I wish to add a default protocol (http://) to the input value prior to client-side validation. I don't wish to relax the validation method to silently accept URLs without a protocol as the user should be aware that a protocol was added.
How is this best accomplished?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var validator=$("#myForm").validate({
rules: {
url: {url:true,}
},
});
//Added per Monax's suggestion.
$('#url').blur(function(){this.value=this.value.substring(0,4)=='http'?this.value:(this.value?'http://'+this.value:'');});;
});
</script>
</head>
<body>
<form id="myForm" method="post">
<input name="url" id="url" value="">
<input type="submit" />
</form>
<?php echo('<pre>'.print_r($_POST,1).'</pre>');?>
</body>
</html>
You don't want to write a custom rule and you insist on manipulating the data before validation. Your options are limited since the plugin is automatically capturing all the validation triggering events. This is my suggested workaround.
Create two input fields...
one visible for the user (no validation)
one hidden for validation. (validation message presented though)
Upon entering any data into visible field, you would programmatically copy and modify the data as needed into the hidden field.
Then programmatically trigger validation on the hidden field.
Something like this.
HTML:
<input type="text" id="url" />
<input type="hidden" name="url" />
jQuery:
$('#url').on('blur keyup', function() {
var myurl = $(this).val(); // entered value
// manipulate and sanitize the value as desired
$('[name="url"]').val() = newvalue; // copy the new value into the hidden field.
$('[name="url"]').valid(); // trigger validation on the hidden field
});
NOTES:
You'll have to enable validation on hidden fields by properly setting the ignore option to something that allows it. [] will enable validation on all hidden fields.
You might have to use the errorPlacement option to tweak the placement of the error message for this hidden field. You can do this conditionally.
This problem is keeping me busy all week and I find little to nothing on the net ...
What I want to do is simple ... on my own website, create a server side PHP script that makes a login to another website with valid credentials and downloads a file that I want to process.
I use curl_init(), curl_setopt() and curl_exec() in trying to achieve that. It doesn't work.
So I stripped down that webpage to figure out what's wrong.
As you can see in the html code, the form's action event is the url to retrieve the file, when correct credentials are submitted.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<form name="form1" method="post" action="http://otherwebsite/login.aspx?ReturnUrl=/export_file.aspx?id=xxxxxxx" >
<script type="text/javascript" language="JavaScript">
function Submit_Form()
{
document.form1.Login$UserName.value="myname";
document.form1.Login$Password.value="mypassword";
//document.form1.Login$LoginButton.click();
document.form1.submit();
}
</script>
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input name="Login$LoginButton" type="submit" />
<br />Login
</form>
</body>
</html>
Now here is where it gets weird.
If I press the button, it works and I receive the download file.
If I click the hyperlink, i get a page saying to login properly.
When I uncomment the javascript line : click() it works too.
So it comes down to this :
Why does the button submit work and javascript submit doesn't work ?
Is there a way that the other website's server check how the form was posted ?
Thank you for your thoughts !
When you click the button, its name is included in the POST request because it's a named submit button. When you use the link, the button's name doesn't get passed in the POST data.
You could probably spoof the button when you use the link by having a hidden field with the name the button should have:
<input type="hidden" name="Login$UserName" value="myname" />
<input type="hidden" name="Login$Password" value="mypassword" />
<input type="hidden" name="Login$LoginButton" />
Note it doesn't need a value because the button it replaces doesn't have a value setting its text. Just including it should be sufficient.
Why not have another hidden field called js_submitted with a value of false, and in your Submit_Form() function, set it to true before firing the submit() method? Then, in PHP (for example), you could look for $_GET/$_POST['js_submitted'] to determine which submission method was used.
It's possible to check that the button was posted with the submit. Maybe they are checking for this.
Yes, it is very easy to find out when a button submits a form, and that is exactly what the site might be doing.
A button is a form control and so, when a form is submitted, the button state is submitted as well. What this means is, when you check the form object on the server that receives the post, you will see it contains a key with the same name as the button and it's value is set to the value attribute of your button.
Consider you have a form:
<form id="form1" action="abc.asp" method="post">
<input type="submit" name="btn" value="Opt123" />
<input type="submit" name="btn" value="Opt456" />
Send
</form>
I am not a PHP person, so code might not be the best:
$item = $_POST['btn'];
In this case, value of $item will be either Opt123 or Opt456 depending on the button pressed, whereas if the link is pressed, then it would be a null or PHP equivalent.
Even though the submit button is part of the form, the browser only sends its name=value pair as part of the post data if the button was actually clicked. When you call the .submit() method from Javascript, your browser sends the data Login$Username=myname&Login$Password=mypassword to the server. But when you actually click the button, it sends Login$Username=myname&Login$Password=mypassword&Login$LoginButton=. As you can see, it would then be very easy for the server to differentiate between the two.
So, you can trick the form into always sending that element by making it hidden. In Submit_Form, just before you say document.form1.submit();, add this:
var sbtn_hid = document.createElement('input');
sbtn_hid.type = 'hidden';
sbtn_hid.name = 'Login$LoginButton';
sbtn_hid.value = '';
document.form1.appendChild(sbtn_hid);
That adds a hidden form element with the same name as the submit button, so the server won't be able to tell the difference.
Why is it that a <form> with a single <input> field will reload the form when the user enters a value and presses the Enter, and it does not if there are 2 or more fields in the <form>?.
I wrote a simple page to test this oddity.
If you enter a value in the second form and press Enter, you'll see it reloads the page passing the entered value as if you called GET. why? and how do I avoid it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testFormEnter</title>
</head>
<body>
<form>
<input type="text" name="partid2" id="partid2" />
<input type="text" name="partdesc" id="partdesc" />
</form>
<p>2 field form works fine</p>
<form>
<input type="text" name="partid" id="partid" />
</form>
<p>One field form reloads page when you press the Enter key why</p>
</body>
</html>
This is a little known "Quirk" that has been out for a while. I know some people have resolved it in various ways.
The easiest bypass in my opinion is to simply have a second input that isn't displayed to the user. Granted not all that user friendly on the backend, it does work to resolve the issue.
I should note that the most common place that I hear of this issue is with IE specifically and not with FireFox or others. Although it does seem to affect them as well.
This is a known bug in IE6/7/8. It doesn't appear that you will get a fix for it.
The best workaround you can do for this, is to add another hidden field (if your engineering conscience permits). IE will no longer auto-submit a form when it finds that there are two input-type fields in the form.
Update
In case you were wondering why this is the case, this gem comes straight out of the HTML 2.0 specification (Section 8.2):
When there is only one single-line text input field in a form, the
user agent should accept Enter in that field as a request to submit
the form.
No, the default behaviour is that on enter, last input in the form is submitted.
If you don't want to submit at all you could add:
<form onsubmit="return false;">
Or in your input
<input ... onkeypress="return event.keyCode != 13;">
Of course there are more beautiful solutions but these are simpler without any library or framework.
Pressing Enter works differently depending on (a) how many fields there are and (b) how many submit buttons there are. It may do nothing, it may submit the form with no 'successful' submit button, or it may pretend the first submit button was clicked (even generating an onclick for it!) and submit with that button's value.
For example, if you add an input type="submit" to your two-field form, you'll notice it too submits.
This is an ancient browser quirk going back at least as far as early Netscape (maybe further), which is unlikely to be changed now.
<form>
Invalid without an ‘action’. If you don't intend to submit anywhere, and you don't need radio button name grouping, you could just completely omit the form element.
Here is the code that I used would use to solve the problem:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" name="StackOverflow1370021" value="Fix IE bug" style="{display:none}" />
</form>
It's not reloading the page as such, it's submitting the form.
However, in this example because you have no action attribute on the form it submits to itself which gives the impression of reloading the page.
Also, I can't repro the behaviour you describe. If I am in any text input in a form and I press Enter it submits the form, no matter where in the form the input is located or how many inputs there are.
You might want to try this out some more in different browsers.
as vineet already said, this is rooted in the html 2.0 specification:
here is how to prevent this from happening without screwing up your urls:
<form>
<input type="text" name="partid" id="partid" />
<input type="text" style="display: none;" />
</form>
Thanks to everyone who answered. It's an eye opener that a form with a single field acts differently then a form with many fields.
Another way to deal with this automatic submit, is to code a submit function that returns false.
In my case I had a button with an onclick event, so I moved the function call with the added return keyword to the onsubmit event. If the function called returns false the submit won't happen.
<form onsubmit="return ajaxMagic()">
<input type="text" name="partid" id="partid" />
<input type="submit" value="Find Part" />
</form
function ajaxMagic() {
...
return (false);
}
The solution I found for all of the browsers that I tested (IE, FF, Chrome, Safari, Opera) is that the first input type=submit element on the form has to be visible and has to be the first element in the form. I was able to use CSS placement to move the submit button to the bottom of the page and it did not affect the results!
<form id="form" action="/">
<input type="submit" value="ensures-the-enter-key-submits-the-form"
style="width:1px;height:1px;position:fixed;bottom:1px;"/>
<div id="header" class="header"></div>
<div id="feedbackMessages" class="feedbackPanel"></div>
...... lots of other input tags, etc...
</form>
This problem occurs in both IE and Chrome.
It does not occur on Firefox.
A simple solution would be to add the following attribute to the form tag:
onsubmit="return false"
That is, of course, assuming that you submit the form using an XMLHttpRequest object.
Yes, form with a single inputText field working as different in HTML 4.
onSubmit return false not working for me but the below fix bug is working fine
<!--Fix IE6/7/8 and HTML 4 bug -->
<input style="display:none;" type="text" name="StackOverflow1370021" value="Fix IE bug" />
I handled this by the following code but I am not sure if this a good approach.
By looking for input fields in a given form and if its 1 prevent the default action.
if($j("form#your-form input[type='text']").length == 1) {
$j(this).bind("keypress", function(event) {
if(event.which == 13) {
event.preventDefault();
}
});
}
I think that's a feature, which I did also disable it though. It's not taking big effort to disable it. Just capture the enter key, ignore it, will do.