How to trigger HTML5 validation error on button click - html

I have a form which done in 3 steps. In first 2 steps validation errors doesn't showing because they have no submit button. How I trigger errors here?

So here's piece of code that will do your job....
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<script>
$(document).ready(function(){ //do this only after the whole thing is loaded, use this for more complex error handles...
$('#form_').submit(function(data){ //this is triggered once you try to submit your data
var Nerror = 0; //we declare the number of errors
if($('#name_input').val()==''){ //here is where you handle errors, checking whether or not you
$('#name_input').addClass('has-error');
$('#name_input').val('');
Nerror++; //increment +1 to Nerror
alert('no name');
}
if($('#lname_input').val()==''){
$('#lname_input').addClass('has-error');
$('#lname_input').val('');
Nerror++;
alert('no last name');
}
if(Nerror>0){ //if Nerror is bigger then zero, we use the .preventDefault method to make sure the form is not submited
data.preventDefault();
}
});
});
</script>
<body>
<form id='form_' action='your_next_step.php' method='post'>
<input type='text' name='name' id='name_input' required> <!-- if you wish to make the inputs required, just put "required" inside the tags... -->
<input type='text' name='lastname' id='lname_input' required>
<button type='submit'>Next</button>
</form>
</body>
I hope you can do it now, if you have more complex handlers like checking your database for equal entries then you need to create a php file that makes that for you, then return the result in JSON or something....
Good luck.

Related

Goole App Script HTML Onclick Button Issue

I am working on a sidebar menu, and so far, I got it working to load values from a sheet. I am working on getting the sidebar to update the value that is selected and currently struggling a little bit since I can't seem to catch an error and struggling a bit to figure out how to error handle app scripts and HTML in app scripts. So the first ask here is can someone point me to a reference on how to error handle issues with HTML and Apps script.
My second issue my current problem, I have an HTML button that is calling onFormUpdate() function which is located inside a seperate HTML file just for handling javascript functions. Here is my index.html
<!DOCTYPE html>
<html>
<base target="_top">
<?!= include('sidebar/sidebarcss'); ?>
<body>
<div id="title">
<div><h2>Meeting Item</h2></div>
</div>
<div id="meet">
<form id="meetform">
Row ID: <br>
<input type="text" id="meetrowId" name="meetrowId" maxlength="4" size="4" readonly />
Meet ID: <br>
<input type="text" id="meetId" name="meetId" maxlength="8" size="10" readonly />
Enter Date: <br>
<input type="text" id="meetingDate" name="meetingDate"/>
Topic: <br>
<input type="text" id="meetTopic" name="meetTopic"/>
Agenda: <br>
<textarea name="meetAgenda" id="meetAgenda" rows="10" cols="30"></textarea>
Comment History:<br>
<textarea name="meetComments" id="meetComments" rows="10" cols="30" readonly ></textarea>
Add Comments:<br>
<textarea name="meetComUpdate" id="meetComUpdate" rows="10" cols="30"></textarea><br>
<input type="button" class="button" value="Update Record" onclick="onFormUpdate()"/>
</form>
</div>
<input type="button" class="button" value="Select Another ID" onclick="google.script.run.showEmailSidebar()"/>
<input type="button" class="button" value="Close" onclick="google.script.host.close()"/>
<?!= include('sidebar/script'); ?>
<script>
google.script.run.withSuccessHandler(onSuccess).SidebarActiveRow();
</script>
</body>
</html>
Within the form i call my onFormUpdate() and nothing happens when I click the button. As you can see i include 'sidebar/script' which is my html file that stores all javascript functions. OnFormUpdate() is located within the 'sidebar/script' and is shown below:
<script>
function onSuccess([cellrow, meetid, meetdate, meettopic, meetagenda, meetcomments])
{
/*
Secondary method for string parsing
const table =sidebarVar.split(",") //["key:value","key:value"]
.map(pair => pair.split(":")); //[["key","value"],["key","value"]]
const result = Object.fromEntries(table);
result.meetid;
*/
document.getElementById('meetrowId').value = cellrow
document.getElementById('meetId').value = meetid
document.getElementById('meetingDate').value = meetdate
document.getElementById('meetTopic').value = meettopic
document.getElementById('meetAgenda').value = meetagenda;
document.getElementById('meetComments').value = meetcomments;
}
function onFormUpdate()
{
var recordform =
{
row: document.getElementById('meetrowId').value,
topic: document.getElementById('meetTopic').value,
agenda: document.getElementById('meetAgenda').value,
newcomment: document.getElementById('meetComUpdate').value
};
google.script.run.withSuccessHandler(SidebarActiveRow).recordUpdate(recordform);
}
</script>
As you can see I am trying to get the app handler to call SidebarActiveRow which is leverage with my onSuccess function to load data elements from the sheet; this works fine. The handler is calling SidebarActiveRow to run after i successfully run recordUpdate() which is located in my code.gs file. So far nothing is happening. I have this current code for testing to see if the function works but no success.
function recordUpdate(recordform) {
SpreadsheetApp.getUi().alert(recordform.row);
}
I get no prompts which I can't seem to troubleshoot since the html and Apps Script function don't really show an errors. I did go to executions to see if there were any errors and i don't see any at this time. So i am looking for some help here.
Look at javascript Error Handling.
For HTML:
<script>
function someFunction() {
try {
// ... do some code
}
catch(err) {
alert(err);
}
}
</script>
For App Script
function someFunction() {
try {
// ... do some code
}
catch(err) {
Logger.log(err); // check execution log
}
}

