JavaScript function which can validate multiple forms on a webpage - javascript

Apologies if this is a straightforward question, as I am still very new to JavaScript. I have a script that validates user inputs by checking if the text-field is empty. If it is not empty, then a confirmation window prompts the user to make sure they want to continue before the form is submitted and the information uploaded.
I would like to know how I can use the code below or similar code to validate multiple forms on the same page, as currently I can only get it to work with one single form? I have tried various solutions, non of which have yet been successful. I have even tried copy/pasting the entire script and changing the relevant elements inside it.
I've stripped my alterations to the code back to where it actually works correctly. Like I said, once I try to re-use it to validate multiple forms, the code stops working correctly.
// Set up event handlers in JavaScript
document.querySelector('form').addEventListener('submit', validationCheck);
document.getElementById('updateEventTitle').addEventListener('keyup', validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
if (eventTitle.value === '') {
btnUpdate.disabled = true;
} else {
btnUpdate.disabled = false;
//Confirmation window
if (event.type === 'submit') {
//Confirmation window
var r = confirm('Do you want to update this item?');
if (r == true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
I would like a script that is able to validate any HTML form on the page, not just the first one.
Many thanks.

We simply can took all the forms, loop through, get inputs and buttons we need for every form and set up listeners for every form, for every element.
Below is a code snippet explaining how it can be done.
// getting all forms
const elForms = [...document.querySelectorAll('form')];
// looping an array
elForms.map(elForm => {
// Get your DOM references just once, not every time the function runs
const elInput = elForm.querySelector(`input[type='text']`);
const elButton = elForm.querySelector(`input[type='submit']`);
// Set up event handlers in JavaScript
elForm.addEventListener('submit', (event) => validationCheck(event, elInput, elButton)); // passing parameters
elInput.addEventListener('keyup', (event) => validationCheck(event, elInput, elButton)); // passing parameters
});
function validationCheck(event, elInput, elButton) {
if(elInput.value==='') {
elButton.disabled = true;
} else {
elButton.disabled = false;
//Confirmation window
if(event.type === 'submit'){
//Confirmation window
var r =confirm('Do you want to update this item?');
if (r==true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTime'>
<input type='text' id='updateEventTime' name='myUpdateEventTime' size='15' maxlength='5' placeholder=$eventTime required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTime' value='Update' id='updateBtn' disabled>
</form>
After answer
There are duplicating id in your example
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle'
This is not valid and can cause problems in future. id should be unique.

Related

Send form inside a while with java, ajax php

I have the following html code with a form
<form id="msg-form-nota">
<input type="hidden" name="id_nota" id="id_nota" value="${project.id}">
<label for="textfield">Calificación obtenida:</label>
<input type="text" name="nota" id="nota" class="form-control form-control-sm" value="${project.nota}" placeholder="Introducir calificación"><br>
<input type="submit" name="submit" id="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
and then I use the following javascript/ajax code to manage the form
$('#msg-form-nota').submit(e => {
e.preventDefault();
const postData = {
nota: $('#nota').val(),
id: $('#id_nota').val()
};
const url ='accion.php';
$.post(url, postData, (response) => {
toastr.success('añadidas!', 'Actualización ', {"hideDuration": 1500});
});
});
The problem that I detect and I don't know how to solve is that, for example, when using a while, 5 forms are created with the same name id, if I use the first form that loads me it works without problem, but if I use the rest, the form does not It works if not that all the content of the form goes to the url as if the method were a get, what can I do? Thank you
If you wanted to completely remove the ID attributes from your forms/elements you can quite easily simplify the entire code by using a FormData object with a reference to the form supplied as the single argument. The FormData object would collate the various input elements for use in the ajax request - thus negating the need to even try to identify the individual input elements explicitly.
document.querySelectorAll('[type="submit"]').forEach(input => input.addEventListener('click',e=>{
e.preventDefault();
/*
The `submit` button raised the event so the `event.target` refers to that button.
From the button we know the `form` is the parentNode - but you can use `closest`
to find the parent form.
*/
let fd = new FormData( e.target.parentNode );
fetch( 'accion.php', { method:'post', body:fd })
.then(r=>r.text())
.then(data=>{
console.log(data);
// call your success function.
toastr.success('añadidas!', 'Actualización ', {
"hideDuration": 1500
});
});
}))
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='123' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Geronimo' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='456' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Fred Flintsone' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='789' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Spitfire' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
In the PHP script accion.php there will be 2 POST parameters sent by the fetch request. These two parameters have the same names as the form input elements. For instance:-
<?php
#accion.php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['id_nota'],
$_POST['nota']
)){
// ... etc do whatever
}
?>
The issue, as your question implies, is because you're repeating the same id attribute multiple times as the HTML is generated in a loop.
The best way to fix this is to use common class attributes on the elements instead. Then you can target the specific instance which from the target property of the event which is raised and passed as an argument to the event handler function. You can also use DOM traversal methods to find the related elements and retrieve their values.
Also note that I wrapped the input within the label element. This removes the need for the for and id attributes on those elements, but retains the same functionality.
$('.msg-form-nota').on('submit', e => {
e.preventDefault();
let $form = $(e.target);
const postData = {
nota: $form.find('.nota').val(),
id: $form.find('.id_nota').val()
};
console.log(postData);
/* make your AJAX request here... */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_001">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_001" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_002">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_002" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_003">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_003" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>

disable button after form submission using plain javascript

Greeting developers, I search in all previous question from stackoverflow. There is no proper answer for this.I create two buttons inside form.One is addfriend and another one is unfriend which is disable. If the user click add , it direct to prompt box.After click ok for that,the unfriend button will able to click. Now my problem is it can submit my form but button is not work as expected until user logout. In all tutorial they show how to disable button only. Whenever i try, it work but not submit my form.I want my form submit and button disable until the user logout.Thanks in advance.
<script>
function myFunction(form){
var subject = prompt("Please enter Subject that want to study");
var btn = document.getElementById("btn");
var add = document.getElementById("add");
btn.disabled=false;
add.disabled=true;
if (subject == null){
form['subject'].value= subject;
add.value="request sent";
form.submit();
return false;
}
else if(subject != null) {
form['subject'].value= subject;
add.value="request sent";
btn.disabled=false;
add.disabled=true;
form.submit();
return true;
}
}
function unfriend(form){
var btn = document.getElementById("btn");
var add = document.getElementById("add");
add.disabled=false;
btn.disabled=true;
add.value="request sent";
return true;
}
</script>
<form method="post" id="form" enctype="multipart/form-data" autocomplete="off" >
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="hidden" id="subject" name="subject" data-uid=<?php echo $_SESSION['sid'] ;?>/>
<td>
<input type="submit" onclick="return myFunction(form)"name="addfriend" data-type='addfriend' id="add" class="btn" value="add" />
</form>
<form>
<input type="submit" value="unfriend" id="btn" onclick="unfriend(form);" disabled="" />
</td>
</form>
I am not an expert in javaScript but seem to understand the problem.
Two possible scenarios are:
1 - if you have input type="submit" then it will submit the form but your javascript method will not be invoked because after submitting the form you will be redirected to some web page either the same page or different page and so it is a new get request all together.
2 - If you have type="button" then it will not submit the form but your javascript method will be invoked as you will remain on the same web page.
check this for difference : Difference between <input type='button' /> and <input type='submit' />
Solution:
Keep input type=button and do an ajax call to the post method and in the success of the ajax call, enable/disable your add and unfriend buttons.
Don't have the code handy so unable to share code.
Hope it helps.

Required attribute not working using javascript submit

I make some form different action within different button
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add');?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print');?>')">Print</button>
Javascript
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
}
Then, my required attribute not working. Did I do something wrong? Let me know if there is other solution.
Thanks,
I can't give you a good explanation but you need the submit buttons inside the form.
So if you would have a button like:
<input type="submit" value="Submit">,
it will trigger the required attribute.
#Remn If you would still stay on your structure with submit inside a function you could trigger yourself the validation like:
if ($("form")[0].checkValidity())
{
$("form").submit()
}
and then do something with inputs that are invalid by passing through each required element ( input is set in code ):
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
In the below case the invalid inputs will be focused one by one.
The whole code is:
$( function () {
$("body").on("click", "#trigger", function() {
if ($("form")[0].checkValidity())
{
$("form").submit()
}
$('form :input[required="required"]').each(function()
{
if(!this.validity.valid)
{
$(this).focus();
// break
return false;
}
});
});
});
Where #trigger is an id I set on the button to submit, you can make your own functions to achieve your goal I just used on().
I hope it helps!
Please try bellow code. i hope solve your problem.
<html>
<head>
<title>Submit</title>
<script type="text/javascript" language="javascript">
function submitForm(action)
{
document.getElementById('form').action = action;
document.getElementById('form').submit(
);
//alert(document.getElementById('form').action);
}
</script>
</head>
<body>
<form id="form" method="get" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required="required">
<button type="submit" class="btn btn-primary" onclick="return submitForm('<?php echo base_url('order/add');?>');" id="submit">Submit</button>
<button type="submit" class="btn btn-warning" onclick="return submitForm('<?php echo base_url('order/print');?>');" id="print">Print</button>
</form>
</body>
</html>
I have test your code by adding Javascript part in Script tag it is working fine. And i tested it on Chrome Windows 10.
<form id="form" method="post" class="form-horizontal" enctype="multipart/form-data">
<input name="name" class="form-control" type="text" required>
</form>
<button type="button" class="btn btn-primary" onClick="submitForm('<?php echo base_url('order/add'); ?>')">Submit</button>
<button type="button" class="btn btn-warning" onClick="submitForm('<?php echo base_url('order/print'); ?>')">Print</button>
<script>
function submitForm(action) {
document.getElementById('form').action = action;
document.getElementById('form').submit();
}
</script>
Using javascript's form.submit() function will cause input validation to be bypassed (according to the HTML specification in point 4 of the form submission algorithm). The only way to trigger HTML input validation is to use a click event on a submit button inside the form, either by the user actually clicking, or in javascript with something like form.querySelector('input[type="submit"]').click().

Storing value in var from form submission with jQuery

I have looked at many answers and none seem to fit the issue. I have a simple search box and submit button, and want to store the value of the input field in a variable. It seems to store at first, then disappears. Code:
JavaScript
$(document).ready(function(){
$('form').submit(function(){
var input = $('#search').val();
$('p').append(input);
});
});
HTML
<form>
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>
The variable will display for a second and disappear, presumably when the search box becomes empty again.
The reason this happens is because when you submit a form the browser will send a new HTTP request to the server and reload your page. You could prevent this behavior by returning false from the submit handler:
$('form').submit(function() {
var input = $('#search').val();
$('p').append(input);
return false;
});
or alternatively:
$('form').submit(function(e) {
e.preventDefault();
var input = $('#search').val();
$('p').append(input);
});
This will prevent the page from reloading and the changes you did to the DOM will remain.
$(document).ready(function(){
$('form').submit(function(){
var input = $('#search').val();
$('p').append(input);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>
For getting result you can do something like this
In HTML code
<form action="" method="get" id="search_form">
<input id='search' class='form-control' type='text' name='search'>
<input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
</form>
<p></p>
<div id="search_result"></div>
in Javascript code
$('#search_form').submit(function(){
var input = $('#search').val();
$('p').text(input);
$("#search_result").load($(this).attr("action")+ " #search_result", function(){
alert("result loaded for "+ input)
})
return false;
});

How I can POST a Button value in PHP

I have a form in which i use multiple Checkbox. On Checkboxes i use JavaScript for validation If I checked all checkbox, it proceeds ahead otherwise it show an alert message.
My code is working Well
Problem
Because i have Two Button on my form and they have different functionality. I want to post value of Button on my action page
My Code goes here
<script>
function letter_submit(){
var pr = document.getElementsByName('pr'),
i = 0;
var allAreChecked = true;
for( ; i < pr.length; i++ )
{
if( pr[i].checked=='' ) {
allAreChecked = false;
}
}
if (!allAreChecked) {
alert("Please Check All Checkboxes");
exit;
} else {
alert("All OK");
document.getElementById("approve_letter").submit();
}
}
</script>
<form action="letter_approve_action.php" id="approve_letter" name = "approve_letter" method="POST" >
<input type="checkbox" name="pr" id="pr" value="" /> NL is appropriately addressed.
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Checked Press Release
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Applicable Methodology is rightly Marked
</br>
<input type="checkbox" name="pr" id="pr" value="" /> Respective Sector Study on Website is Updated Within Last 12 Months.
</br>
<button type="button" name="btn_submit" id="btn_submit" value="Approve" onclick="letter_submit();">Approve</button>
<button type="button" name="btn_submit" id="btn_submit" value="Re - Submit" />Re-Submit</button>
</form>
On action page i use
echo $submit = $_POST ['btn_submit'];
and i got an error
Notice: Undefined index: btn_submit in C:\xampp\htdocs\Work_Que_Backup\login\pacra-all\w_q\nl\letter_approve_action.php on line 26
You may use <button> tag.
For example:
<form method="post">
<input type="text" name="myText" value="some text here..."/>
<button type="submit" name="myButton" value="buttonValue">Submit</button>
</form>
The label tht is displayed is "Submit" but you can access your button value from the server with a different value.
It will be accessible with php on server side as:
echo $_POST['myButton']; //buttonValue
The problem in your code is that your button is of type "button", and you trigger the POST by javascript - so the value for btn_submit is never set.
Change the button type to "submit" and move the event handler onclick=... to the form tag onsubmit=.... In your javascript function, you can the cancel the submit by returning false.

Categories