extra input added by jquery doesn't work - php

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...

Related

Copy a value based on radio input status

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>

How to compare form data in php

HTML/PHP:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" name="imageval" />
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
PHP:
$arrImg = array("img1", "img2", "img3", "img4", "img5", "img6");
$arrImgText = array("56", "342", "34534", "12", "444", "652");
$imgval = trim(strip_tags(stripslashes($_POST['imageval']))); //get the image source that was displayed in the form
$numval = trim(strip_tags(stripslashes($_POST['numval']))); //get the number that the user entered
//if ({arrImg[imgval] == arrImgText[numval]}) {
//do something;
//}
The image that is displayed in the form has some numbers. When the user hit send, I would like to compare the number that was entered that was displayed in the image and compare.
How can I do that.
In your form, create hidden input:
<input type="hidden" name="imageval" value="img1" />
In your PHP file you can have now two $_POST variables:
$secretImg = $_POST['imageval'];
$token = $_POST['numval'];
Now you need to find key of image:
$imgKey = array_search($secretImg, $arrImg);
Using the key value, check the proper token:
if ($arrImgText[$imgKey] === $token) {
// Token is valid
}
You can't pass images because it is not an input element, what you could do is use a hidden input element instead:
<form method="post" name="contact" id="frmContact" action="sM.php">
<img id="main-img" src="theimage/img1.png" />
<input type="hidden" val="img1" name="imageval" /> <!-- THIS IS THE HIDDEN INPUT ELEMENT THAT WILL BE SUBMITTED -->
<div style="clear: both; padding: 10px 0 0 0; overflow: hidden;">
Please enter the number(s) from the image above: <input type="text" id="tNum" placeholder="Enter Number(s)" name="numval" />
</div>
<input type="submit" value="Send" id="submit" name="submit" class="submit_btn" />
</form>
In order to search the image value in the array using PHP, you can use in_array:
if( in_array( $_POST['imageval'], $arrImgText ) {
echo "Image found";
}
Edit: To get the specific index, use the example in #GrzegorzGajda'a answer

JSON causes memory error

I have two file. One is index.php and the other is display.php.
Index.php contains a form and after submitting, it generates a json value and displays that in a textarea, so I might edit before I press the "generate" button and it redirects me to the display.php where a for loop generates a html template according to the posted son data. It works perfectly with up to 3 item, but if I use 4 or more, it drops me a fatal error with memory limit. As I still got errors after increasing the limit, I tried the following on the display.php:
ini_set('memory_limit', '-1');
set_time_limit(0);
After this, it drops me an error 503 - service unavailable.
I don't know what to do, I am asking your help.
index.php:
<meta charset="utf-8">
<style>
pre, textarea { background-color:#31495D;min-height:300px;color:white;margin-bottom:50px;padding:25px;width:100%;display:block;border-bottom:5px solid #A058B3; }
.submit { padding:15px;background-color:green;color:white;border:none;font-size:12px;width:150px;margin:0 auto;margin-top:15px;margin-bottom:15px }
</style>
<?php
$json = json_encode($_POST, JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE);
echo "
<h2>JSON for template</h2>
<form action='display.php' method='post'>
<textarea name='json'>$json</textarea>
<input class='submit' type='submit' value='Generate Template'>
</form>
";
$json = json_decode($json, true);
?>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="url[]" placeholder="http://www.example.com/"/><input type="text" name="name[]" placeholder="Name"/><input type="text" name="subtext[]" placeholder="Subtext"/><input type="text" name="image[]" placeholder="Image URL"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<label>Title of Block <input type="text" name="title"></label><br>
<label>Heading of Block <input type="text" name="heading"></label><br><br>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="url[]" placeholder="http://www.example.com/"/><input type="text" name="name[]" placeholder="Name"/><input type="text" name="subtext[]" placeholder="Subtext"/><input type="text" name="image[]" placeholder="Image URL"/></div>
</div>
<br><br>
<input type="submit" value="Generate Code">
</form>
And the display.php
<?php
$json = json_decode($_POST['json'], true);
$c = count($json);
$i = 0;
$rows = 3;
$content = "<table>";
for($i=0; $i < count($json["name"]); $i++) {
$content .=
'<td width="226" valign="top" style="padding:5px;padding-bottom:20px;" class="m-stack m-pad-b">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:22px;padding-bottom:5px; mso-line-height-rule:exactly; line-height: 18px; padding-top: 8px;">
<a href="'.$json['url'][$i].'" target="_blank" style="text-decoration:none;color:#0896ff; display:block;">
'.$json['name'][$i].'<br><span style="color: #7d90a6; font-size: 14px;">'.$json['subtext'][$i].'</span>
</a>
</td>
</tr>
<tr>
<td background="'.$json['image'][$i].'" width="226" height="226" valign="top" style="background-size:cover; background-position:center center; border-radius:6px 6px 0 0;" class="m-ufi-bg">
<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:226px;height:226px;">
<v:fill type="frame" src="'.$json['image'][$i].'" color="#7bceeb" />
</v:rect>
<![endif]-->
</td>
</tr>
</table>
</td>
';
if($i == 3) { $content .= '</tr><tr>'; unset($i); $i == 0; }
}
echo "</table>";
echo $content;
This is just an experiment for me, any suggestion / critique is appreciated. Thanks in advance.
You are reseting $i to 0 so it never becomes greater than count($json) and your for loop becomes infinite

JQuery/Javascript select-all by clicking link or selecting "select-all" from a checkbox dropdown

I have a private messaging system and would like to have about 4-5 links above the inbox where a user can click if they want to "select all", "none", "favourite", "read" or "unread" messages.
How would I do this using jquery/javascript? Are there any tutorials about that explain this thoroughly? I am not that great with javascript but I'm a quick learner.
I originally really wanted to do a gmail style checkbox drop down but it is proving to be quite difficult and I think having links across of the message inbox would be more user friendly..
I hacked together a simple example of how I would do this, you will have to tailor it to your needs, but it should get you started.
Just try this (make sure you change it to match your jquery library):
<html>
<body>
<div class="mesg" id="mesg1" read="1" favorite="0">
<input type="checkbox" name="check1">
message 1 info
</div>
<div class="mesg" id="mesg2" read="1" favorite="1">
<input type="checkbox" name="check2">
message 2 info
</div>
<div class="mesg" id="mesg3" read="0" favorite="0">
<input type="checkbox" name="check3">
message 3 info
</div>
<input type="button" value="select read" id="select_read" />
<input type="button" value="select favorite" id="select_fav" />
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
$("#select_read").click(function() {
$("div.mesg input[type=checkbox]").attr("checked", false);
$("div.mesg[read=1] input[type=checkbox]").attr("checked", true);
});
$("#select_fav").click(function() {
$("div.mesg input[type=checkbox]").attr("checked", false);
$("div.mesg[favorite=1] input[type=checkbox]").attr("checked", true);
});
});
</script>
</body>
</html>
My solution on jsFiddle: http://www.jsfiddle.net/pereskokov/sYe4S/6/
HTML:
<p id="links">
Select all,
none,
unread,
read,
favourite
</p>
<p id="messages">
<label class="unread">
<input type="checkbox" name="message" value="1" class="unread" /> Hi, man!
</label><br/>
<label class="read fav">
<input type="checkbox" name="message" value="2" class="read fav" /> Cute kittens, look
</label><br/>
<label class="read">
<input type="checkbox" name="message" value="3" class="read" /> Pysh-pysh, ololo
</label><br />
<label class="unread">
<input type="checkbox" name="message" value="4" class="unread" /> New important task!
</label><br/>
</p>
CSS:
label.unread {
font-weight: bold;
}
label.fav {
background-color: #F5E942;
}
a.pseudo {
text-decoration: none;
border-bottom: 1px dashed #4998C9;
color: #4998C9;
}
a.active {
background-color: #4998C9;
color: white;
padding: 0 0.2em;
}
jQuery:
$('#links').delegate('a', 'click', function(ev) {
// reset all checkboxes
$('input:checkbox').attr('checked', false);
// get info, what is the user choice
whichMessages = $(this).attr('id');
// do our main work - select checkboxes
switch (whichMessages) {
case 'all':
$('input:checkbox').attr('checked', true);
break;
case 'read':
$('input:checkbox.read').attr('checked', true);
break;
case 'unread':
$('input:checkbox.unread').attr('checked', true);
break;
case 'fav':
$('input:checkbox.fav').attr('checked', true);
break;
};
// add some user-frendly markup
$('#links a').removeClass('active');
$(this).addClass('active');
// and standart action to prevent standart link click event
ev.preventDefault();
});
Excuse me, I am the man, who gave you fish, but did not teach you to catch fish.
Use jquery, then
$(".parent").find("input[type=checkbox]").each(function() {
$(this).checked = true;
});
Obviously this is just an example and you won't be able to simply copy paste this, but this should get you started.

Tell me there's a better way to turn these checkboxes into JSON

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.

Categories