I made the html & js code to do the validation check. But the data is submitted before checking the data

<form name="mForm" action="${pageContext.request.contextPath}/login/insertSeller.do" method="post">
id : <input type="text" name="id" />
<input type="submit" value="register" onClick="doAction()" />
</form>
<script>
function doAction() {
var f = document.mForm;
var id = f.id;
if (id.value == "") {
alert("insert your id");
id.focus();
return false;
}
return true;
}
</script>
Is there any error to correct?
If I click the button, the alert window opens with a message,
but the data is submitted without the validation check.
What do I need to do?
Please help me :)
You really shouldn’t have inline event handlers in modern HTML. Nevertheless, you could try the following:
<input … onclick="return doAction()">
The return in the onclick causes the input to wait for permission.
For the sake of completeness, here is how I would do it in a modern browser:
First, use a button instead:
<button type="submit">register</button>
Second, give your button a name
<button name="register" type="submit">register</button>
You can give a name to the older style input element, and the process will still work.
Next, add the following to your JavaScript:
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('button[name="register"]).onclick=doAction;
},false);
The main function acts as a startup script. The point of it is that it is waiting for the DOM to have loaded. Otherwise it’s not possible to look for elements that aren’t there yet.
Note that you assign to the onclick event handler the name of the function.

input tag (type=submit) not working as a link

I tried this html code
<input type="submit" value="Login" class="button" />
It is a part of my html form.
I want to use submit button to submit the data and show ( error.html ) page.
You will wrap it with <form action="error.html"></form>
You can use like this
<html>
<form action="error.html">
<input type="submit" value="Login" class="button"> </input>
</form>
</html>
I am a bit unsure of what you want to do, since you say you already have a form then I guess that the error.html is not calling to the form because you already have another link to the form already. Then this is could be a way to call on two pages almost at the same time. Submit first to the form and then after the sumbit it goes to the linked error page.
Working to call on BOTH the form html and the error.html link:
JavaScript:
<script language="JavaScript">
/** Delay me BEGIN **/
function DelayMyError(){
var count = 0;
// delay in milliseconds
var delay = 100;
var interval = setInterval(function(){
if (count++ < 1) {
window.location.href='error.html';
} else {
clearInterval(interval);
}
}, delay);
}
/** Delay me END **/
</script>
HTML:
<form action="YourFormPage.html">
<input type="button" onclick="form.submit();DelayMyError();" value="Login"></input>
</form>
I hope this was the answer you were searching for. Please contact me back if it worked, I am curious too. Theoretically speaking it should work that it first submits and then after 100 milliseconds it calls for the link called error.html.
How ever if you just want to do a link without a delay you could do it like this, but there is a risk that this more simple approach will not call on the form and that it will only work as a link skipping the submit:
OPTIONAL but I am unsure if this one will call on both the form html and the error.html or not:
<form action="YourFormPage.html">
<input type="button" onclick="form.submit();window.location.href='error.html';" value="Login"></input>
</form>

Making 'file' input element mandatory (required)

