Error occurs when jQuery processing a form is inside another form - asp.net

I am writing a form using jQuery and encounter some difficulties.
My form works fine in static page (html).
However, when I use the form in dynamic page(aspx), the form does not behave correctly.
I cannot append items to the form and call the form.serialize function.
I think the error occurs when a form is inside another form (.aspx code needs to enclosed by a form tag).
What should I do?
Let me give a simplified version of my code:
<form name="Form1" method="post" id="Form1">
some content
<form name="form_inside">
<input name="fname" type="text" />
</form>
</form>
jQuery code:
$("#form_inside").append($("<input type='text' name='lname'>"));
When the user submits,
$("#form_inside").serialize();
// it should return fname=inputfname&lname=inputlname
I want to append element to "form_inside" and serialize the form "form_inside".
The form "Form1" is required by the aspx and I cannot remove it.

Could you just serialize the fields inside Form1?
I don't know anything about ASP, but it seems that you're not doing a straightforward "submit" anyway - so does it really matter if the fields aren't within their own separate form?
You could possibly group the fields you're interested in within a <div> or something, e.g.:
<div id="my-interesting-fields">
...
</div>
then substitute #form-inside with #my-interesting-fields where appropriate - is that helpful at all?
Edit
OK, a quick glance at the jQuery code suggests that serialize() depends on the form's elements member.
I suppose you could hack this in a couple of different ways:
Copy all elements from #my-interesting-fields into a temporary <form> that you dynamically create outside Form1, then call serialize() on that. Something like:
$("#Form1").after("<form id='tmp-form'></form>").
append("#my-interesting-fields input");
$("tmp-form").serialize();
Or, create an elements member on #my-interesting-fields, e.g.
$("#my-interesting-fields").elements = $("#my-interesting-fields input");
$("#my-interesting-fields").serialize();
I haven't tried either of these, but that might give you a couple of ideas. Not that I would necessarily recommend either of them :)

Because you can't have nested <form> tags you'll need to close off the standard dotnet form tag like below:
<script type="text/javascript">
$(document).ready(function() {
$("#form_inside").append($("<input type='text' name='lname'>"));
$("#submitBtn").click(function() {function() {
var obj = $("#form_inside *");
var values = new Array();
obj.each(function(i,obj1) {
if (obj1.name && !obj1.disabled && obj1.value) {
values.push(obj1);
};
});
alert(jQuery.param(values));
}); });
});
</script>
<form id="form1" runat="server">
<div>
<div id="form_inside" name="form_inside"> <input name="fname" type="text" /><input type="button" id="submitBtn" /></div>
</div>
</form>
jQuery.param on a array of form elements will give you the same results as .serialize()
so you get all elements in div $("#form_inside *) then filter for elements then on the result jQuery.param will give you exactly what you need

Related

form submit redirect to a new url with AMP-HTML

I have a simple problem yet it seems impossible to solve in AMP!!
I have a simple form with an input and a submit button like this:
<form id="myform">
<input type="text" id="srchInput"/>
<button type="submit">Submit</button>
</form>
All I want is to be able to concat a static url to the input value and redirect the page to the result, when the form is submitted.
For instance if the user inputs: "Hello" and submits the form, I would like to redirect him to a page like "MY/STATIC/URL/Hello".
Is there any way to achieve this in amp?
One way of doing this is by setting the AMP-Redirect-To header in the response (See AMP-form-redirection). Send the user input on form submission, and then generate your desired url from your API endpoint and set AMP-Redirect-To header in your response to the generated URL.
Another way of doing it would be by using navigateTo(url=STRING) action (See AMP Actions & Events) on for the form submit event. In this case you have to store the value in input to a state by using events like input-throttled, and then use url substitution in the navigateTo url string to append amp-state value.
The first method is guaranteed to work.
The second method should work in theory, but I was unable to figure out how to get AMP-STATE value by url substitution. The code for the same should be something like:
<form id="myform" on="submit:AMP.navigateTo(url="MY/STATIC/URL/AMP_STATE(endValue)>")">
<input type="text" id="srchInput" on="input-throttled:AMP.setState({ endValue : event.value })" />
<button type="submit"> Submit </button>
</form>
If you can figure out how to substitute amp-state value to the url this should work. Let me know if it helped.
The easiest way to do this is via a GET action:
<head>
...
<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
</head>
<body>
<form method="GET" action="MY/STATIC/URL" target="_top">
<input type="text" id="srchInput" name="srcInput" value="test">
<button type="submit">Submit</button>
</form>
</body>
The form submit will navigate to /MY/STATIC/URL?srcInput=test.

meteor template argument value differs between helper and event

I want to include a Blaze template with an argument and then use the argument value in an event. The problem is that when I include the template a second time with a different argument I get the argument value from the first instance of the template in events.
Template:
<template name="UploadFormLayoutImage">
<form class="uploadPanel">
<input type="file" name="fileupload" id="input-field">
<label for="input-field">Upload file</label>
</form>
</template>
Include:
{> UploadFormLayoutImage layoutArea="area1"}}
{> UploadFormLayoutImage layoutArea="area2"}}
js:
Template.UploadFormLayoutImage.onCreated(function(){
this.currentArea = new ReactiveVar;
this.currentArea.set(this.data.layoutArea);
});
Template.UploadFormLayoutImage.helpers({
layoutArea: function() {
return Template.instance().currentArea.get(); //Returns the correct argument value for each instance of the template.
}
});
Template.UploadFormLayoutImage.events({
'change input[type="file"]': function(e, instance) {
e.preventDefault();
console.log(instance.data.layoutArea); //Allways returns 'area1'
}
});
What am I missing here? (This is my first Stackoverflow question. Please be gentle :))
What if you change the instance.data.layoutArea in your events method to this.layoutArea?
In my effort to make the code example easy to read i stripped away the part that caused the problem. I'm using a label for the input field and therefore the input field has an id and thats of course not ok when repeating the template.
I now use the layoutArea-helper as an id value and every thing works just fine.
<template name="UploadFormLayoutImage">
<form class="uploadPanel">
<input type="file" name="fileupload" id="{{layoutArea}}">
<label for="{{layoutArea}}">Upload file</label>
</form>
</template>

