I'm creating a WordPress theme in which I need to copy some values to a Gravity Forms page with dynamically populated fields. I'm loading options (air-conditioning power) as an ACF repeater field saved together with price of this particular unit. I need to copy this price based on the checked radio into a static div field plus into a hidden input field so it can be used in the form.
Below is the simple structure I need to achieve and a code I have so far. All I need is to copy the price saved somewhere (can be a PHP varible or anything) to a div (probably by jQuery) and into a hidden field in the same time and change it dynamically based on users choice.
<form class="order" action="<?php echo get_permalink(26); ?>">
<div>
<?php if($power) { ?>
<div class="power">
<?php $power_counter = 1; while(have_rows('power')) { the_row();
$power= get_sub_field('power');
$price = get_sub_field('price');
?>
<input type="radio" name="power" id="power<?php echo $power_counter; ?>" value="<?php echo get_the_title() . ' ' . $power; ?>"<?php if($power_counter == 1) { echo "checked"; }; ?>><label for="power<?php echo $power_counter; ?>"><?php echo $power; ?></label>
<input type="hidden" name="price_wo_vat" id="price<?php echo $power_counter; ?>" value="<?php echo $price; ?>">
<div id="price<?php echo $power_counter; ?>" class="price"><?php echo $price. __(' CZK','klima'); ?></div>
<?php $power_counter++; }; ?>
</div>
<?php }; ?>
<input type="number" name="pcs" value="1" min="1" max="99">
<input type="submit" value="<?php _e('Order','klima'); ?>">
</div>
$(document).ready(function() {
var selPrice = parseInt($('#selected_price').val()),
chosenPrice = parseInt($('input[name="power"]:checked').val()),
qty = parseInt($('input[name="pcs"]').val()),
initTotal = calcTotal(chosenPrice, qty);
$('#total').text(initTotal);
$('input[name="pcs"]').on('change', function() {
var myQty = $(this).val(),
chooseQty = parseInt($('input[name="power"]:checked').val()),
newQty = calcTotal(chooseQty, myQty);
$('#total').text(newQty);
});
$('input[name="power"]').on('click', function() {
var myPrice = $(this).val(),
myQty = parseInt($('input[name="pcs"]').val()),
newTotal = calcTotal(myPrice, myQty);
$(this).attr('checked',true);
$('#total').text(newTotal);
});
});
function calcTotal(price, qty) {
var total = price * qty;
return total
}
.power {
margin-bottom: 10px;
}
.total-container {
padding: 5px;
background-color: #DDD;
width: 50px;
margin-bottom: 10px;
}
input[name='pcs'] {
padding: 5px;
text-align: center;
width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="order" action="#">
<div>
<div class="power">
<!-- #Power 1 -->
<input type="radio" name="power" id="power1" value="62" data-xvat="80" checked="true">
<label for="power1">Option 1 - £62</label>
<br>
<!-- #Power 2 -->
<input type="radio" name="power" id="power2" value="114" data-xvat="160">
<label for="power2">Option 2 - £114</label>
<br>
<!-- #Power 3 -->
<input type="radio" name="power" id="power3" value="139" data-xvat="240">
<label for="power3">Option 3 - £139</label>
<br>
</div>
<div class="total-container">£<span id="total"></span></div>
<input type="hidden" name="selected_price" id="selected_price" value="0">
<input type="number" name="pcs" value="1" min="1" max="99">
<input type="submit" value="Order">
</div>
Related
Imagine I have 3 data's in my room_table and the column is room_id, image, room_name then I'm going to display the data of my room_table in my html code.
PS: Ignore the text_checkin, text_checkout first. I'm going to explain after the code.
HTML code:
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
I have table named reservation then the columns are room_id, checkin, checkout.
the 3 data's in my room_table will display. Then the textbox, and the button will be thrice cause of the while loop. Then imagine I clicked the button submit in the 2nd row, then the 2nd row id should insert on my table reservation but the problem is only first row id is inserting on table reservation
Here's my script:
<script type="text/javascript">
function chk()
{
var roomid = document.getElementById('text_roomid').value;
var checkin = document.getElementById('text_checkin').value;
var checkout = document.getElementById('text_checkout').value;
var dataString = 'roomid='+ roomid + '&checkin=' + checkin + '&checkout=' + checkout;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>
PHP code: server.php
$roomid = $_POST['roomid'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$query = "INSERT INTO reservation (room_id, checkin, checkout) values ('$roomid', '$checkin', '$checkout')";
mysqli_query($db, $query);
echo "success!";
please help me out of this problem, tyia!
The error lies within your while loop. Your printed elements will all have the same id's. When your function is looking for an id to get the value, it will always return the first that it finds, no matter how many instances there are of that id. So you're having conflicting id's. id's should always be unique.
What you could do to avoid this, is to declare a counter outside your while loop and increment it inside your while loop, then attach that onto your id. In that way, you will always have a unique id to parse along.
For instance:
<?php $count=0; while($row = mysqli_fetch_array($rooms)) { $count++;?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" id="text_checkin<?php echo $count; ?>">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" id="text_checkout<?php echo $count; ?>">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" id="text_roomid<?php echo $count; ?>" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg<?php echo $count; ?>"></p>
</div>
<?php } ?>
However, you will then need to change your logic for how you fetch the data from each element, as you don't really know what their id's could end up being due to the incrementor. It's not static.
If you need any further help, let me know.
As Martin said there is the problem with the id's so you have to change the logic a little bit.
$db = mysqli_connect('xxxxxx', 'xxxx', '', 'xxxx');
$rooms = mysqli_query($db, "SELECT * FROM rooms ORDER BY id ASC;");
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
<?php while($row = mysqli_fetch_array($rooms)) { ?>
<div>
<form >
<img src="upload/<?php echo $row['image']; ?>" style="width: 20%;">
<label>Check IN</label>
<input type="date" name="text_checkin" class="text_checkin">
<br>
<label>Check OUT</label>
<input type="date" name="text_checkout" class="text_checkout">
<br>
<label>Room ID</label>
<input type="text" name="text_roomid" class="text_roomid" value="<?php echo $row['id']; ?>">
<br>
<input type="submit" value="submit" name="submit" id="submit" onclick="return chk()">
<br><br><br>
</form>
<p id="msg"></p>
</div>
<?php } ?>
Then you can get the values individually and pass them as array to the server.
<script type="text/javascript">
function chk()
{
var roomidArr = $(".text_roomid");
var checkinArr = $(".text_checkin");
var checkoutArr = $(".text_checkout");
/*
You can get value of each element as;
for(var i = 0; i < roomidArr.length; i++){
console.log($(roomidArr[i]).val());
}
*/
//var dataString = Apply your logic here as;
$.ajax({
type: "post",
url: "server.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html("success");
}
});
return false;
}
</script>
Ive saved form data with ajax and php, reusing the data from the database.
However the way I am approaching this is different, there is no database, so some insight would be great.
I am emailing form data, all the data is just simple checkboxes, the values are either 0 or 1. When the user refreshes the page id like to keep the checked values.
I guess without a database I would need to use cookies, and the only way to avoid cookies would be ajax and a database (strictly my logic, not sure if true), this is why I am asking, I just want a simple solution.
Form snippet:
<input name="sharks" type="hidden" value="0">
<input name="sharks" type="checkbox" value="1" id="sharks" '.$VALUE ? ' checked="checked"' : ''.'>
The php part of that input is shaky, Id like to question whether the value is 0 or 1, if its 1 then its checked if its 0 then empty.
Getting it from the database would be easier but not so sure since there is no database, Im guessing cookies would come into place.
Sorry if this last part is shaky but im a little unsure and dont know where to look.
Using Sessions:
session_start();
if(isset($_POST['submit'])) {
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form
<form action="<?php the_permalink(); ?>" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<?php
if ($_SESSION['value'] == 1) {
$checked = 'checked="checked"'; }
?>
<li>
<input name="personalization_result[memory_0]" type="hidden" value="0">
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" value="0">
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" <?php $checked ?> >
</li>
<li>
<input name="personalization_result[memory_2]" type="hidden" value="0">
<input name="personalization_result[memory_2]" type="checkbox" value="1" id="personalization_result_memory_2" <?php $checked ?> >
</li>
This code stores the data in a session:
<?php
session_start();
if(isset($_POST['submit']))
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
}
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
print ' checked="checked"';
}
print ">";
?>
<br>
<input type="submit" name="submit" value="Save" />
</form>
Worked for me, keeping the checkbox checked after I closed and opened the browser again. After some testing I added a rather complex if to avoid the undefined variable notice. Now the set part seems robust.
You can either use session or cookie. Basically you will access using $_COOKIE or $_SESSION. I would rather say that this is easier than using a database.
For cookies have a look at setcookie (http://www.php.net/setcookie)
For sessions: http://php.net/manual/en/book.session.php
I would use local storage or session storage, this is a client side memory storage location that persists even if the page is refreshed, it is integrated into html5.
Here is a nice tutorial about it:
http://www.w3schools.com/html/html5_webstorage.asp
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Persist checkboxes 1</title>
<script>
window.jQuery || document.write("<script src='jquery-.1.1.js'><\/script>");
</script>
<script>
$(document).ready(function()
{
$('#me').click(function()
{
var seloption = $('input[type="checkbox"]:checked');
if (seloption.length > 0)
{
var abc = seloption.length + "checked \n";
//alert(abc);
i = 0;
seloption.each(function()
{
abc = abc + $(this).text(seloption[i]) + "<br>";
}
);
$('#msg').html(abc);
}
}
);
}
);
</script>
</head>
<body>
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<div>
<label for="option4">Option 4</label>
<input type="checkbox" id="option4">
</div>
<div>
<label for="option5">Option 5</label>
<input type="checkbox" id="option5">
</div>
<div>
<label for="option6">Option 6</label>
<input type="checkbox" id="option6">
</div>
<div>
<label for="option7">Option 7</label>
<input type="checkbox" id="option7">
</div>
<div>
<label for="option8">Option 8</label>
<input type="checkbox" id="option8">
</div>
<div>
<label for="option9">Option 9</label>
<input type="checkbox" id="option9">
</div>
<button type="button" id="me">Submit</button>
<div id="msg">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script>
$(":checkbox").on("change", function() {
var checkboxValues = {};
$(":checkbox").each(function() {
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, {expires: 1, path: '/'});
});
function repopulateCheckboxes() {
var checkboxValues = $.cookie('checkboxValues');
if (checkboxValues) {
Object.keys(checkboxValues).forEach(function(element) {
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
</script>
</body>
</html>
Hi I'm trying to get a dinamically input added with Jquery, but when I try to get the code it's not working
The code in codeigniter catch all POST but less the one added by jquery
here is the code:
<script type="text/javascript">
$(document).ready(function(){
var value = parseFloat($("#subtotal").val());
$('.subtotal').html(value);
$('#subtotal').val(value);
$('input[name="phprop"]').change(function(event){
if($('input[name="phprop"]:checked').val() == 'Yes'){
$('#sections').show();
}else if($('input[name="phprop"]:checked').val() == 'No'){ $('#sections').hide();}
});
$('input[name="xsst"]').change(function(event){
if($('input[name="xsst"]:checked').val() == 'Yes'){
$('#xtraphotos').show();
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo('#xtrabox');
var num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i); i++;
}else if($('input[name="xsst"]:checked').val() == 'No'){
$('#xtraphotos').hide();
$('#xtraphotos input[type="text"]').remove();
var num = value - 9.95 * (i - 1);
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(0);
i = 1;
}
});
var scntDiv = $('#xtrabox');
var i = 1;
$('#addScnt').live('click', function() {
$('<input type="text" name="extraid'+i+'" id="extraid'+ i +'" style="width:80px;margin-left:4px;"/>').appendTo(scntDiv);
num = value + 9.95;
value = parseFloat(num.toFixed(2));
$('.subtotal').html(value);
$('#subtotal').val(value);
$('#extrass').val(i);
i++;
return false;
});
});
</script>
Here is the HTML
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
Here is the Codeigniter code:
if($_POST['extrass'] !=0){
for($i=1;$i<=$_POST['extrass'];$i++){
$names = "extraid".$i;
$extras .= $_POST[$names];
if($i!=$_POST['extrass']){
$extras .= "-";
}
}
Here is the complete HTML (Just the form Section):
<?php echo form_open_multipart(base_url() . 'purchase/confirmation')?>
<p style="float:left">Image ID of the Photos for your Website</p><div style="float:left;margin: 13px 0 0 110px;width: 450px;"><?php
if($idtype == 4){$x=3;}elseif($idtype == 1){$x=5;}elseif($idtype == 2){$x=10;}elseif($idtype == 3){$x=13;}
for($i=1;$i<=$x;$i++){?><input type="text" name="ssid[]" id="ssid_<?=$i?>" value="" style="width:80px; margin-left:4px;"/><?php }?></div>
</div>
<div style="margin-left: 50px;">
<label><b>Do you need more photos for your web?</b> </label>Yes<input type="radio" name="xsst" id="xsst" value="Yes"/>No<input type="radio" name="xsst" id="xsst" value="No"/> (Each aditional photo has a cost of <b>$9.95</b>)
<div id="xtraphotos" style="display:none;">Add another picture box<div id="xtrabox"></div></div></div>
<br />
<div id="choose_your_template" style="background-image:url(<?=base_url()?>images/step_4.png)"><div style="padding-left:5px; float:left">
<span style=" position: relative; top: 14px; left: 210px; font-size: 18px; color: gray; ">Step 4: Do you have Photos? Upload the pictures for your website.</span></div>
</div>
<div style="margin-left: 50px;">
<label>Do you have photos of your property? </label>Yes<input type="radio" name="phprop" id="phprop" value="Yes"/>No<input type="radio" name="phprop" id="phprop" value="No"/><br />
<div id="sections" style="display:none;">
<p>Upload the photos in the theme that they should be used. The photos should be in jpge.format. Otherwise the system will not accept. them.</p><br/>
<?php
if($idtype == 4){$x=1;}elseif($idtype == 1){$x=3;}elseif($idtype == 2){$x=4;}elseif($idtype == 3){$x=5;}
for($i=1;$i<=$x;$i++){?>
<label>Section</label><select name="section[]" id="section"><option value="">Choose Section</option><option value="home">Home</option><option value="about-us">About Us</option><option value="contact-us">Contact Us</option></select><?php for($j=1;$j<=4;$j++){?><input type="file" name="userphoto<?=$i?><?=$j?>" /><?php }?><br /> <br />
<?php }?>
<p>I certify that the photos that i am uploading for the website development are of my entire property and that I have all the copyrights.</p></div>
</div><br />
<input type="hidden" id="domain" name="domain" value="<?=$domain?>" />
<input type="hidden" id="payment_plan" name="payment_plan" value="<?=$poption?>" />
<?php if($ownamedomain){?>
<input type="hidden" name="ownamedomain" id="ownamedomain" value="<?=$ownamedomain?>" />
<?php }?>
<input type="hidden" name="idtype" id="idtype" value="<?=$idtype?>" />
<input type="hidden" name="templateid" id="templateid" value="<?=$templateid?>" />
<input type="hidden" name="extrass" id="extrass" value="0" />
<input type="hidden" name="subtotal" id="subtotal" value="<?=$subtotal?>" />
<div style="padding-left:45px; padding-top:15px;">
<hr style=" width: 868px; margin: 0 0 16px; "/>
<div align="center">
<p>Subtotal: USD$<span class="subtotal"><?=$subtotal?></span> </p></div>
</div>
<div style="background:url(<?=base_url()?>images/bottombar.png) no-repeat;display: block;height: 16px;margin: 0 36px 10px;width: 902px;"></div>
<input type="submit" name="continue" id="continue"/><input type="button" value="Back" onClick="history.back();" class="back">
</div>
Your HTML have a tag form?
When.you not put forms elements inside a form, onload, some brownser add a form to correct code syntax... But when you add nes elements using DOM, maybe this elements not include inside this form...
Ok here is my problem, and all of my 'dirty' code. This isn't my production code but just trying to make it work at the moment.
Basically what I need is when a user selects the Not Ok radio button it displays the textarea for that unique set which it doesn't do right now when I select Not Ok it gives the textarea's for all the entries which right now is about 13 sets of questions that get generated dynamically from a mysql database at the moment. I have a feeling it has to do something with unique id's that are either in the wrong place in my code now, or just simply aren't there at all. Any help is appreciated greatly.
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT * FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;">
<fieldset data-role="controlgroup">
<legend><?php echo $q_title; ?>:</legend>
<input type="radio" name="help[]" id="checkbox-1a" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$(":radio:eq(1)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$(":radio:eq(0)").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
<fieldset data-role="fieldcontain">
<label for="<?php echo $q_title; ?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_a[]" id="<?php echo $q_title; ?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
The other 2 answers are ways to fix your issue. As a side, here is possibly why it is happening. When you are using -
$(":radio:eq(1)").click(function()
$(":radio:eq(0)").click(function()
You are using a click listener that just checks for if 'any' radio button with that index position was clicked on your page. So any button with 1 index position will make every $(":radio:eq(1)").click(function() execute.
Edit -
You would want to change your radio button ids, as (1) they will not be unique as you repeat them with each while() loop, and (2) you could use it to check if that specific radio buttton was clicked.
Try changing it to -
...
<input type="radio" name="help[]" id="checkbox-1a-<?php echo $q_id; ?>" value="Ok" />
<label for="checkbox-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-2a-<?php echo $q_id; ?>" value="Not Ok" />
<label for="checkbox-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?php echo $q_id; ?>" style="display:none;">
<script>
$(document).ready(function(){
$("#checkbox-2a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").show(500);
});
$("#checkbox-1a-<?php echo $q_id; ?>").click(function(){
$("#hidden_text-<?php echo $q_id; ?>").hide(500);
});
});
</script>
The easiest way that I have found to show hide elements based off of radio values is to serve up an onchange event based on the id of the element (which you already have). In your case, since you only have two radios based off the same name, the easiest way is a simple if/else statement. Something like:
<script type="text/javascript">
$(function(){
$('#checkbox-1a').change(function(){
if($(this).attr('checked')){
$('#hidden-text-<?php echo $q_id;?>').hide(500);
}else{
$('#hidden-text-<?php echo $q_id;?>').show(500);
}
});
});
</script>
Where we state when #checkbox-1a is changed: if the element is checked (selected), then do something (in your case hide something), otherwise do something else (in your case show something).
Try something like:
<div data-role="collapsible" data-theme="b" data-content-theme="c">
<h3>Vehicle Check Information</h3>
<?php
$query = mysql_query("SELECT id,title FROM vehicle_q");
while($row = mysql_fetch_array($query)) {
$q_title = $row['title'];
$q_id = $row['id'];
?>
<div data-role="fieldcontain" style="border:0;" class="groupings">
<fieldset data-role="controlgroup">
<legend><?=$q_title?>:</legend>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-1a" value="Ok" />
<label for="checkbox-<?=$q_id?>-1a">Ok</label>
<input type="radio" name="help[]" id="checkbox-<?=$q_id?>-2a" value="Not Ok" />
<label for="checkbox-<?=$q_id?>-2a">Not Ok</label>
</fieldset>
<div id="hidden_text-<?=$q_id?>" class="hiddenText" style="display:none;">
<fieldset data-role="fieldcontain">
<label for="<?=$q_title?>_t">Explain the Deficiency(If any):</label>
<textarea name="text_<?=$q_id?>_a[]" id="<?=$q_title?>_t"></textarea>
</fieldset>
</div>
</div>
<input type="hidden" name="q_title1[]" value="<?php echo $q_title; ?>" />
<?php
}
?>
</div>
<script>
$(document).ready(function(){
$(".groupings input:radio").click(function(){
if (this.value == "Ok") {
$(this).parent().next('.hiddenText').show(500);
} else {
$(this).parent().next('.hiddenText').hide(500);
}
});
});
</script>
This is untested, but the script only needs to be declared once and it will apply to the rest relative to the radio button.
I'm working on a form that lets folks choose their preferred methods of contact. Among other things, the form consists of 9 checkboxes (3 sets of three) that I'm trying to store in my database as JSON.
Here's the pertinent parts of the form...
<h1 style="padding-top:25px;">Communication Preferences</h1><hr />
<div class="onethird contactprefs" style="width: 28%">
<h4>Preferred Method</h4>
<p>From time to time, we might need to contact you regarding our service. Which mode of contact would you prefer?</p>
<p>
<input type="checkbox" name="preferred[]" value="p" style="display: inline;" />Phone <!-- make these tooltips -->
<br />
<input type="checkbox" name="preferred[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="preferred[]" value="s" style="display: inline;" />SMS
</p>
</div>
<div class="onethird contactprefs" style="width: 28%; border-left: solid 1px #cdcdcd; border-right: solid 1px #cdcdcd; padding-left: 18px; padding-right: 15px;">
<h4>Weather Delays</h4>
<p>We don't mess with Mother Nature, and sometimes she forces us to cancel service. If that happens, how should we inform you?</p>
<p>
<input type="checkbox" name="weather[]" value="p" style="display: inline;" />Phone
<br />
<input type="checkbox" name="weather[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="weather[]" value="s" style="display: inline;" />SMS
</p>
</div>
<div class="onethird contactprefs" style="width: 28%">
<h4>Holiday Reminders</h4>
<p>If you'd like us to send you reminders about interruptions in service due to holidays, just choose your preferred method below.</p>
<p>
<input type="checkbox" name="holiday[]" value="p" style="display: inline;" />Phone
<br />
<input type="checkbox" name="holiday[]" value="e" style="display: inline;" checked />Email
<br />
<input type="checkbox" name="holiday[]" value="s" style="display: inline;" />SMS
</p>
</div>
<!-- end contact preferences -->
As I mentioned, I need to take the data from these checkboxes and convert them into a well formed JSON string.
Here's what I'm doing, but it seems awfully messy. Tell me theres a better way...
/* THERE MUST BE A BETTER WAY TO DO THIS */
// get the preferred data
$preferred = $this->input->post('preferred');
if(in_array('p',$preferred)){
$pref['p'] = 1;
}else{ $pref['p'] = 0;}
if(in_array('e',$preferred)){
$pref['e'] = 1;
}else{ $pref['e'] = 0;}
if(in_array('s',$preferred)){
$pref['s'] = 1;
}else{ $pref['s'] = 0;}
// get the weather data
$weather = $this->input->post('weather');
if(in_array('p',$weather)){
$wea['p'] = 1;
}else{ $wea['p'] = 0;}
if(in_array('e',$weather)){
$wea['e'] = 1;
}else{ $wea['e'] = 0;}
if(in_array('s',$weather)){
$wea['s'] = 1;
}else{ $wea['s'] = 0;}
// get the holiday data
$holiday = $this->input->post('holiday');
if(in_array('p',$holiday)){
$hol['p'] = 1;
}else{ $hol['p'] = 0;}
if(in_array('e',$holiday)){
$hol['e'] = 1;
}else{ $hol['e'] = 0;}
if(in_array('s',$holiday)){
$hol['s'] = 1;
}else{ $hol['s'] = 0;}
$contact_prefs = array('preferred' => $pref,'weather' => $wea,'holiday' => $hol);
$contact_prefs = json_encode($contact_prefs);
Thanks in advance for the insight.
One idea to make it more automatic (untested):
$contact_prefs = array();
$groups = array('preferred', 'weather', 'holiday'); // checkbox groups
foreach($groups as $group) {
$preferences = array('p' => 0, 'e' => 0, 's' => 0); // create default array
$values = $this->input->post($group); // get the checked values for a group
foreach($values as $value) {
$preferences[$value] = 1; // if box is checked, set value to 1
}
$contact_prefs[$group] = $preferences;
}
$contact_prefs = json_encode($contact_prefs);
Of course this only works, if the three checkbox groups have the same values.