To keep it simple I have 2 form multiple select elements. Depending on the dropdown selected, it will auto hide or show additional input fields.
This is achieved like such:
$(document).ready(function(){
$("#find-replace1 select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep1").hide();
$(".find1").show();
$(".replace1").show();
} else {
$(".rep1").show();
$(".find1").hide();
$(".replace1").hide();
}
});
}).change();
});
$(document).ready(function(){
$("#find-replace2 select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep2").hide();
$(".find2").show();
$(".replace2").show();
} else {
$(".rep2").show();
$(".find2").hide();
$(".replace2").hide();
}
});
}).change();
});
My html is:
<p>
<form method="POST" action="#" accept-charset="UTF-8">
<div id="find-replace1" class="form-group-a">
<select class="form-control" name="priceaction">
<option value="Append">Append</option>
<option value="Prepend">Prepend</option>
<option value="Replace">Replace</option>
<option value="Find/Replace">Find/Replace</option>
</select>
</div>
<div class="form-group-a">
<input class="form-control formwidth rep1" autocomplete="off" name="value" type="text" style="display: block;">
</div>
<div class="form-group-a">
<input class="form-control formwidth find1" autocomplete="off" placeholder="find this" name="find" type="text" style="display: none;">
</div>
<div class="form-group-a">
<input class="form-control formwidth replace1" autocomplete="off" placeholder="replace with" name="replace" type="text" style="display: none;">
</div>
<div class="clear"></div>
<input type="submit" value="Update">
</form>
</p>
<hr>
<p>
<form method="POST" action="#" accept-charset="UTF-8">
<div id="find-replace2" class="form-group-a">
<select class="form-control" name="priceaction">
<option value="Append">Append</option>
<option value="Prepend">Prepend</option>
<option value="Replace">Replace</option>
<option value="Find/Replace">Find/Replace</option>
</select>
</div>
<div class="form-group-a">
<input class="form-control formwidth rep2" autocomplete="off" name="value" type="text" style="display: block;">
</div>
<div class="form-group-a">
<input class="form-control formwidth find2" autocomplete="off" placeholder="find this" name="find" type="text" style="display: none;">
</div>
<div class="form-group-a">
<input class="form-control formwidth replace2" autocomplete="off" placeholder="replace with" name="replace" type="text" style="display: none;">
</div>
<div class="clear"></div>
<input type="submit" value="Update">
</form>
</p>
Here is the jsfiddle: https://jsfiddle.net/kqjkprc1/
On my live site I actually have more than one form element but I kept it simple with 2 for this example. I notice it only applies the jQuery to the last form element on the page no matter what. Not sure why the first form element is unaffected and won't show/hide the hidden input fields.
On the one hand you can add different form actions like this
<form method="POST" action="update_1.php" >
</form>
<form method="POST" action="update_2.php">
</form>
on the other hand you can define differnt submit names
<form method="POST" action="#" >
<input type="submit" name="form1">
</form>
<form method="POST" action="#" >
<input type="submit" name="form2">
</form>
and get in in the php file like that
if (!empty($_POST['form1'])) {
//do something here for form 1;
}
if (!empty($_POST['form2'])) {
//do something here for form 2;
}
--- UPDATE ---
ahh ok i think i have a solution for you (first line changes)
$( "option:selected", this).each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep1").hide();
$(".find1").show();
$(".replace1").show();
} else {
$(".rep1").show();
$(".find1").hide();
$(".replace1").hide();
}
});
https://jsfiddle.net/kqjkprc1/1/
Related
this question has been asked but I haven't found a working solution.
I have 2 forms. The first is sending datas to the database (form2). The second one is uploading a photo (form1).
I would need to save the path of the uploaded picture and store it in a text input in form1 and after send it with the form2 datas. Do you have any tips? It is possible without JQuery using just Php?
I have a solution with JQuery but it is not working.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function submitform()
{
var name=$('#name').val();
$('#variable').val(name); // set the value of name field to the hidden field
$('form#form1').submit(); // submit the form
}
</script>
Create a new product
<form action="../handlers/processNewProduct.php" id="form2">
<div class="mb-3">
<label for="productname" class="form-label">Product Name</label>
<input type="text" class="form-control" id="productname" name="productname" placeholder="Product Name">
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<input type="text" class="form-control" id="description" value="xxxxxxxxx" name="description" placeholder="Description">
</div>
<div class="mb-3">
<label for="pricelist" class="form-label">Price list</label>
<input type="number" class="form-control" id="pricelist" name="pricelist" placeholder="Price">
</div>
<input type='text' name='variable' id='variable' value=''>
<button type="" class="btn btn-primary">Insert data</button>
</form>
<form action="../handlers/processUploadProductPicture.php" method="post" enctype="multipart/form-data" id="form1" onsubmit="submitform()">
Select image to upload:
<input type='file' name='fileToUpload' id='name'>
<input type='submit' value='Upload Image' id='upload'>
</form>
I have a HTML form that send a request to API with AJAX. But i would not leave the api key in the JS file. So, i thinked to do a PHP wrapper but i'm at start and i don't know how can i do. Can you give me some exemples for understand this process?
I have this form that redirect to the url:
<form action="www.mysite.com/subscribe" method="POST" accept-charset="utf-8" id="signup-form" name="signup-form">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="Nome"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="cognome" id="cognome" placeholder="Cognome"/>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email"//>
</div>
<?php include('countries.php'); ?>
<div class="form-group">
<select class="form-control" id="list" name="list">
<option value="" disabled="disabled">Seleziona un interesse</option>
<option value="aVD3PdrkiaVJhVU9yN9nMQ">lista 3</option>
<option value="spd7cktddsPGTgoDuu892f763Q">lista 2</option>
<option value="yCQHvcGxKvBFTeoSp892UxZA">lista 1</option>
</select>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="gdpr" id="gdpr" >
<label class="form-check-label" for="gdpr">Accetta il gdpr</label>
</div>
<input type="submit" value="Sign up" id="submit-btn"/>
<p id="status"></p>
</form>
And my JS file with AJAX call (Miss some elements)
$(document).ready(function() {
$("#signup-form").submit(function(e) {
console.log('submitting');
e.preventDefault();
var $form = $(this),
url = $form.attr('action');
url = 'https://sendy.exnovostudio.eu/subscribe';
var e = document.getElementById("list");
var list = e.value;
params = {
name: $form.find('input[name="name"]').val(),
email: $form.find('input[name="email"]').val(),
list: list,
api_key: <---I WANT HIDE THIS BUT IT DOESN T WORK IF I DELETE
gdpr : gdpr,
boolean: true
}
window.message = function(text, color){
$("#status").css("color", color).text(text);
}
$form.find('input').attr("disabled", "disabled");
message('iscrizione in corso...', 'blue');
What is the best practice to share the api key in the AJAX call?
When the user picks either phone or email I want the form to then generate a box to enter the details of which they selected. How do I do this? Thanks.
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" value="<?= (isset($fields['phone']) ? $fields['phone'] : '' )?>"/>
</div>
<div class="field-container full clearfix">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" value="<?= (isset($fields['email']) ? $fields['email'] : '' )?>"/>
</div>
Here's a snippet that shows you how to do that with javascript:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
Please note that I added a Id to the select element and to the input elements.
EDIT | USAGE
Create a file, call it script.js or whatever you like and put this in it:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
Save the file to a folder on your server that is accesible. For example /public/js/script.js
In your html, add
<script src="/public/js/script.js"></script> <!-- or however your path is -->
to the very end of your file, directly before the closing </body> tag So that it looks like this
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
<script src="/public/js/script.js"></script> <!-- here is the script included -->
</body>
That's it.
This worked for me:
Add an id to your select: select name="fields[contact]" id="contact"
Set phone and email fields to hidden by using a class or inline style: div class="field-container full clearfix hide-this" id="phone-container"
--or just set style: display:none;
Javascript:
$('#contact').change(function(){
if(this.selectedOptions[0].text == 'phone') {
$('#phone-container').show().focus();
}else{$('#phone-container').hide();}
});
This should do the trick... let me know?
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
.field-hide{
display: none;
}
</style>
<script>
function valChange(ele){
var fields = document.getElementById("container").children;
for(var i=0; i < fields.length; i++){
fields[i].classList.add("field-hide");
}
switch(ele.value){
case "phone":
document.getElementById("phone").classList.remove("field-hide");
break;
case "email":
document.getElementById("email").classList.remove("field-hide");
break;
}
}
</script>
</head>
<body>
<div class="field-container full clearfix">
<label class="required">What is your preferred method of contact?</label>
<select type="text" name="fields[contact]" onchange="valChange(this)">
<option value="blank" selected disabled>Choose</option>
<option value="phone">Quoted</option>
<option value="email">Labour Only</option>
</select>
</div>
<div id="container">
<div class="field-container full clearfix field-hide" id="phone">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" placeholder="enter phone number">
</div>
<div class="field-container full clearfix field-hide" id="email">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" placeholder="enter email">
</div>
</div>
</body>
</html>
I have a form by multiple field. In this form i can add multiple group field by prese a button via javascript. To understand exactly what I mean please see fiddle:
https://jsfiddle.net/alihesari/060ym890/2/
How to get all added fields by php and insert theme in mysql after submit?
<fomr action="">
<button type="button" id="add_hotel" class="btn btn-primary">
Add Hotel</button>
<button type="button" id="remove_hotel" class="btn btn-warning">Remove Hotel</button>
<ul class="hotels_ul">
<li class="hotel_li">
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="hotel_name[]">Hotel Name:</label>
<input type="text" name="hotel_name[]" id="hotel_name[]" class="form-control" placeholder="Hotel Name">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="hotelRate[]">Hotel Rate: </label>
<select name="hotelRate[]" id="hotelRate[]" class="form-control">
<option value=""></option>
<option value="متل">متل</option>
<option value="یک ستاره">یک ستاره</option>
<option value="دو ستاره">دو ستاره</option>
<option value="سه ستاره">سه ستاره</option>
<option value="سه ستاره تاپ">سه ستاره تاپ</option>
<option value="چهار ستاره">چهار ستاره</option>
<option value="چهار ستاره تاپ">چهار ستاره تاپ</option>
<option value="پنج ستاره">پنج ستاره</option>
<option value="پنج ستاره تاپ">پنج ستاره تاپ</option>
<option value="هفت ستاره">هفت ستاره</option>
<option value="هتل آپارتمان">هتل آپارتمان</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room1[]">Room 1</label>
<input name="room1[]" id="room1[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room2[]">Room 2</label>
<input name="room2[]" id="room2[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room3[]">Room 3</label>
<input name="room3[]" id="room3[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room4[]">Room 4</label>
<input name="room4[]" id="room4[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-20">
<div class="form-group">
<label for="desc[]">Description</label>
<textarea class="form-control" name="desc[]" id="desc[]" placeholder="Description"></textarea>
</div>
</div>
</div>
</li>
</ul>
<input type="submit" value="submit">
</form>
Here's an example of how you can handle the forms with both JS and PHP.
(if the JS example here doesn't work, see https://jsfiddle.net/n6kzxj4m/)
$(function() {
$(".add").on('click', function(e) {
$($(".hotel").last().clone(true, true)).insertAfter($(".hotel").last());
// reset new items
$(".hotel").last().find(':input:not(select)').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(".hotel").last().find('[select]').prop('selectedIndex', 0);
$(".hotel").last().find(':checkbox, :radio').prop('checked', false);
});
$(".remove").on('click', function(e) {
$(this).parents(".hotel").remove();
});
$("form").on('submit', function(e) {
e.preventDefault();
var $form = $(this);
$("#output").html($form.serializeJSON());
});
});
// plugin below only for debug on jsfiddle
/**
* jQuery serializeObject
* #copyright 2014, macek <paulmacek#gmail.com>
* #link https://github.com/macek/jquery-serialize-object
* #license BSD
* #version 2.4.5
*/
!function(e,r){if("function"==typeof define&&define.amd)define(["exports","jquery"],function(e,i){return r(e,i)});else if("undefined"!=typeof exports){var i=require("jquery");r(exports,i)}else r(e,e.jQuery||e.Zepto||e.ender||e.$)}(this,function(e,r){function i(e,i){function n(e,r,i){return e[r]=i,e}function a(e,r){for(var i,a=e.match(t.key);void 0!==(i=a.pop());)if(t.push.test(i)){var o=s(e.replace(/\[\]$/,""));r=n([],o,r)}else t.fixed.test(i)?r=n([],i,r):t.named.test(i)&&(r=n({},i,r));return r}function s(e){return void 0===h[e]&&(h[e]=0),h[e]++}function o(e){switch(r('[name="'+e.name+'"]',i).attr("type")){case"checkbox":return"on"===e.value?!0:e.value;default:return e.value}}function u(r){if(!t.validate.test(r.name))return this;var i=a(r.name,o(r));return c=e.extend(!0,c,i),this}function f(r){if(!e.isArray(r))throw new Error("formSerializer.addPairs expects an Array");for(var i=0,t=r.length;t>i;i++)this.addPair(r[i]);return this}function d(){return c}function l(){return JSON.stringify(d())}var c={},h={};this.addPair=u,this.addPairs=f,this.serialize=d,this.serializeJSON=l}var t={validate:/^[a-z_][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,key:/[a-z0-9_]+|(?=\[\])/gi,push:/^$/,fixed:/^\d+$/,named:/^[a-z0-9_]+$/i};return i.patterns=t,i.serializeObject=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serialize()},i.serializeJSON=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serializeJSON()},"undefined"!=typeof r.fn&&(r.fn.serializeObject=i.serializeObject,r.fn.serializeJSON=i.serializeJSON),e.FormSerializer=i,i});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
<fieldset class="hotel">
<legend>Add a hotel</legend>
<p><label>Hotel: <input type="text" name="hotel[name][]" /></label></p>
<p><label>Rate: <select name="hotel[rate][]"><option>123</option><option>456</option></select></label></p>
<p><input type="button" class="add" value="Add hotel" /> <input type="button" class="remove" value="Remove this hotel" /></p>
</fieldset>
<p><input type="submit" value="Search!" /></p>
</form>
<pre id="output"></pre>
Then, for the PHP handling, you can do:
<?php
if(!empty($_POST)) {
// handle items. $key is the index.
foreach($_POST['hotel']['name'] as $key => $hotel) {
$name = $hotel;
$rate = $_POST['hotel']['rate'][$key];
echo "Name: $name<br>Rate: $rate<hr>";
}
}
NOTE: You may want to check to ensure the number of items in $_POST['hotel']['name'] match the number of items in $_POST['hotel']['rate']. This method may not be ideal, and you may want to assign an ID per hotel row item via JS. But this is a basic approach to your question.
I am building a simple form script that collects a users email and returns a PIN.
The input sits in standard HTML below:
<p>
<form class="form-inline" role="form" method="POST">
<div class="form-group">
<label class="sr-only" for="srEmail">Email address</label>
<input type="email" name="srEmail" class="form-control input-lg" id="srEmail" placeholder="Enter email">
</div>
<button type="submit" name="srSubmit" class="btn btn-default btn-lg">Generate PIN</button>
</form>
</p>
I have the following if statement that checks the database to see if the email already exists, and if the user would like a PIN reminder.
if($num_rows != 0) {//if email found in table
?>
Email already registered, would you like a PIN reminder?
<form method="POST" action="">
<input type="submit" name="srSend" value="Click here to get pin reminder" />
<input type="hidden" name="srEmail" value="<?php echo strtolower($email);?>" />
</form>
<?php
exit;
}
At the moment, this returns the result to the user as a new page; how do I put this in the actual HTML of the body page, so it would actually appear below the original form input in a new <p> element?
This is a piece of cake with jquery.post
include the jquery library in your html head and you'll need a short script to get the php content by ajax
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$('#yourForm').submit(function(e){
e.preventDefault();
var data=$('#yourForm').serialize();
$.post('yourphp.php',data,function(html){
$(body).append(html);
});
});
});
</script>
</head>
<body>
<p>
<form id="yourForm" class="form-inline" role="form" method="POST">
<div class="form-group">
<label class="sr-only" for="srEmail">Email address</label>
<input type="email" name="srEmail" class="form-control input-lg" id="srEmail" placeholder="Enter email">
</div>
<button type="submit" name="srSubmit" class="btn btn-default btn-lg">Generate PIN</button>
</form>
</p>
</body>
You could able to achieve that without ajax too. Simply use a hidden iframe in your main page, then set the target attribute of your form to the iframe as follows:
<form method="post" action="page.php" target="myIframe">
.....
</form>
<p id="theResultP"></p>
<iframe src="#" name="myIframe" style="visibility: hidden"></iframe>
The question now, How could you make the page loaded in the iframe "page.php" to interact with the opener page to update the p. This may be done as follow:
//page.php
<script>
result = parent.document.getElementById('theResultP');
result.innerHtml = "<b>The message you want</b>"
</script>
I dont know if I get what you asking for,but this is my solution :
<p>
<form class="form-inline" role="form" method="POST">
<div class="form-group">
<label class="sr-only" for="srEmail">Email address</label>
<input type="email" name="srEmail" class="form-control input-lg" id="srEmail" placeholder="Enter email">
</div>
<button type="submit" name="srSubmit" class="btn btn-default btn-lg">Generate PIN</button>
</form>
</p>
<?php
if (isset($message)){
<p><?php print $message ?></p>
?>
<?php
}
?>
and in top of your file write something like this :
<?php
if($_post['srSend']){
$message='write your message here';
}
?>