How to pass values from one Contact Form 7 form to another in Wordpress?

I have a site that has 2 forms - a short form and a long form. If you look at http://dforbesinsuranceagency.com you'll see the short form next to the masthead photo. The long form is at http://dforbesinsuranceagency.com/request-free-insurance-quotes/
When the user hits Submit on the short form, it kicks them over to the long form page, so that part works fine. The part that gives me fits is that I need the values entered into the short form fields First Name, Last Name, Email Address and Telephone passed to their equivalent fields on the long form.
How do I do this?
This is how I am redirecting the short form to the long form (I added it to the Additional Settings section for the short form):
on_sent_ok: "location = 'http://dforbesinsuranceagency.com//request-free-insurance-quotes';"
Any help would be appreciated.
Hack, hack, hackety, hack hack hack... Without suggesting "not using a form-builder" I don't think there is an elegant solution - you can't use the other PHP method suggested without modifying the plugin itself (and that is a can of worms). I will propose a Javascript solution but there are some caveats (below):
jQuery(document).ready(function($){
$('#quick-quote form:first').submit(function(){
var foo = {};
$(this).find('input[type=text], select').each(function(){
foo[$(this).attr('name')] = $(this).val();
});
document.cookie = 'formData='+JSON.stringify(foo);
});
var ff = $('#container form:first');
if(ff.length){
var data = $.parseJSON(
document.cookie.match('(^|;) ?formData=([^;]*)(;|$)')[2]
);
if(data){
for(var name in data){
ff.find('input[name='+name+'], select[name='+name+']').val(data[name]);
}
}
}
});
What this will essentially do is: on submission, store your mini-form options in a cookie. On page load it will then look for a form in the main body of the page and apply any stored cookie data.
Notes
The jQuery selectors are deliberately ambiguous to avoid any future changes in your admin panel/plugin that will likely screw with the form IDs (thus breaking the script).
I'm not faffing about pairing field/option names - for example the select box in your mini-form is named insurance-type however the matching box in the main form is named ins-type - you will have to ensure they are of the same name.
This also applies to select box values - if there is no matching value, it will be ignored (eg. some of your values in the main form have » » characters in front (and so don't match).
try this.
set the action of our first form to a php file named xyz.php
<form method="post" action="xyz.php">
<input type="text" name="name">
<input type="text" name="email_address">
<input type="submit" value="Go To Step 2">
</form>
the file xyz.php will create a new form for you which in this case is your second form (the big one). Set the action of the form as required. the code of your xyz.php will look something like this.
<form method="post" action="form3.php">
<input type="text" name="name" value="<?php echo $_POST['name']; ?>">
<input type="text" name="email_address" value="<?php echo $_POST['email_address']; ?>">
<input type="radio" group="membership_type" value="Free">
<input type="radio" group="membership_type" value="Normal">
<input type="radio" group="membership_type" value="Deluxe">
<input type="checkbox" name="terms_and_conditions">
<input type="submit" value="Go To Step 3">
</form>
where the input fields of the first form will already be filled with the details given by the user in the first form.
You can create the first form by yourself and let the contact form create the second form for you providing the default values using the method above.
Hope this helps!

Using embedded standard HTML forms with ASP.NET

I have a standard aspx page with which I need to add another standard HTML form into and have it submit to another location (external site), however whenever I press the submit button the page seems to do a post back rather than using the sub-forms action url.
A mock up of what the form relationships is below. Note in the real deployment the form will be part of a content area of a master page layout, so the form needs to submit independantly from the master page form.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<form id="subscribe_form" method="post" action="https://someothersite.com" name="em_subscribe_form" >
<input type="text" id="field1" name="field1" />
<input id="submitsubform" type="submit" value="Submit" />
</form>
</div>
</form>
</body>
</html>
It's an interesting problem. Ideally you only want the 1 form tag on the page as other users have mentioned. Potentially you could post the data via javascript without having 2 form tags.
Example taken from here, modified for your needs. Not 100% sure if this will work for you but I think this is how you'll have to approach it.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function postdata()
{
var fieldValue = document.getElementById("field1").value;
postwith("http://someothersite.com",{field1:fieldValue});
}
function postwith (to,p) {
var myForm = document.createElement("form");
myForm.method="post" ;
myForm.action = to ;
for (var k in p) {
var myInput = document.createElement("input") ;
myInput.setAttribute("name", k) ;
myInput.setAttribute("value", p[k]);
myForm.appendChild(myInput) ;
}
document.body.appendChild(myForm) ;
myForm.submit() ;
document.body.removeChild(myForm) ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<input type="text" id="field1" name="field1" />
<asp:Button ID="btnSubmitSubscribe" runat="server" Text="Submit" OnClientClick="postdata(); return false;" />
</div>
</div>
</form>
</body>
</html>
If javascript is not a viable option - you can use .Net's HttpWebRequest object to create the post call in code behind. Would look something like this in the code behind (assuming your text field is an asp textbox:
private void OnSubscribeClick(object sender, System.EventArgs e)
{
string field1 = Field1.Text;
ASCIIEncoding encoding=new ASCIIEncoding();
string postData="field1="+field1 ;
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://someotherwebsite/");
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
}
If you add an ASP.NET button to the form, and set its PostBackUrl property to the external site, then all the form data will be posted to that URL.
There is a very nice tricky solution for this problem.
You can insert a </form> tag before your <form> to close the asp.net form which causes the problem. Do not forget to add a <form> tag after your html form. It may cause the editor to give you an exception, but do not worry, it will work.
Nested forms are not possible in HTML according to the W3C. You can achieve your intended result using JavaScript or with jQuery as explained by Peter on a blog called My Thoughts.
In my experience, Appetere Web Solutions has the best solution. Simple and elegant...and it's not a hack. Use the PostBackUrl.
I just tried it and everything works as expected. I didn't want to use Javascript because I didn't want to include it in my Master Page for every page that uses it.
I had the same situation as Ross - except that my input types were all of the "hidden" varitey.
Cowgod's answer got me thinking about nested forms within my .aspx page. I ended up "un-nesting" my 2nd form OUT of the main .aspx form ( ) and placed it (along with my js script tags) just under the body tag - but before the main .aspx form tag.
Suddenly, everything was submitting as it was supposed to. Is this a hack?
ASP.NET allows you to have multiple forms on one page, but only one can be runat=server. However I don't think you can nest forms at all.
You might have to make a new master page, one without a form tag on it so the form will work on that one page only. This is not a good solution, unless you can place the form outside the master pages' form, and use javascript to submit the second form, but that's hardly better. There really is no good solution for what you are trying to achieve, and if so I'd like to hear it. I don't think you can do a POST call from a code-behind, can you? I'm sure there's some way. But that's probably the only solution: from code.

Best way to implement Google Custom Search on an aspx page

Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).
You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags.
You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example:
<body>
<form action="http://www.google.com/cse" id="cse-search-box"> ... </form>
<form runat="server" id="aspNetform"> ... </form>
<body>
You may be able to have multiple form tags, but note that they cannot be nested. You'll run into all kinds of weirdness in that scenario (e.g., I've seen cases where the opening tag for the nested form apparently gets ignored and then its closing tag winds up closing the "parent" form out).
You'll need to remove the form tag and use javascript send the query. Have a look at
http://my6solutions.com/post/2009/04/19/Fixing-Google-Custom-Search-nested-form-tags-in-asp-net-pages.aspx
I have included the before and after code as well. So you can see what I've done to integrate it with blogengine .net.
You could use Javascript:
<input name="Query" type="text" class="searchField" id="Query" value="Search" size="15" onfocus="if(this.value == 'Search') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Search'; }" onkeydown="var event = event || window.event; var key = event.which || event.keyCode; if(key==13) window.open('http://www.google.com/search?q=' + getElementById('Query').value ); " /><input name="" type="button" class="searchButton" value="go" onclick="window.open('http://www.google.com/search?q=' + getElementById('Query').value );" />

Resources