I want to make (an HTML) 'file' input element mandatory: something like
<input type='file' required = 'required' .../>
But it is not working.
I saw this WW3 manual which states 'required' attribute is new to HTML 5. But I am not using HTML 5 in the project I am working which doesn't support the new feature.
Any idea?
Thanks to HTML5, it is as easy as this:
<input type='file' required />
Example:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>
You can do it using Jquery like this:-
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadfile').val();
if(imgVal=='')
{
alert("empty input file");
return false;
}
});
});
</script>
<input type="file" name="image" id="uploadfile" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
As of now in 2017, I am able to do this-
<input type='file' required />
and when you submit the form, it asks for file.
You could create a polyfill that executes on the form submit. For example:
/* Attach the form event when jQuery loads. */
$(document).ready(function(e){
/* Handle any form's submit event. */
$("form").submit(function(e){
e.preventDefault(); /* Stop the form from submitting immediately. */
var continueInvoke = true; /* Variable used to avoid $(this) scope confusion with .each() function. */
/* Loop through each form element that has the required="" attribute. */
$("form input[required]").each(function(){
/* If the element has no value. */
if($(this).val() == ""){
continueInvoke = false; /* Set the variable to false, to indicate that the form should not be submited. */
}
});
/* Read the variable. Detect any items with no value. */
if(continueInvoke == true){
$(this).submit(); /* Submit the form. */
}
});
});
This script waits for the form to be submitted, then loops though each form element that has the required attribute has a value entered. If everything has a value, it submits the form.
An example element to be checked could be:
<input type="file" name="file_input" required="true" />
(You can remove the comments & minify this code when using it on your website)
var imgVal = $('[type=file]').val();
Similar to Vivek's suggestion, but now you have a more generic selector of the input file and you don't rely on specific ID or class.
See this demo.
Some times the input field is not bound with the form.
I might seem within the <form> and </form> tags but it is outside these tags.
You can try applying the form attribute to the input field to make sure it is related to your form.
<input type="file" name="" required="" form="YOUR-FORM-ID-HERE" />
I hope it helps.
All statements above are entirely correct. However, it is possible for a malicious user to send a POST request without using your form in order to generate errors. Thus, HTML and JS, while offering a user-friendly approach, will not prevent these sorts of attacks. To do so, make sure that your server double checks request data to make sure nothing is empty.
https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/
<button onclick="myFunction()">Try it</button>
<p id="geeks"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("gfg");
if (!inpObj.checkValidity()) {
document.getElementById("geeks")
.innerHTML = inpObj.validationMessage;
} else {
document.getElementById("geeks")
.innerHTML = "Input is ALL RIGHT";
}
}
</script>

show JSON in new window

I have a problem with json. I'd like to display the result of my form in the new browser window in JSON. (When user fills all fields in the form, button becomes enabled and shows JSON in specified format (I did it)). I translated it in JSON but dunno how to output it...I'm thinking of create new html page and do window.open on button on 1st page, but then it doesn't read data from 1st page which user entered. Or should I save it somehow in JSON file and then read it from other page?
For example:
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button type="submit" id="btn" class="btn" disabled="disabled">Submit</button>
</form>
I have some form with date field and button:
I can easily get JSON of date field by {{date | json}} on the same page, but I just want to output it in new browser window. How can I do this? Please help me with some tips. Thanks.
If it's not too big you can send the information to the new window as a data URL.
The frame will be reused once it is open.
This might be a start, showing how to plug in the JSON data and break it up over multiple lines for display.
window.open('data:application/json,'
+JSON.stringify(location).replace(/([[{,])/g, "$1%0a"),
'jsonFrame',
'resizeable,top=100, left=100, height=200, width=300,status=1')
See MDN for all the details.
You should be able to get at the window.opener from the new window and parse values out of it. The following plunker shows storing data from the current scope in an accessible area when the controller's submit is clicked. From the new window it then parses the content from the opener into the window's scope for further processing.
http://plnkr.co/edit/OkKX5zxYVSoZ7w81WV8J?p=preview
You'll notice here too how to get an angular friendly way of calling the submission and the disabling of the button until ready.
Hope this helps.
How about to save your input data into a cookie on one page and then get it via JavaScript when you will open a new window?
I could prepare the code in jsFiddle, but seems like it does not import external resources at this moment. So I'll post it here:
page 1:
...
<form name="form" ng-controller="MyCtrl">
<label> <b> * Date: </b> </label> <input id="date" type="datetime-local" ng-model="date" name="date" onkeyup="changeButtonStatus()" onchange="changeButtonStatus()" required> </input>
<button id="btn" class="btn" >Submit</button>
</form>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#btn').click( function() {
var cookie_value = $('#inut_test').val();
/*cookie_value should be your json string*/
$.cookie("json_cookie", cookie_value, { path: '/' });
window.open("http://localhost/page2");
return false;
});
</script>
...
page 2:
...
<a id="see-cookie" href="#">
click me!!!
</a>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
$('#see-cookie').live('click', function() {
alert($.cookie('json_cookie'));
return false;
});
</script>
...
Do not forget about { path: '/' } cookie property to set it for all site and about including jQuery cookie library into your page.