How to load multiple pages of PHP in same division - javascript

I have three PHP pages. In first file, there are two divisions, of which, one division contains a list of hyperlinked URLs and second division loads the output of clicked hyperlinked URL. Below is the snippet for first file:
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
});
</script>
<div id="content"> Sidebar <p> </p>
<div class="form">
<pre>
<a href=sample_form1.php><b>Psychotic Drug</b></a><p>
<a href=sample_form2.php><b>Antibiotic</b></a><p>
<a href=sample_form3.php><b>Pain killer</b></a><p>
<a href=sample_form4.php><b>Anti viral</b></a><p>
</pre>
</div>
In second file, I have form which is getting opened in first file's second division. Below is the code snippet for second file:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
//var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
alert(" " + y[k].value);
return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
</script>
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
Drug name: <input type="text" name="dname"></pre>
<pre>
<input type="checkbox" name="drug" value="ID">DRUG-ID <input type="checkbox" name="drug" value="Tree">Drug Tree</br>
<input type="checkbox" name="drug" value="Node">Node <input type="checkbox" name="drug" value="patent">Patent</br></br>
<input type="submit" value="Submit">
</pre>
</form>
I want to load this file in the first file's second division and that is happening as desired. But whenever I am trying to submit the input, form remains unresponsive. i.e. form entry is not being accepted and onclick function is not working. Please guide me in this regard how can I load multiple PHP/HTML files in one division.

