I am using Ajax to submit forms in serial. I am trying to make the first s_referee_email + s_referee_fname pair required while the second or others not - there will be up to five of these pairs. I cant seem to figure how to make just the first pair required without breaking the form. I have tried using HTML5 and some answers from stack but havent been able to get anything to work. Any advice is greatly appreciated!
fiddle: https://jsfiddle.net/badsmell/gcrvqbna/
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!--serial submit ajax-->
<script>
function mySubmit(){
var myForms = $("form");
myForms.each(function(index) {
var form = myForms.eq(index);
var serializedForm = form.serialize();
serializedForm += '&s_referer_fname='+$('#s_refererFname').val();
$.post("http://post.aspx", serializedForm, function (data, status) {
if (status === "success"){
window.location.href= "http://redirect";
}
});
});
}
</script>
<title>Forward a copy to a friend</title>
<style type="text/css">
*[class=hide] {
display: none
}
</style>
</head>
<body>
<!--hidden iframe-->
<iframe class="hide" id="myIframe"></iframe>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" required >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" required >
</form>
<form method="post" action="post.aspx" target="myIFrame">
<input type="hidden" name="s_referer_email" value="test#test.com" />
<input type="text" size="30" maxlength="255" name="s_referee_email" value="" >
<input type="text" size="22" maxlength="50" name="s_referee_fname" value="" >
</form>
<label for="s_referer_fname">Your name:</label> <br /> <input type="text" name="s_referer_fname" value="" size="20" id="s_refererFname" ><br>
<p><button onclick="mySubmit();">Submit</button> </p>
</body>
</html>
Adding required="required" to the tags can let you make any field compulsory to be filled by user.
You should never use .onclick(), or similar attributes from a userscript.
Userscripts operate in a sandbox, and onclick operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener() (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="func()" id="button_id" ...>'
You would use:
something.outerHTML += '<input id="button_id" ...>'
document.getElementById ("button_id").addEventListener ("click", func, false);
And for your answer, one method is to perform a check before actually submitting the forms. Check if the required fields have been filled, if yes, go ahead and submit the form, or else don't submit and show an error message instead.
Related
I am trying to create something that when the script is run it reads the parameters that have been set in there.
For example loading a custom sidebar where the user can enter details or parameters to the run the script with. These parameters will remain until they are changed but shouldn't be required every time you run a script that uses these parameters.
A sort of like settings menu.
I have seen something similar in some addons that have been made can someone please point in right direction on how to go abouts doing this.
I already have the scripts running succesfully just need a UI where the parameters can be entered and set. I would like to avoid reading it from a sheet in the spreadsheet if possible.
Edit:
I see that there is a getscriptproperty available that is available to all users:
so far I have got update (2):
HTML:
function showside(){
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('body'))
}
function setProperty(objectForm){
PropertiesService.getScriptProperties().setProperties(
{a1: objectForm.a1 ,
a2: objectForm.a2,
p1: objectForm.p1,
p2: objectForm.p3})
return 'Updated'
}
<!DOCTYPE html>
<html>
<head>
<script>
function readProperty(){
var settings = PropertiesService.getScriptProperties(), keys = settings.getKeys()
Logger.log('running')
for (var i =0;i<keys.length;i++){
document.getElementbyID(keys[i].toUpperCase()).value = settings.getProperty(keys[i])
}
}
function handleFormSubmit(objectForm){
google.script.run.setProperty(update).setProperty(objectForm)
}
function update(update){
var div = document.getElementById('output');
div.innerHTML = 'Updated!';
}
</script>
<base target="_top">
</head>
<body onload="readProperty()">
<form id="myForm" onsubmit="handleFormSubmit(this)">
a1<input type="url" id="a1" value="" />
a2<input type="url" id="a2" value="" />
a3<input type="url" id="a3" value="" />
P1<input type="text" id="P1" value="" />
P2<input type="text" id="P2" value="" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
A rough approach; Improvise from here;
Read comments inside the loadScript();
document.getElementById("formWithData").onsubmit = loadScript();
function loadScript() {
// get data from submitted form
// this way script will re-run with data based on what u give in the form
}
<form id="formWithData">
<input type="text" placeholder ="enter condition 1">
<input type="text" placeholder ="enter condition 2">
<input type="text" placeholder ="enter condition 3">
</form>
I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
I am trying these days to do a search form that sends to two different pages with two different buttons with a single text box. So far I am doing this:
<form action="http://www.youtube.com/results" method="get">
<input name="search_query" type="text" maxlength="128" />
<input type="submit" value="YouTube" />
</form>
<form action="https://torrentz.eu/search" method="get">
<input name="q" type="text" maxlength="128" />
<input type="submit" value="TorrentZ" />
</form>
of course the result is this:
I can work with that, but I want to make it "cuter" like this:
So far I have tried using a script but I did not get it so I scraped it, then I tried making an if/elseif but yet again, I was not sure what I was doing, I am not a good planner for what I see, a toggle button or a dropbox is not as fast, as I just need to press tab once or twice and enter to just search where I want.
As an extra note, I am just making my personal "new tab" for chrome, as the basic and the ones I find in extensions are pretty heavy for my mini laptop.
In HTML5 you can use formaction attribute.
<!DOCTYPE html>
<html>
<body>
<form>
<input name="search_query" type="text" maxlength="128" />
<input type="submit" formaction="http://www.youtube.com/results" value="YouTube" />
<input type="submit" formaction="https://torrentz.eu/search" value="TorrentZ" />
</form>
</body>
</html>
Since you tried and failed a script, let's look at ways we can achieve this.
Using form
Be extremely wary of what you do here. It is easy to send a get request using form but it always "flushes" out the query strings already present in the action URL, and submits the request by adding name-value pairs in its child nodes. Make sure to create your query as a child node.
<input type="text" id="box" name="searchbox" maxlength="128" placeholder="Type text to be searched here" autofocus />
<input type="button" value="Youtube" onclick="search_youtube()"/>
<input type="button" value="Torrentz" onclick="search_torrentz()"/>
<script>
function search_youtube(){
var add="https://www.youtube.com/results";
var box = document.getElementById("box");
box.name="search_query"
if(box.value)
{
var form = open().document.createElement("form");
form.action=add;
form.appendChild(box.cloneNode(false))
form.submit();
}
}
function search_torrentz(){
var add="https://www.torrentz.com/search";
var box = document.getElementById("box");
box.name="q"
if(box.value)
{
var form = open().document.createElement("form");
form.action=add;
form.appendChild(box.cloneNode(false))
form.submit();
}
}
</script>
Using HTML5 formaction attribute
<form action="https://www.youtube.com/results" method="GET">
<input type="text" id="box" name="search_query" maxlength="128" placeholder="Type text to be searched here" autofocus />
<input type="submit" value="Torrentz" formaction="https://www.torrentz.com/search" onclick="document.getElementById('box').name='q'" />
<input type="submit" name="submit" value="Youtube" />
</form>
Aweber from data display javascript code something look like:
<script type="text/javascript">formData.display("name")</script>
<script type="text/javascript">formData.display("email")</script>
<script type="text/javascript">formData.display("phone")</script>
Now How can I use this in input filed value like:
<form method="post" action="">
<input name="name" type="text" value="<script type="text/javascript">formData.display("name")</script>">
<input name="email" type="text" value="<script type="text/javascript">formData.display("email")</script>">
<input name="phone" type="text" value="<script type="text/javascript">formData.display("phone")</script>">
<input type="submit" value="Go">
</form>
Reference: https://help.aweber.com/entries/21696333-How-Do-I-Display-Subscribers-Names-or-Email-Addresses-On-My-Thank-You-Page-
Please help me.
You can not simple place some code inside a value attribute hoping it will work, you need to appropriate JavaScript code to add the formData to the value attribute of the input field. You can do it with something like:
window.onload = function() {
document.getElementsByName('name')[0].value = formData.display("name");
document.getElementsByName('email')[0].value = formData.display("email");
document.getElementsByName('phone')[0].value = formData.display("phone");
}
I have a form that, when submitted, does not post the dynamically added hidden field.
html:
<div>
<form action="thankyou.php" onsubmit="return validate()" id="orderform" method="post">
<input type="text" name="name" /><br>
<input type="text" name="email" required /><br>
<input type="text" name="charterco" required /><br>
<input type="text" name="bname" /><br>
<input type="text" name="dtime" required /><br>
<input type="submit" />
</form>
</div>
jquery:
$('#orderform').submit(function(eventObj){
$('<input />').attr('type','hidden')
.attr('id','list')
.attr('name','shopList')
.attr('value',sliststr>)
.appendTo('#orderform');
return true;
});
POST data from Chrome DevTools:
name:b
email:b#b.com
charterco:b
bname:b
dtime:12:00
message:Comment
I can't work out what's gone wrong. My sliststr variable turns up filled and correct in my little debugging test on jsfiddle here. For whatever reason, it isn't POSTing.
EDIT: As #JayBlanchard pointed out below, I am adding to the form after the POST has been written.
Try to append the dynamic element, set the value of it and then submit the form. Otherwise it's submitting the form and then appending the html in callback.
Try the following.
function validate(){
var shoplist = [1,2,3];
$('#orderform').append("<input type='text' name='shop' id='list'>")
$('[name="shop"]').val(shoplist)
$('#orderform').submit(function(eventObj){
return true;
});
}