Enable and Disable array of textBoxes by check boxes - php

i have been working on this code !
and i couldn't done it right .
what i want is the text box to be enabled when the corresponding checkbox is checked .
but when apply the function nothing happens :(
in my code the text and check boxes are dynamically generated from database using php .
here is my code :
<div><div class="ac-container">
<div id="accordion">
<?php
$qry="SELECT * FROM catalog";
$result= mysql_query($qry);
if($result){
while($info = mysql_fetch_array($result))
{
print "<h3> cat:".$info['name']."</h3><div>";
$qryitem="SELECT * FROM item WHERE Id=". $info['Cid'];
$resultitem=mysql_query($qryitem);
if($resultitem){
?>
<form name="form1" id="form" method="post" action="manage_item_action.php" >
<?php
while($info=mysql_fetch_array($resultitem))
{
?>
<input type="checkbox" id="checkB" name="op[]" value="<?php echo $info['Id'];?>" /> <?php echo $info['name'];?>
<label> Quantity <input disabled="disabled" id="textB" type="text"
name="Quantit[]" value="<?php echo $info['Quantity'];?>"/>
</label>
<script>
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++){
checkBoxes[i].onchange = function() {
textBoxes[i].disabled =!(this.checked);};
}
</script>
<br/>
<?php
}
}
else echo "There are no items.";
print "</div>";
}
}
?>
</div>
<input type="submit" value="update" name="submit"/>
<input type=reset value="clear"></td></tr> </form>

The problem you are having is that inside your event handler the variable i is not defined. To overcome this problem, you could add a property to each checkbox to save what index they are referring to:
checkBoxes=document.form1.elements['op[]'];
textBoxes=document.form1.elements['Quantit[]'];
for(var i=0 ; i<checkBoxes.length;i++)
{
checkBoxes[i].myIndex = i;
checkBoxes[i].onchange = function() {
textBoxes[this.myIndex].disabled =!(this.checked);
};
}
Other methods to solve this problem: http://www.howtocreate.co.uk/referencedvariables.html
Your code is still pretty messed up. For instance you are generating too many closing <div/>-tags with your first print-statement. I would suggest you just remove the PHP-code from your question, as the question is only related to html and javascript.
I would also suggest to use a library for manipulating DOM elements like jQuery.
When writing and debugging javascript, you should always make sure that you get error messages. "nothing happens" is a sign that you are just ignoring errors. For Firefox download the addon Firebug. Safari also has developer tools that you can activate in the settings. Using these tools will make it very easy to spot and solve problems like this.

Related

confused about basic find and replace app

