I have a list, (a simple list) from which i am able to select and set elements (using js), and then a form that allows me to choose how many elements i want, and a submit form.if one doesn't select an element, there is a script that throws an exception. The problem is that i want that the form doesn't submit, if an element is not selected, but not throw an exception, but to show me a message down the submit button (using jquery). my script below:
<? foreach ($types as $type):?>
<ul class = "product_types">
<? if ($type->stock_2 > 0):?>
<li id = 'product_types'><a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a></li>
<? else: ?>
<li id = 'product_unavailable_types'><label><?= $type->label; ?></label></li>
<? endif; ?>
</ul>
<? endforeach; ?>
<form name="addtobasket" method="POST" action="<?= Route::url('Add to Basket', array('sale_id' => $sale->id)); ?>">
<input type="hidden" name="idOfSelectedItem" id="idOfSelectedItem" value="-1">
<select name="number" id="number">
<option value=0>Alege numarul de produse</option> </select>
<button type="submit" name = "submit" onclick="addtobasket";>Adauga in cos</button><br />
</form>
and the js that sets the list elements:
<script type="text/javascript">
function selecteazaElement(id,stock)
{
document.addtobasket.idOfSelectedItem.value=id;
window["canSubmit"] = true;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6)
stock=6;
for (i=1;i<=stock;i++)
{
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
//window.status="my status";
}
Add a submit listener to the form. When it's submitted, check to see if an element is selected, and if not you can prevent the submission by using return false. Here's an example:
$('#myForm').submit(function()
{
if (/* test case not true */) {
$('#myError').show();
return false;
}
// ... continue work
});
And here's the HTML:
<form id="myForm">
<input type="text"/>
<input type="submit"/>
</form>
If you don't want to use jQuery, you can also handle the submit event with plain JavaScript like so:
var myform = document.getElementById('myForm');
myform.addEventListener('submit', function() { console.log('Submitted!'); return false; });
Related
developers i create one page where it fetches data from the registration page. Each data row I put add and unfriend button (disabled). Once the user clicks add, the prompt box appears to ask the user to enter a subject and click ok. After click ok,it insert in another database table.while the unfriend button will be able to click. Here my problem is once click add button the prompt appears and after click ok, the data does not insert into the database. If I click unfriend button it inserts into the database. I want the data submitted whenever the user clicks the add button. I think it's because this form has two submit buttons but I don't know how to distinguish between the buttons.Moreover,in javascript i put return false and true follow some tutorials.may i know when i should use return false and true?. Here is the code:
<?php
session_start();
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID";
$result= mysqli_query($mysqli,$sql);
?>
<html>
<script>
function myFunction(form){
var subject = prompt("Please enter Subject that want to study");
form['add'].value="request sent";
if (subject != null){
form['subject'].value= subject;
form['btn'].disabled=false;
form['add'].disabled=true;
return false;
form.submit();
}
return true;
form['add'].submit();
}
function unfriend(form){
form["add"].disabled=false;
form["btn"].disabled=true;
form["add"].value="Add friend";
return true;
form.submit();
}
</script>
<body>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
?>
<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(this.form);" name="addfriend" data-type='addfriend' id="add" class="btn" value="add" />
<input type="submit" value="unfriend" id="btn" onclick="return unfriend(this.form);" disabled /> </td> </form>
<?php
}
}
?>
<?php
if(isset($_POST['subject']) and $_POST['id']) {
$user_id = $_SESSION['sid'];
$friend_id = $_POST['id'];
$status = "yes";
$subject=$_POST['subject'];
$sql="INSERT INTO friends(user_id,status,subject,friend_id)" ."VALUES('$user_id','yes','$subject','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['friend_id']=$friend_id;
$_SESSION['user_id'] = $user_id;
} else {
}
}?>
</body>
</html>
Your return statements terminate the function; no code after the return will execute, so your form.submit() calls never happen. In your friend function, because you're returning false and your onclick has return friend(...), you're cancelling form submission, and the form is never submitted (not by your code, and not by the browser), In unfriend, though, you're returning true, so although your code doesn't submit the form, the browser does.
If you want to submit the form programatically, put those form.submit calls before the return, and return false so the browser doesn't also submit the form.
Forgive me if this question is naive. I'm new to JavaScript and am learning my way through some setbacks with a form I'm using to display data.
An icao code is passed to the #depicao <select> menu via $_GET['icao'] in the JavaScript code at the bottom of the script. On page load, the <select> menu is populated with the $_GET['icao'] value.
After the #depicao <select> menu is populated, I'd like the form to automatically submit itself with its populated value. My train of thought is that if I include
document.getElementById("form").submit();
as the last line in the script, I can get the script to submit itself after it loads with the $_GET['icao'] value. Unfortunately, this hasn't been working, however.
NOTICE: The code contains multiple <input type="submit" name="submit"> buttons. I believe that this is the culprit.
See code below.
<form id="form" action="<?php echo actionurl('/schedules/view');?>" method="post">
<div id="tabcontainer">
<ul>
<li><span>Via departure airport</span></li>
<li><span>Via arrival airport</span></li>
</ul>
<div id="depapttab">
<select id="depicao" name="depicao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
<div id="arrapttab">
<select id="arricao" name="arricao">
<option value="">Select All</option>
<?php
$exclude = array(13, 18, 19, 22); // Airport IDs found in phpVMS_airports not to be included in the dropdown menu
if(!$depairports) $depairports = array();
foreach($depairports as $airport) {
if(!in_array($airport->id, $exclude)) { // Exclude values in the above array from the dropdown menu
echo '<option value="'.$airport->icao.'">'.$airport->icao.' - '.$airport->name.'</option>';
}
}
?>
</select>
<input type="submit" name="submit" value="Find Flights" />
</div>
</div>
<input type="hidden" name="action" value="findflight" />
</form>
<script type="text/javascript">
function formReset() {
document.getElementById("form").reset();
}
function setSelectedIndex(s, valsearch) {
// Loop through all the items in drop down list
for (i = 0; i< s.options.length; i++) {
if (s.options[i].value == valsearch) {
// Item is found. Set its property and exit
s.options[i].selected = true;
break;
}
}
return;
}
setSelectedIndex(document.getElementById("depicao"),"<?php if(isset($_GET['icao'])) { echo $_GET['icao']; } else { echo 'Select All'; } ?>");
document.getElementById("form").submit();
</script>
Form Auto Submission Confusion ?:
After the #depicao menu is populated, I'd like the form to automatically submit itself with its populated value.
How I understood you was that you want the form to be submitted automatically when the select menu is populated ? I think you meant when the user chooses a selection, it should submit automatically. If this is what you mean. Please add a onchange="//submitfunction()" onto the <select> tag
I want to pass a selected checkbox value, when a user submits (POSTs) a form, to Google Analytics to track as a custom metric within Google Analytics dashboard.
The user will submit their choice to the server which will first call the JS sendDataToGA(selectedOption) { function to pass that data to GA, then the POST will run.
How do I accomplish this? It seems that the POST is firing and not calling the JS function.
PHP/HTML:
<?php if (!empty($_POST)): ?>
Selection: <?php echo htmlspecialchars($_POST["option"]); ?><br>
<?php else: ?>
<!-- On form submit, fire a custom GA function to capture the selected option -->
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post" >
<input type="checkbox" name="option" value="option 1">Option 1<br>
<input type="checkbox" name="option" value="option 2">Option 2<br>
<input type="submit" value="Submit" id="submitBtn" onclick="sendDataToGA(selectedOption);">
</form>
<?php endif; ?>
JS:
function sendDataToGA(selectedCheckboxValue) {
ga('send', 'event', 'category', 'action', {
'metric1': selectedCheckboxValue,
'hitCallback': function () {
console.log("data has been sent to Google Analytics");
}
});
}
If you give your form an id attribute you can do the following using jQuery
$("#myForm").submit(function () {
ga(...);
});
or without jQuery:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> onsubmit="sendDataToGA(selectedOption)" method="post">
...
</form>
You can intercept the submit event before it posts to the server. In jQuery, this is a handler you attach in the domReady event. This assumes your form has id="formid", and you can halt the postback by setting everythingIsOkay = false.
$(document).ready(function () {
$("#formid").submit(function(event) { //Catch form submit event
event.preventDefault(); //Stop it from posting back unless you tell it to
var everythingIsOkay = true;
//Do your processing here
if(everythingIsOkay){
document.forms["formid"].submit(); //Go ahead and postback
}
});
});
I have a sign up dialog box, which has a login form in it.
I have done some basic form validation in the same file as the form, if errors exist then appropriate messages are echo'd out underneath the fields when the form is submit.
However when the form is submit, the page is refreshed and the dialog box closes, it has to be opened again for the user to see the errors. This is not very appropriate and I want to somehow keep the dialog box open on refresh, only IF errors exist in the form validation.
There must be a way around this but I don't quite know how to implement this.
Here is my code (index.php):
// PHP validation
$fornameErr = $surnameErr ="";
$forname = $surname="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["forename"])) {
$fornameErr = "Missing";
}
else {
$forename= $_POST["forename"];
}
if (empty($_POST["surname"])) {
$surnameErr= "Missing";
}
else {
$surname= $_POST["surname"];
}
}
// Link which opens up the dialog box by calling the 'check_domain_input()' function
<div id="clickable" onclick="check_domain_input()">Or sign up</div>
// The form in the dialog box
<div id="dialog" title="Sign up" style="display:none">
<center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div align="center">
<br/>
<input type="text" class="input" name="forename" size="20" maxlength="40" placeholder="Forename" value="<?php echo htmlspecialchars($forename);?>"/>
<span class="error"><?php echo $fornameErr ;?></span>
<br/>
<input type="text" class="input" name="surname" size="20" maxlength="40" placeholder="Surname" value="<?php echo htmlspecialchars($surname);?>"/>
<span class="error"><?php echo $surnameErr ;?></span>
<br/>
<input type="submit" value ="Sign up" class="submit"/>
<br/>
<br/>
</div>
</form>
</center>
</div>
<!-- Dialog box function -->
<script>
function check_domain_input()
{
$( "#dialog" ).dialog({modal: true});
var domain_val = document.getElementsByName('domain');
if (domain_val[0].value.length > 0)
{
return true;
}
$( "#dialog" ).dialog({modal: true});
return false;
}
</script>
You could call your check_domain_input method as the page loads if you've got an error to show, like this:
<script>
function check_domain_input()
{
...
}
<?php if (!empty($fornameErr) || !empty($surnameErr)) : ?>
$(function() {
check_domain_input();
});
<?php endif; ?>
</script>
You can use onsubmit="return validateFunction()" as shown at this link.
You can have PHP set a JavaScript variable that your jQuery onload function reads and reacts to.
You can use AJAX instead of form submissions. With AJAX, you can simply use the AJAX call's error function to react to bad validation.
I have a page which has lot of post data in the url.
For example,
www.test.com/test.php?userid='tester'&name=test&so on
The above page has a form that has something like this:
<?
$set=get_value_set;
if($set ==1) {
$set_value="SET";
} else {
$set_value="UNSET";
}
?>
<form name="test">
<input type="text" readonly="READONLY" value="<? echo $user_id; ?>">
<input type="submit" value="Email" name="submit_user">
<input type="submit" value="<? echo $set_value; ?>" name="submit_user">
<?
function setuser()
{
//sets the value
}
function email_user()
{
//sets the value
}
?>
there are two buttons above, when I click on email, i want the value of email button to be passed to the email_user function and do some proceesing there. Similar thing when I click on the set button.
NOTE:But in both cases above, I want the form to remain in the same page with the same post data in the url, but I also want the page to be refreshed so that the set button can have a value of Set or Unset depending on the database update.
Is this possible?
I would start to remove the submit action of each button and change them to
<input type="button" class="btn-Email" value="Email" name="submit_user" />
<input type="button" class="btn-Other" value="<? echo $set_value; ?>" name="submit_user" />
and then, using jQuery, you can easily process each click and submit the form
$(function() {
$(".btn-Email").click(function() {
// append anything you want
var but_email_value = $(this).val(), // or $(".btn-Email").val()
btn_other_value = $(".btn-Other").val();
$("form").submit();
});
$(".btn-Other").click(function() {
// append anything you want
var but_other_value = $(this).val(), // or $(".btn-Other").val();
btn_email_value = $(".btn-Email").val();
$("form").submit();
});
});
change your HTML
<form id="test" name="test">
...
<button onclick="email_user();">Email</button>
<button onclick="setuser();"><? echo $set_value; ?></button>
</form>
your functions should submit the form for you:
document.getElementById("test").submit();