I guess the inline js in your form isn't evaluated by jQuery's ajax function (for which $.load is just a shortcut).
You could try moving that section no the main file, which would read:
<script>
$(document).ready(function() {
$('a').each(function(){
$(this).on("click",function(e) {
console.log(e);
e.preventDefault();
$('#sidebar').load($(this).attr('href'));
});
$(document).on('submit','form[name=drugForm]',function() {
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for(k=0;k<y.length;k++) {
if(y[k].checked) {
alert(" " + y[k].value);
return true;
}
}
alert("Check one checkbox at least");
return false;
});
});
</script>
Still, it seems to me this is an ugly way to deal with the whole structure. There's some heavy refactoring on its way.

Related

How can I make a pop up window (alertbox) if the input isn't valid? [duplicate]

This question already has answers here:
A simple jQuery form validation script [closed]
(2 answers)
Closed 5 years ago.
Basically what i'm trying to do is that when i hit a button, it will check if something has been written, if it hasn't I would like an alert box to appear. Is this possible? Down below is what I have so far, any tips? (#inputvalue is the id of the values when writing. I created a new function for the process called validateForm. Is this possible to do in Jquery? I supose that what I wrote is more Javascript, because that's mostly what i'm used to...). //Nathalie!
function validateForm() {
var x = document.forms["#inputValue"].value;
if ("#inputValue" == "") {
alert("Name must be filled out");
return false;
}
}
Provided that you use jQuery (as you have tagged your question) you could try something like this:
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
$(function(){
function validateForm(){
var ele = $("#inputValue");
if(!ele.val()){
alert("Name must be filled out")
}
}
$("#btnId").on("click", validateForm);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputValue"/>
<input type="button" id="btnId" value="submit"/>
Sure, using the code you provided, you just need to target #inputValue properly and use that value in your test.
function validateForm() {
var x = document.getElementById('inputValue').value;
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
}
<form onsubmit="validateForm()">
<input id="inputValue" type="text">
<input type="submit">
</form>
Using jquery, it's basically the same thing. Here's an example using a submit handler in jquery instead of an onsubmit attribute in html, and using jquery selectors.
$('form').on('submit',function(e) {
var x = $('#inputValue').val();
if (x.trim() == "") {
alert("Name must be filled out");
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="inputValue" type="text">
<input type="submit">
</form>
In addition to what Michael Coker said, it would be better if you attach an event listener by script to the form tag:
document.addEventListener("DOMContentLoaded", function() {
document.getElementsByName("form")[0].addEventListener("submit", function() {
var value = document.getElementById("inputValue").value;
if (value == "")
{
window.alert("Name must be filled out!");
}
});
});
Here is a solution using jQuery. Unlike some of the answers above, I did not use a form.
//Listen for the click of the button
$(document).on("click", "#enterButton", function(e) {
//Get the value of the input box
var F_Name = $('[name="FirstNameInput"]').val();
//If it is empty, alert.
if (!F_Name.trim()) {
alert('Empty');
}else{
//DO SOMETHING WITH THE INPUT, AJAX?
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="FirstNameInput">
<button type="button" id='enterButton'>Enter</button>

multiple function not working for onsubmit

My form is validating the two java functions script and if both are true it will continue the form submit. But when i submit it validates only first function validateFormROLLNO() not the second function. Also, when the first function fails it submits the form anyway. I want to submit the form only when the two functions are passed.
first function will check if the roll no = 12 characters.
second function checks if the name is not null.
<body>
<center>
<script type="text/javascript">
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x !=12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validateFormNAME() {
var p = document.forms["myForm"]["student"].value;
if (p =='') {
alert("Name cannot be NULL!!!!");
return false;
}
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}
function validate(){
return validateFormROLLNO() && validateFormNAME();
}
</script>
<br> <FORM name="myForm" ACTION="insert.jsp" onsubmit="return validate()" METHOD="POST">
Please enter the Rollno and Name you want to INSERT:
<BR> <br>
<b>ISIN :<INPUT TYPE="TEXT" NAME="id"></b>
<BR><BR>
<b> SOURCE :<INPUT TYPE="TEXT" NAME="student"></b>
<br><BR>
<INPUT TYPE="SUBMIT" value="Submit">
</FORM>
</center>
</body>
</html>
There might be some javascript errors exists on the page, that don't let second function to execute. Please use browser's inspect element to explore it.
document.forms["myForm"]["id"].value you are are checking value of the textbox. Please document.forms["myForm"]["id"].value.length to validate it.
Here is the complete method.
function validateFormROLLNO() {
var x = document.forms["myForm"]["id"].value;
if (x.length <12) {
alert("ROLLNO must be 12 characters long!!!!");
return false;
}
else
return true;
document.forms["myForm"]["submit"].disabled = true;
document.forms["myForm"]["submit"].value="Wait..";
}

HTML <input> Required Attribute Fails to Prevent Form from Submitting in Apps Script App

I'm testing some code I wrote in Google Apps Script. I've required my fields to have text, but when I test it with null fields, the sever side code is run anyway. The code fires the pop-up stating that fields are required, but submits the form when clicking "OK" on the pop-up. I've tested it where I've filled out all the fields and then submitted which uploads perfectly. I think I just have my coding backwards or something in my "onclick". I have a basic knowledge of coding so I'm sorry if this is a dumb question. Thank you, thank you, thank you in advance.
<p>
<form id="myForm">
<h1>NHD Paper Upload</h1>
<label>Name</label>
<input type="text" name="myName" class="required" placeholder="Enter your full name..">
<label>Division</label>
<input type="text" name="myDivision" class="required" placeholder="(ex. Junior or Senior)">
<label>School</label>
<input type="text" name="mySchool" class="required" placeholder="Enter your school..">
<label>Affiliate</label>
<input type="text" name="myAffiliate" class="required" placeholder="Enter your affiliate..">
<label>Select file to upload. Make sure your file is labeled in the following manner <b>LastName_Division_School_State.pdf</b></label>
<input type="file" name="myFile">
<input type="submit" value="Submit File"
onclick="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
<br />
<label><b>Once upload is successful please stay on this window to copy and paste the URL produced on the next screen into registration.</b></label>
<br />
<label><b>If you have any issues or questions please send an email to elaine#nhd.org.</b></label>
</form>
</p>
<div id="output"></div>
<script>
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
}
}
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 15px; }
p {margin-left:20px;}
</style>
and here is the javascript
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var dropbox = "NHD Papers";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName + ", Division: " + form.myDivision + ", School: " + form.mySchool + ", State: " + form.myState);
return "<h2>File uploaded successfully!</h2><p>Copy and paste the following URL into registration:<br /><br /><strong>" + file.getUrl() + '</strong></p>';
} catch (error) {
return error.toString();
}
}
Right now, google.script.run is being called directly from the submit button.
Current set up:
<input type="submit" value="Submit File"
onclick="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
If you want to prevent google.script.run from being run when a required input field is not filled in, I'd try running the submit event from the <form> tag.
<form id="myForm" onsubmit="validateForm();
this.value='Please be patient while your paper is uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this);
return false;">
Make sure to change this.parentNode to just this, for using this set up.
As a personal preference, I like to put google.script.run it's own function. You are already using a separate function for validateForm(), you could put the google.script.run in that function:
Simplify the form tag to:
<form id="myForm" onsubmit="validateForm()">
Script
function validateForm() {
var x=document.getElementsByClassName('required');
for(var i = 0; i <x.length; i++){
if (x[i].value == null || x[i].value == "")
{
alert("All fields must be filled out.");
return false;
}
this.value='Please be patient while your paper is uploading..';
var myFormObject = document.getElementById('myForm');
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(myFormObject);
}
}
Since the function is outside of the form, you can't use this.parentNode anymore. Get the form by your id. One option is shown in the example code.

Execute code when textboxes have data

I have a project which I have to calculate the coordenates between two points. The first coordenates are calculated once the user enters in three text boxes the street, province and city.
How can I execute the code I have in PHP once the user fills out all three boxes and not before?
<form name="form" action="" method="post">
<input type="text" name="provincia" id="provincia">
<input type="text" name="municipio" id="municipio">
<input type="text" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
This is the form the user has to fill in. Once the user writes in all three (without mattering the order) I have php code which Im not sure if it can execute once these boxes have values.
What should I have to use to accomplish this? Ajax? Jquery? Javascript?
Not really sure,
thanks.
are you looking for this?
$(document).ready(function () {
var flag = false;
$("input[type=text]").change(function () {
flag = true;
$("input[type=text]").each(function () {
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
alert(values);
});
});
edit
<form name="form" action="" method="post">
<input type="text" class="tobeChecked" name="provincia" id="provincia">
<input type="text" class="tobeChecked" name="municipio" id="municipio">
<input type="text" class="tobeChecked" name="calle" id="calle">
<input type="submit" value="¡Buscar!"/>
</form>
$(document).ready(function () {
var flag = false;
$(".tobeChecked").change(function () {
var values = "";
flag = true;
$(".tobeChecked").each(function () {
values += $(this).val().trim() + "+";
if ($(this).val().trim() == "") {
flag = false;
}
});
if (flag) {
alert("all have values");
$("input[type=submit]").trigger("click");
}
});
});
Create a function to validate the required field for those three text boxes and once all are filled with values execute your script:
$('#provincia,#municipio,#calle').blur(function(){
if($('#provincia').val() !="" && $('#municipio').val() !="" && $('#calle').val() !=""){
// Do your process here
}
});
You can use jquery validate plugin to validate these 3 input fields on the client side itself, In that way, the user cannot submit the form until he completely fills the input fields.
Give your Button an ID like:
<input type="submit" id="button" value="¡Buscar!"/>
Then you can do this in JQuery:
$("#button").click(function(){
//Get the value of the fields
var textfield1 = document.getElementById("provincia").value;
var textfield2 = document.getElementById("municipio").value;
var textfield3 = document.getElementById("calle").value;
//Check if Values are filled
if ( !textfield1.match(/\S/) || !textfield2.match(/\S/) || !textfield3.match(/\S/))
{
//execute your script
}
I hope it helps.
use jquery .change() function
$( "#provincia" ).change(function() {
//you can do something here
alert( "Handler for .change() called." );
});

How to check checkbox array along with text using javascript

I have HTML page with javascript. In this, I have form which contains text for name and checkboxes. Below is the HTML form:
<form name="drugForm" action="form1.php" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="dname">
<pre>
<input type="checkbox" name="drug" value="id1">ID1 <input type="checkbox" name="drug" value="id2">ID2</br>
<input type="checkbox" name="drug" value="id3">ID3 <input type="checkbox" name="drug" value="id4">ID4</br>
</pre>
<input type="submit" value="Submit">
</form>
Below is the javascript for same:
<script>
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
//var y=document.drugForm.drug[0].value;
var y = new Array();
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
alert("click any checkbox "+ y);
//alert("Working with boolean " + y);
return false;
}
}
</script>
Here, I want to check whether any checkbox is checked also along with name entry. But whenever I am trying to put for loop with y (array) in else if condition or anywhere in function, the code is not working and instead giving action directly.
My question, specifically, is how to check checkboxes, like did in if condition, is checked and how to get those values?
The code below validate when there's at least one checked box:
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
} else if (Boolean(x)) {
for (k=0;k<y.length;k++) {
if(y[k].checked) {
return true;
}
}
alert("Check one option at least");
return false;
}
}
There's another goog option in jquery as shown in another post.
Try this,
function validateForm(){
var x=document.forms["drugForm"]["dname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (x)
{
if(!$('input:checkbox:checked').length)//check length of checked checkboxes
{
alert("click any checkbox ");
return false;
}
}
}

Categories