I am trying to do a find and replace applicaiton the problem is that after cliked submit button all the text fields gets clean nothing displays on the screen What am i doing wrong
<?php
$offset=0;
if(isset($_POST['text'] ) && isset($_POST['searchfor']) && isset($_POST['replacewith'])){
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$searchLength=strlen($search);
if(!empty($text) && !empty($search) &&!empty($replace)){
while ($strpos= strpos($text,$search,$offset)){
echo $offset=$strpos+$searchLength;
}
} else {
echo "<script>alert('errorrrr')</script>";
}
}
?>
<form action="#" method="post">
<textarea name="text" id="" cols="30" rows="10"></textarea><br>
Search For:<br>
<input type="text" name="searchfor"><br>
ReplaceWith<br>
<input type="text"name="replacewith"><br>
<input type="submit" value="Fr..."></>
</form>
Regarding your form, you decided to submit to the same page.
Doing this, the page is obviously fully reloaded when submitted. Hence it is normal that what you typed in has disappeared.
If you want to see it again, you have to display you variables in the HTML code.
For example:
<?php
$myVar = "";
if(isset($_POST['myVar']){
$myVar = $_POST['myVar'];
}
?>
<form>
<input type="text" value="<?php echo $myVar;?>"/>
</form>
NB: I encourage you to filter the user entry.
Regards
there is problems in your code :
1 - echo $offset=$strpos+$searchLength; the echo can't be used in this format. insted use echo $offset; in next line for seeing offset values.
2 - if the text be like 'amir love persepolis' and search for 'amir' to replace it with 'all men's' you will have another issue, because you will have while ( 0 ) situation. think about this too!

Image upload script only works for latest <li></li> saved in DB

Below is a script to upload images and save them to the DB.
On one page of the website, there's a table and inside each <li></li>, there is an upload icon where users can add one image.
The issue is the image upload only works for the "highest" empty <li> on the table.
Here, "highest" means the latest <li> saved in the DB (table is sorted by TIME DESC).
For instance, if I want to upload an image to a random <li></li> on the page, once I select an image, nothing happens. But if I select the "highest" empty (empty = no image saved in DB) <li></li>, it works like a charm.
HTML:
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
<input class="upload" id="file" type="file" style="display:none" />
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
<img class="upload_icon" src="/upload_icon.png">
</form>
</div>
</li>
JAVASCRIPT (upload gets triggered as soon as one image is chosen):
<script>
$('.upload_icon').click(function(){
$(this).parent().find('.upload').click();
});
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
</script>
PHP:
<?php
include "includes/connnect.php";
$id = $_SESSION['id'];
$recipe_id = mysql_real_escape_string($_POST['recipe_id']);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$recipe_id= $_POST['recipe_id'];
//get image attributes
$add = query("UPDATE cookbook SET recipe_pic = '".$location."' WHERE recipe_id =
'$recipe_id'");
header(Location:"home.php");
}
?>
What's going here ?
There are many, many problems with your question. First of all the HTML you've posted is invalid. I suspect that your Javascript code has a problem with such invalid HTML. However, the following code has not (for your HTML code duplicated once for demonstration purposes):
NodeList.prototype.forEach = Array.prototype.forEach;
document.querySelectorAll('input[type="file"]').forEach(function (file) {
var click = function() {
file.click();
};
var change = function() {
console.log('change:', file.value);
};
file.form.querySelector('img').addEventListener('click', click);
file.addEventListener('change', change);
});
http://jsfiddle.net/eBLL5/
All you need is to assign the correct listeners to the correct elements, as you can see, I do not use any ID values because they are duplicated.
I can use as well duplicate IDs in case you think this is not an argument, this is demonstrated in a related answer:
remove text from multiple spans having same id
I hope this helps you to get the feets again on the ground so that you can continue to validate the HTML and clean up a little bit.
It appears that your html form has
<input type="hidden" value="<?php echo $recipe_id; ?>"/>
However, the input field name attribute is not present so the post data stream will not have a definition for $_POST["recipe_id"] field. The undefined value is likely being interpreted by your script as 0 and so only the top or "highest" li image is updated.
If you alter the input field thus:
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>"/>
You may have better results...
Just change this part :
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
With :
$("#file").change(function(){$(this).parents("form").get(0).submit();})
In your HTML, you have:
<form id="upload_icon" action="upload_extra.php" method="POST"
enctype="multipart/form-data">
Then your Javascript mentions:
document.getElementById("file").onchange = function() {
document.getElementById("upload_icon").submit();
}
According to some specifications (HTML4, HTML5), there shouldn't be same IDs on multiple elements. So, when you use an iteration, avoid printing ids without appending something unique on them, like:
<form id="upload_icon<?php print $recipe_id; ?>"
action="upload_extra.php" method="POST" enctype="multipart/form-data">
Your Javascript can be turned into something like the following. (please mind that you need to call this function after the page is loaded)
function afterPageLoad() {
var buttons = document.getElementsByClassName("upload");
for (i = 0; i < buttons.length; i++) {
buttons[i].onchange = function() {
this.form.submit();
}
}
}
Now, if your PHP code has stopped working, we would need to see that, too, at the part you omitted by writing
//get image attributes
where the $location variable is initiated.
In JavaScript provided its submitting the form by finding the element by ID, As in the HTML code the IDs are repeating (not a standard method, IDS can't repeat but class can) so the browser will always submit the last (highest) form only, that's why when adding image to highest row its working and in between its not.
Please check this code out
<script>
$(document).ready(function()
{
id = '';
$('.upload_icon').click(function(){
id = $(this).attr('id');
$(this).parent().find('#file'+id).click();
});
$(".upload").change(function () {
$('#upload_icon'+id).submit();
});
});
</script>
<style>
.upload_icon {
cursor:pointer;
}
</style>
<ul>
<?php for($recipe_id=1;$recipe_id<10;$recipe_id++): ?>
<li id="entry<?php echo $recipe_id ?>">
<div class="addimage_icon" id="upload<?php echo $recipe_id; ?>">
<form action="upload.php" method="POST" enctype="multipart/form-data" id="upload_icon<?php echo $recipe_id; ?>">
<input class="upload" id="file<?php echo $recipe_id; ?>" type="file" name="image" style="display:none"/>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?>" />
<img class="upload_icon" src="https://cdn2.iconfinder.com/data/icons/picons-basic-2/57/basic2-036_cloud_upload-128.png" id="<?php echo $recipe_id; ?>">
</form>
</div>
</li>
<?php endfor; ?>
</li>
In the HTMl code I have provided have different IDs for each forms (used the $recipe_id as suffix), when ever click event on the upload icon is fired it will check which upload icon is clicked by its attribute Id and then the respective input type file value is changed by finding the element by Id (used the same $recipe_id as suffix here also). On input type change event also same logic is used to fire the respective form.

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

Add variable into (specify text field) on the previous page

I have been looking for a way to add the information (string) from a variable in the previous page.
As far as I know this should be possible using javascript somehow.
New one couldn't get the old one to work properly..
<script type="text/javascript">
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
Armory Avatar
I have that piece of code that opens the link into a new popup window(which remembers the url of the previous page).
In this window people can insert some information about there WoW character and the realm this character is on. After they do this and hit submit the site displays the url for the avatar retrieved from the blizzard armory.
http://eu.battle.net/static-render/eu/(imagepath)
Code for the popup page: Updated this current code (7-4-2012)
<?php
if (!isset($_POST['submit'])) {
?>
<!-- The fill in form -->
<html>
<head>
<title>Armory Avatar</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Character Name:<input type="text" size="12" maxlength="50" name="cname"><br />
Realm Name:
<select name="rname">
<optgroup label="English Realms">
<option value="aerie-peak">Aerie-Peak</option>
<option value="agamaggan">Agamaggan</option>
<option value="aggramar">Aggramar</option>
etc etc etc.
</optgroup>
</select><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else { //If form is submitted execute this
$charname = $_POST["cname"]; //input character name
$realmname = $_POST["rname"]; //input realm name
$charurl = urlencode(utf8_encode($charname)); //prepares character name for url usage
$realmurl = 'http://eu.battle.net/api/wow/character/'.$realmname.'/'; //combines the basic url link with the realm name
$toon = $realmurl.$charurl; //adds the charactername behind the realm url
$data = #file_get_contents($toon); //retrieves the data from the armory api
if ($data) {
// if armory data is found execute this
$obj = json_decode($data); //converts the data from json to be used in the php code ?>
<img src='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> </img><br /> <?php //Is url link to image
$armoryname = utf8_decode($obj->name); //makes the name readable again
echo "Name: " . $armoryname . "<br />"; //character name
echo "Level: " . $obj->level . "<br />"; //character level
echo "Achievement Points : " . $obj->achievementPoints . "<br />"; //Achievement Points
if ( $obj->gender == 1 ){ //Deteremines the gender of the character
echo "Gender : Female <br />" ; //displays gender as female
}else{
echo "Gender : Male <br />" ; //dispalays gender as male
}
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
?>
Image: <a href='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?></a><br />
<!--Button submit code-->
<script type="text/javascript">
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
</script>
<input> <!-- The button here -->
<?php
}
else { // if armory data is not found execute this ?>
error code stuf
}
}
?>
Now i need this line of code:
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
To be returned when the window is closed or simply by hitting another submit button(prefered to happen on close over button). And when either of those happen it needs to insert this into this string:
<input type="text" class="textbox" name="avatarurl" size="25" maxlength="100" value="{$avatarurl}" /></td>
The texbox called avatarurl.
Hopefully any of you know how to modify or create a javascript that does this for you. Since my php is already severely limited and my javascript knowledge is next to none.
You need to modify the way you're closing your pop-up window. Try something like this:
// When a BUTTON with the class name 'cancel_link'
// is clicked, it activates the following
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
You need to make sure your closing link has cancel_link as its class name, and that your input element in your parent document has an id of avatarurl.
So after searching trying and thanks to #Jamie i knew where to look.
I found http://www.codingforums.com/showthread.php?t=213298
And this was finally the thing that worked.
On the php page to open it i added:
<script type="text/javascript">
function open_pop(){
window.open('armory.php','AvatarArmory','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
<html>
.....
<input type="button" value = "OpenArmory" onClick="open_pop()" />
And added id="blogbox" to the input for the textbox.
<input type="text" class="textbox" name="avatarurl" size="45" value="{$avatarurl}" id="blogbox"/>
On the armory.php page i added this button with the javascrip function:
<script type="text/javascript">
function pops(avatar){
textcontent=opener.document.getElementById("blogbox").value;
opener.document.getElementById("blogbox").value = textcontent + " " + avatar;
}
</script>
<input type="button" value = "Insert Avatar.." onClick="pops('<?php echo $image; ?>');window.close()" />
And that worked perfectly.
Thank you jamie for the help.

Receive form input data with PHP POST

I'm using the jQuery tag-it plugin, which basically has an input field. Everything works well, but I am unable to receive the input field value by submitting the form with PHP.
Here's the form part:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST[mytags];
echo $tags;
}
?>
The demo of the plugin is here: http://levycarneiro.com/projects/tag-it/example.html
and the javascript code is here: http://levycarneiro.com/projects/tag-it/js/tag-it.js
I'll be thankful for any help.
in tpl
<script type="text/javascript">
$(document).ready(function() {
$("#tags-input").tagit({
fieldName: "tag[]",
availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"]
});
});
</script>
use fieldName: "tag[]" attribute, in backend print_r($_POST) and check what it will display
ul is not a form element which would be submitted, it's a UI element. And you need to use quotes around your array indexes, like this:
if (isset($_POST['submit'])) {
the code should look like this:
<?
if ($_POST['submit']) {
$tags = $_POST['mytags'];
echo $tags;
}
?>
you forgot the enclosing '
if you forget that php treats the submit in $_POST[submit] as a constant
EDIT:
try this:
<?
var_dump($_POST);
?>
The acutal tags are stored in this form field which is created for each tag:
function create_choice (value) {
// some stuff
el += "<input type=\"hidden\" style=\"display:none;\" value=\""+value+"\" name=\"item[tags][]\">\n";
// some other stuff
}
So you must look out not for 'mytags' but for $_POST['item']['tags'] in your PHP Code which will then give you an array of the tags.
There should be NO posted data
your code does not use any input fields!
Looking at your plugin, it seems to create hidden input fields on the fly as you add tags.
Assuming that part of the code is actually working, put the following into your PHP code.
<?php
var_dump($_POST); //this has to be in the page you POST to
?>
See if all your tags are showing up. If it is, then your JS works and your PHP is at fault. As user #ITroubs mentions, you should quote your array indices. See if that fixes it.
If no data is displayed, then your JS plugin is not working properly.
Using firebug, add a couple of tags and inspect inside the LI element of your list and see if any hidden INPUTS are being created.
Also check if there are any JS errors being reported.
Tested and solved:
<form action="<?=$PHP_SELF?>" method="post">
<div class="line">
<label for="tags">Tags</label>
<ul id="mytags" name="item[tags][]"></ul>
</div>
<input name="submit" value="Submit" type="submit" />
</form>
Here is PHP part:
<?
if ($_POST[submit]) {
$tags = $_POST["item"]["tags"];
foreach($tags as $i=>$v)
{
$tagsf .= $v;
if($i < (count($tags)-1))
$tagsf .= ",";
}
echo $tagsf;
//This shows the tags with ",". Example: dog,cat,bird,onion
}
?>

Categories