Here is what I want to do: I have a form on which I have a checkbox. When that checkbox is checked I want some additional fields to show and when it is not checked I want those fields not to show. Also after the form is submitted and there is some kind of error (for example the person has not confirmed that they are not a robot) I want the checkbox to remain checked if it was previously checked (and of course the additional fields still to be showed if it is checked).
I tried a couple of different approaches:
Using data-toggle
Using a JavaScript on click function of the checkbox
Using jQuery prop method
Using jQuery :checked selector
(Reference for 3. and 4. https://www.tutorialrepublic.com/faq/how-to-check-a-checkbox-is-checked-or-not-using-jquery.php)
An occurring problem with all of the methods was that after submitting the form with errors then the additional fields would not be shown even though the checkbox was checked.
<div class="form-group">
<label for="additionalFields" class="checkbox-inline ml-1 mb-0">Show additonal fields</label>
<input class="align-middle" type="checkbox" name="additionalFields" value="additionalFields" data-toggle="collapse" data-target="#fields" <?php if (isset($_POST['additonalFields'])) echo 'checked="checked"'; ?>>
</div>
<div class="form-group collapse in row" id="fields">
<div class="col-sm-6">
<label class="form-control-label ml-1 mb-xs-form" for="fieldOne">Field 1:</label>
<input class="form-control" type="text" id="fieldOne" name="fieldOne" maxlength="100" placeholder="Field 1"
<?php
if ($_POST && ($suspect || $errors || !($response->success))) {
echo 'value="' . htmlentities($fieldOne) . '"';
}
?>>
</div>
<div class="col-sm-6">
<label class="form-control-label ml-1 mt-3 mt-sm-0" for="fieldTwo">Field 2</label>
<input class="form-control" type="text" id="fieldTwo" name="fieldTwo" maxlength="100" placeholder="Field 2"
<?php
if ($_POST && ($suspect || $errors || !($response->success))) {
echo 'value="' . htmlentities($fieldTwo) . '"';
}
?>>
</div>
</div><!-- form-group -->
The above code is using data-toggle. When using JavaScript or jQuery I was using display: none; and display: flex; to show and hide the additional fields.
I do not see any jQuery but I assume you mean
$(function() {
$("[name=additionalFields]").on("change",function() {
$($(this).data("target")).toggle(this.checked);
}).trigger("change"); // initialise on load
})
on html reloading, you need manually predefined what js event did if you click the checkbox.
if you mean using data-toggle is using bootstrap accordion, then you need to add class 'show' to event data target to make that extra input field showed.
so try this:
<div class="form-group">
<label for="additionalFields" class="checkbox-inline ml-1 mb-0">Show additonal fields</label>
<input class="align-middle" type="checkbox" name="additionalFields" value="additionalFields" data-toggle="collapse" data-target="#fields" <?php if (isset($_POST['additonalFields'])) echo 'checked="checked"'; ?>>
</div>
<div class="form-group collapse in row <?php if (isset($_POST['additonalFields'])) echo 'show'; ?>" id="fields">
<div class="col-sm-6">
<label class="form-control-label ml-1 mb-xs-form" for="fieldOne">Field 1:</label>
<input class="form-control" type="text" id="fieldOne" name="fieldOne" maxlength="100" placeholder="Field 1"
<?php
if ($_POST && ($suspect || $errors || !($response->success))) {
echo 'value="' . htmlentities($fieldOne) . '"';
}
?>>
</div>
<div class="col-sm-6">
<label class="form-control-label ml-1 mt-3 mt-sm-0" for="fieldTwo">Field 2</label>
<input class="form-control" type="text" id="fieldTwo" name="fieldTwo" maxlength="100" placeholder="Field 2"
<?php
if ($_POST && ($suspect || $errors || !($response->success))) {
echo 'value="' . htmlentities($fieldTwo) . '"';
}
?>>
</div>
Related
In the last part of the code, i have more than one checkbox. I have an input textbox named livello that must store its value to mysql database.
The checkboxes are not fixed in number but can vary if the admin add some to the data base. So based on this code
<!--Add Utente Modal -->
<div id="aggiungi" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<form method="post" class="form-horizontal" role="form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi UTENTE</h4>
</div>
<div class="modal-body">
<input type="hidden" name="edit_id" value="<?php echo $id; ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="username">Username:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username" name="username" required autofocus> </div>
<label class="control-label col-sm-2" for="password">Password:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="password" name="password" required> </div>
</div>
<br>
<br>
<div class="form-group">
<label class="control-label col-sm-2" for="nome">Nome:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="nome" name="nome" required> </div>
<label class="control-label col-sm-2" for="cognome">Cognome:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="cognome" name="cognome" required> </div>
</div>
<br>
<br>
<div class="form-group">
<label class="control-label col-sm-2" for="sesso">Sesso:</label>
<div class="col-sm-4">
<select id="sesso" name="sesso" >
<option value=" "> </option>
<option value="m">Maschio</option>
<option value="f">Femmina</option>
</select>
</div>
<label class="control-label col-sm-2" for="posizione">Posizione:</label>
<div class="col-sm-4">
<select id="posizione" name="posizione" >
<option value=" "> </option>
<option value="Staff">Staff</option>
<option value="Operatore">Operatore</option>
</select>
</div>
</div>
<br>
<br>
<div class='form-group'>
<?php
$sql = "SELECT id, posizione, nome
FROM user_livelli";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$posizione = $row['posizione'];
$nome = $row['nome'];
?>
<input type='checkbox' name='nome_posiz[]'/> <?php echo $nome; ?>
<div id='show' class='col-sm-4'></div>
<?php
}
}
?>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="livello">Livello:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="livello" name="livello"> </div>
</div>
<script>
let oShow=document.getElementById('show');
let oInput=document.getElementById('livello');
let oCol=Array.from( document.querySelectorAll('.form-group > input[type="checkbox"]') );
let livello=new Array( oCol.length ).fill( '0', 0, oCol.length );
oInput.value=livello.join('');
oCol.forEach( (chk,index)=>{
chk.addEventListener('change',function(e){
livello.splice(index,1,this.checked ? '1':'0' );
oShow.innerHTML=livello.join('');
oInput.value=livello.join('');
});
})
</script>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="add_utente"><span class="glyphicon glyphicon-plus"></span> Aggiungi</button>
<button type="button" class="btn btn-warning" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> Annulla</button>
</div>
</form>
</div>
</div>
</div>
When i add a new UTENTE (user), i would like to have Livello at 000000 because the 6 checkboxes are unchecked. When i check one or more checkboxes, Livello immediately change value to for example 100011.
PS in edit
The script works very well for add a new user where the admin check the necessary checkbox.
How can the script be changed for edit user data.
In this case the checkbox are checked or not (and this part already works), livello have a value like 0010011100
I would like livello value printed inside livello input box and that this value could also change if i check or uncheck checkboxes
ID attributes MUST be unique within the DOM. So, rather than assigning each with the same ID set that as the element's name - and use the array style syntax.
I'm not a user of jQuery but I'm sure it is feasible to do this in jQuery with probably only minor modifications to the following. The below uses document.querySelectorAll to find a reference to ALL the checkboxes and assigns a simple listener to each.
let oShow=document.getElementById('show');
let oInput=document.getElementById('livello');
let oCol=Array.from( document.querySelectorAll('.form-group > input[type="checkbox"]') );
let livello=new Array( oCol.length ).fill( '0', 0, oCol.length );
oCol.forEach( (chk,index)=>{
chk.addEventListener('change',function(e){
livello.splice(index,1,this.checked ? '1':'0' );
oShow.innerHTML=livello.join('');
oInput.value=livello.join('');
});
})
<div class='form-group'>
<input type='checkbox' name='check[]' value='1' />aaa
<input type='checkbox' name='check[]' value='1' />bbb
<input type='checkbox' name='check[]' value='1' />ccc
<input type='checkbox' name='check[]' value='1' />ddd
<input type='checkbox' name='check[]' value='1' />eee
<input type='checkbox' name='check[]' value='1' />fff
<div id='show' class='col-sm-4'></div>
</div>
<!-- as per comment, unclear where in the DOM this snippet lives however -->
<div class='form-group'>
<label class='control-label col-sm-2' for='livello'>Livello:</label>
<div class='col-sm-4'>
<input type='text' class='form-control' id='livello' name='livello'>
</div>
</div>
You could use something like
$livello = "";
if(isset($_POST['checkbox1']){
$livello .= "1";
} else {
$livello .= "0";
}
if(isset($_POST['checkbox2']){
$livello .= "1";
} else {
$livello .= "0";
}
Thanks to the jquery code provided by Swati, I understand that to see the string (all zeros that is all unchecked) inside livello as soon as the code start, just add oInput.value=livello.join(''); after string declaration in the javascript. Thanks so much
I have a foreach that loops through and javascript that toggles days of the week and then a checkbox that toggles the times to - from. Although, if there are two of these the toggle only works for the top one.
I am trying to figure out how to have each toggle separate on each div. I think I need to use parent but im not too sure. Also this is an edit, so I need to have the values displayed on each one if selected.
$('input[id="specificTime"]').on('switchChange.bootstrapSwitch', function(event, state) {
$("#specific_on").toggle();
console.log(state); // true | false
});
$('#MonChecked').click(function() {
$("#MonTimes").toggle(this.checked);
});
$('#TueChecked').click(function() {
$("#TueTimes").toggle(this.checked);
});
$('#WedChecked').click(function() {
$("#WedTimes").toggle(this.checked);
});
$('#ThuChecked').click(function() {
$("#ThuTimes").toggle(this.checked);
});
$('#FriChecked').click(function() {
$("#FriTimes").toggle(this.checked);
});
$('#SatChecked').click(function() {
$("#SatTimes").toggle(this.checked);
});
$('#SunChecked').click(function() {
$("#SunTimes").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" style="height:30px">
<div class="col-md-3 topPadding">
Specific Times
</div>
<div class="col-md-9" style="height:30px">
<!-- <input type="checkbox" class="make-switch" data-on-label="All Times" data-off-label="Specific Times" value="time" name="specificTime" data-size="small"> -->
<input type="checkbox" class="make-switch" data-on-label="All Times" data-off-label="Specific Times" value="time" id="specificTime" name="specificTime" data-size="small">
</div>
</div>
<hr>
<div id="specific_on" style="display:none">
<div class="row">
<div class="col-md-12">
<?php foreach ($week_days as $day) {
$sday = substr($day,0,3);
?>
<div class="row">
<div class="col-md-1">
<input type="checkbox" class="form-control input-sm" id="<?php echo $sday?>Checked" name="day[]" value="<?php echo $sday?>" data-size="small">
</div>
<div class="col-md-2 topPadding">
<?php echo ucfirst($day) ?>
</div>
<div id="<?php echo $sday?>Times" style="display:none;">
<div class="col-md-2 topPadding2">
<input type="text" class="form-control timepicker form-filter input-sm" id="timepicker" required readonly name="<?php echo $sday?>_time_from" placeholder="From">
</div>
<div class="col-md-2 topPadding2">
<input type="text" class="form-control timepicker form-filter input-sm" id="timepicker" required readonly name="<?php echo $sday?>_time_to" placeholder="To">
</div>
</div>
</div>
<?php } ?>
</div>
</div>
</div> <!-- End of specific_on -->
I have a form that uses JavaScript for displaying a div depending on what radio button was chosen. Now in my other form for the update, i'd applied the same java script but made few changes on displaying directly the div without clicking the radio button but it didn't work. How to do it correctly. Any help is much appreciated.
<script type="text/javascript">
function payment() {
if (document.getElementById('installmentCheck').checked) {
document.getElementById('installment').style.display = "block";
document.getElementById('full').style.display = "none";
}else if (document.getElementById('fullCheck').checked) {
document.getElementById('full').style.display = "block";
document.getElementById('installment').style.display = "none";
}
}
</script>
<div class="col-lg-6 ">
<div class="form-group">
<label class="control-label">
Payment Scheme :
</label>
<div class="input-group ">
<?php
if ($scholarship->scholarship_payment != 'Full') {
echo '<input type="radio" onclick="javascript:payment();" name="choosePaymentScheme" id="installmentCheck" value="Installment" checked > Installment    ';
echo '<input type="radio" onclick="javascript:payment();" name="choosePaymentScheme" id="fullCheck" value="Full"> Full';
}else{
echo '<input type="radio" onclick="javascript:payment();" name="choosePaymentScheme" id="installmentCheck" value="Installment" > Installment    ';
echo '<input type="radio" onclick="javascript:payment();" name="choosePaymentScheme" id="fullCheck" value="Full" checked> Full';
}
?>
</div>
</div>
<div id="installment" style="display:none">
<div class="form-group">
<input type="text" name="Install" >
</div>
</div>
<div id="full" style="display:none">
<div class="form-group">
<input type="text" name="full" >
</div>
</div>
</div>
If I understood you correctly, you could remove the display:none CSS from the bottom <div>s conditionally:
<div id="installment" <?php if($scholarship->scholarship_payment == 'Full'){ echo 'style="display:none"' } ?>>
<div class="form-group">
<input type="text" name="Install" >
</div>
</div>
<div id="full" <?php if($scholarship->scholarship_payment != 'Full'){ echo 'style="display:none"' } ?>>
<div class="form-group">
<input type="text" name="full" >
</div>
</div>
Or, alternatively, switch id and name in one box:
<div id="<?php if($scholarship->scholarship_payment != 'Full'){ echo 'installment' } else { echo "full" } ?>">
<div class="form-group">
<input type="text" name="<?php if($scholarship->scholarship_payment != 'Full'){ echo 'Install' } else { echo "full" } ?>" >
</div>
</div>
I am trying to populate a form on a button click, so for example a user clicks a button and then it populates the inputs with the button id's information from a json page. I have added what I need in the jquery belo
Here's my javascript, which doesn't have an onclick, which I need it to, but need it t
jquery script
(i need an on click perform this action)
$.get('<?php echo Config::get('URL'); ?>dashboard/employment_json/(i need this to be the value of the button)',function(d){
$("input[name='json_name']").val(d.name);
$("input[name='json_country']").val(d.country);
$("input[name='json_start']").val(d.date_start);
$("input[name='json_end']").val(d.date_end);
$("input[name='json_duration']").val(d.duration);
$("input[name='json_description']").val(d.description);
},'json');
Here's sample data of the inputs:
<div class="col-md-6">
<div class="form-group">
<label for="field-1" class="control-label">
<?php echo System::translate("Employment name"); ?>
</label>
<input type="text" disabled name="json_name" class="form-control" id="field-1">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Employment Country"); ?>
</label>
<input type="text" disabled name="json_country" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Start Date"); ?>
</label>
<input type="text" disabled name="json_start" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("End date"); ?>
</label>
<input type="text" disabled name="json_end" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Employment Duration"); ?>
</label>
<input type="text" disabled name="json_duration" class="form-control" id="field-2">
</div>
</div>
And lastly, but not least,
Json sample
{"employment":{"name":"test","duration":"12","date_end":"2015-07-01","date_start":"2014-07-07","country":"America","description":"This is just a test description of no important value. Have a nice day."}}
Maybe something like this ?
$('.myButtonClass').on('click', function(e){
var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + e.target.id;
$.get(url,function(d){
$("input[name='json_name']").val(d.name);
$("input[name='json_country']").val(d.country);
$("input[name='json_start']").val(d.date_start);
$("input[name='json_end']").val(d.date_end);
$("input[name='json_duration']").val(d.duration);
$("input[name='json_description']").val(d.description);
},'json');
});
Obviously you have to change
$('.myButtonClass')
here you have to use the class or id of the button you want to bind the action to.
I'm creating a checkout system. I have three parts to it:
Shipping info
Payment info
Order confirmation
I'm trying to figure out a way that when the customer enters their shipping information, that data can be echo'd out onto my order confirmation part, so they can confirm that is where they want it shipped to.
The way I designed my checkout system is that all three parts are on the same page. Only one part shows at once and the others are hidden until the customer would click 'Proceed to xxxx'. When they click that Proceed button, nothing is being sent. It is just taking the div and showing it and hiding the previous div. Nothing is sent until when the customer clicks Submit order on the confirmation div.
I validate the fields and assigned them to variables so I can post the shipping and product info into my db.
if($validation->passed()) {
if(isset($_POST['create'])){
$fullname = trim( $_POST['customer_name'] );
$streetline1 = trim( $_POST['streetline1'] );
$streetline2 = trim( $_POST['streetline2'] );
$city = trim( $_POST['city'] );
$state = trim( $_POST['state'] );
$zipcode = trim( $_POST['zipcode'] );
$phone_number = trim( $_POST['phone_number'] );
$email = ( $_POST['email'] );
//etc...
Shipping Information Section:
<div class="shippinginfocontainer">
<span class="summarytitle">
<p>Enter Shipping Information</p>
</span><br>
<div class="center">
<div class="field">
<label class="paddingleft" for="fullname">Full Name</label>
<div class="center">
<input type="text" class="biginputbarinline" name="fullname" value="<?php echo escape(Input::get('firstname')); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline1">Street Line 1</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline1" value="<?php echo escape($user->data()->streetline1); ?>" required>
</div>
</div>
<div class="field">
<label class="paddingleft" for="streetline2">Street Line 2</label>
<div class="center">
<input type="text" class="biginputbarinline" name="streetline2" value="<?php echo escape($user->data()->streetline2); ?>">
</div>
</div>
<div class="field">
<label class="paddingleft" for="city">City</label>
<div class="center">
<input type="text" class="biginputbarinline" name="city" value="<?php echo escape($user->data()->city); ?>" required>
</div>
</div>
</div>
<div class="formleftcenter">
<div class="field">
<label for="state">State</label>
<input type="text" class="mediuminputbar" name="state" value="<?php echo escape($user->data()->state); ?>" required>
</div>
<div class="field">
<label for="Phone Number">Phone Number</label>
<input type="text" class="mediuminputbar" name="Phone Number" value="<?php echo escape($user->data()->phone_number); ?>">
</div>
</div>
<div class="formrightcenter">
<div class="field">
<label for="zipcode">Zip Code</label>
<input type="text" class="mediuminputbar" name="zipcode" value="<?php echo escape($user->data()->zipcode); ?>" required>
</div>
<div class="field">
<label for="email">Email</label>
<input type="text" class="mediuminputbar" name="email" value="<?php echo escape($user->data()->email); ?>" required>
</div>
</div>
<div class="clear">
<button class="checkoutbutton" id="button2">Proceed to Payment Information</button>
</div>
</div>
I won't add my payment part as it is irrelevant to this question.
Then this is the relevant part of the Confirmation part. I wasn't sure how to do this, so I just wrote in echo's to show what I am trying to do.
<div class="confirmshippinginfo">
<p>Shipping to:</p>
<p><?php echo $fullname; ?></p>
<p><?php echo $streetline1; ?></p>
<p><?php echo $streetline2; ?></p>
<p><?php echo $city . $state . $zipcode; ?></p>
</div>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input class="widebutton" type="submit" value="Place Your Order">
Is there a way to do this with keeping this all on the same page? I really do not want to have multiple pages for this and I like the way I have all of this formatted. I just can't figure out this part.
You could possibly use AJAX via serialize() of your form when you click a review button (as Matthew Johnson suggested). Second idea is something like this where you copy from one input to another, in a different part of your page. It would take a bit more work to set up than something like AJAX because you are basically duplicating a form. Using .html() inside a div or span placeholder would probably work too:
HTML:
<input type="text" class="copy-from" data-copy="name" name="name" />
<input type="text" class="this-elem" id="name" disabled />
CSS
.this-elem {
border: none;
font-size: 18px;
color: #333;
}
jQuery
$(document).ready(function() {
$(".copy-from").keyup(function() {
var ElemId = $(this).data('copy');
$("#"+ElemId).val($(this).val());
});
});
Demo
http://jsfiddle.net/fh5kfhtm/4/
EDIT: AJAX/PHP Solution
<!-- This is the placeholder for the data after submission -->
<div id="final"></div>
<!-- FORM, well really simplified form -->
<form id="orderform" method="post" action="process.php">
<input type="hidden" name="order_form" />
<input type="text" name="address" />
<!--
This triggers the ajax (you would use your
"Proceed to Order Confirmation" button)
-->
<div id="confirm">CONFIRM</div>
<input type="submit" name="submit" value="ORDER" />
</form>
new.php
File name/path must match what's in the AJAX url
<?php
if(isset($_POST['order_form'])) {
print_r($_POST);
exit;
}?>
jQuery AJAX
<!-- GET THE LIBRARIES (YOU SHOULD ALREADY HAVE THEM) -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#confirm").click(function() {
$.ajax({
// This is where you need the right path to the new php file
url:'/path/to/new.php',
type: 'post',
data: $("#orderform").serialize(),
success: function(response) {
$("#final").html(response);
}
});
});
});
</script>