I'm new with JavaScript. Can someone give me an example how to delete an empty form element upon submit?
<form action='...' method='post' id='mySubmitForm'>
<input type='text' name='name'>
<input type='text' name='email'>
<input type='text' name='phoneNumber'>
<input type='submit' value='Save'>
</form>
Is there a easy way to check with JavaScript if the form is empty and delete it before submission if so?
There is a submit event that the browser throws before form submission that you can use.
reference: http://www.quirksmode.org/js/forms.html
Return false if you don't want the form to be submitted, true if you want it to happen. In the event, delete / add the extra inputs that you want accordingly.
function validate(formName)
{
var form = document.forms[formName];
//validate, and do stuff
//remove items that you want with a call like this
form.removeChild(document.getElementById(id));
form.submit();
}
If this is for validation, you should really be doing validation server side, not client side.
You would call this function like so:
<input type=BUTTON onClick="validate('myForm')"/>
You can use jQuery, which is probably the easiest way.
$(document).ready(function() {
$('#.mySubmitForm').submit(function(event) {
event.preventDefault();
$('input[type=text]').each(function() {
var inputElement = $(this);
inputElement.val() == "" ? inputElement.remove() : null;
});
$(this).trigger('submit');
});
});
I didn't test that code, but it should delete the empty form values before submit, then remove them.
function onsubmit() {
[].forEach.call(document.querySelectorAll('#mySubmitForm input[type=text]'), function(col) {
if(col.value=='') col.disabled = 'disabled';
});
}
and onsubmit="onsubmit()" in your <form> tag
Checking through javaScript is easy, but I'd advise you to have-and-assign an id attribute to your form elements
You can check in the following way,
var email = document.getElementById('email').value;
and you can remove email from your form as shown below
form.removeChild(document.getElementById('email'));
form.submit();
you can have a look at Adding and Removing HTML elements dynamically with Javascript for more details.
Related
I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>
I am trying to capture the value of a submit button so I can submit the form based on this button being used. The form name incidentform and the button name is updateincidentButton. Below is the code.
$(function(){
$$("#incidentform").submit(function(e){
var =$("#updateincidentButton").val();
if(var==="Update incident"){
alert(var);
e.preventDefault();
}
})
})
Here is the basic html of the form
<form id="incidentform" action="/" method="get">
<input type="submit" class="button" id="updateincidentButton" name="updateincidentButton" value="Update Incident"/>
</form>
var is a reserved keyword in javascript. You can't use it as the name of a variable.
Change this:
var =$("#updateincidentButton").val();
to something like this:
var var1 = $("#updateincidentButton").val();
First off, you don't need two "$$".
Is the name "updateincidentButton" or the id? If it is currently the name, change it to the id:
<button id="incidentform">Click Me</button>
Same thing with the form. The hashtag that is passed into $ represents an id of an element.
First, you have to define your form somewhere...give it an ID:
<form id="aspnetForm">
....
<input type="button" id="updateincidentButton" value="Update incident"/>
</form>
Next, change your JavaScript:
$("#updateincidentButton").click(function(e){
if ($(this).val() == "Update incident"){
$("aspnetForm").submit();
}
e.preventDefault();
return false;
});
Make sure the type of the button is 'button'.
$(document).on('click', '#updateincidentButton', function () {
var value = $('#updateincidentButton').val();
if (value == 'Update incident') {
alert(value);
}
});
Then you won't even have to prevent default. Then submit form using AJAX. Posting to a URL dependent on the value of the button when clicked.
This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.
I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});
I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';