newbie asking here.
i have an ordered list of multi dimensional array
$blok = array
(
array("B","X","X",3,4,5,"X",7,8,9,10),
array("G",1,2,3,4,5,6,7,8,9,10),
array("L",1,2,3,4,5,6,7,8,9,10),
array("Q",1,2,3,4,5,6,7,8,9,10)
);
and then i echo each and every array value into separate div :
*already figured it out how to echo them and insert them into div id.
my question is : can i insert string after "this" inside onclick ?
<div class="span4"><div class="table1" style="float:left; background-color:magenta;" id= "'. //ARRAY VALUE// .'" onclick="select(this,"B");" >
<div class="span4"><div class="table1" style="float:left; background-color:blue;" id= "'. //ARRAY VALUE// .'" onclick="select(this,"Q");" >
my goal is to input the div id (the array value) and the string into my database using input type=hidden after onclick
<input type="hidden" id="type" name="type" value="" />
<input type="hidden" id="table" name="table" value="" />
any help is appreciated, i'm drawing a blank here.
btw this is my javascript :
var i=0; document.getElementById("table").value=""; function select(id , tipe){
if($(id).attr('class')=="table2"){
$(id).attr('class','table1');
var m=document.getElementById("table").value.split(",");
var removeItem = $(id).attr('id');;
var n = jQuery.grep(m, function(value) {
return value != removeItem;
});
document.getElementById("table").value=n;
if(n.length==0){i=0;}
}else{
$(id).attr('class','table2');
if(i==0){
document.getElementById("table").value+=$(id).attr('id');
i=1;
}else{
var j=document.getElementById("table").value.split(",");
if(jQuery.inArray($(id).attr('id'), j)==-1) {
document.getElementById("table").value+=","+$(id).attr('id');
}
}
}
var type=document.getElementById('type');
type.value=tipe }
edit : i forgot to mention i'm using concatenation assignment like this :
$number =' <div class="table1" style="float:left; background-color:magenta;" id= "'. $blok[$row][$col] .'" onclick="select(this,"B");" > ';
$number .= $blok[$row][$col]; //echo the array value to display the table number
$number .=' </div> ';
so to display those div with ARRAY VALUE as div id and text to display
i only wrote :
echo $number;
Wrap the second argument into a single quotes:
.. onclick="select(this,'B');" ...
for your php code:
.'" onclick="select(this,'."'B'".');" > ';
Related
I have obtained a resultset from a query and have count variable which is used to assign id to an input tag. Now i want to pass this id as parameter to a javascript function and increment/decrement the text input field value which has id assigned by the count variable value.
query used to get result:
for (some condition){
$cartsql = "SELECT * FROM products WHERE id=$key";
$cartres = mysqli_query($connection, $cartsql);
$cartr = mysqli_fetch_assoc($cartres);
++$count;
<div class="entry value-minus1" onclick="decrement(<?php echo $count; ?>)"></div>
<input class="entry value1" type="text" value="<?php echo $value['quantity']; ?>" id="<?php echo $count; ?>" />
<div class="entry value-plus1" onclick="increment(<?php echo $count; ?>)"></div>
<!--quantity-->
<script>
function decrement(<?php echo $count; ?>) {
alert("hello");
var y = document.getElementById(<?php echo $count; ?>).value;
y = y - 1;
document.getElementById(<?php echo $count; ?>).value = y;
}
</script>
}
First off, there's a typo in the first div. You forgot to echo the value. Change:
onclick="decrement(<?php $count; ?>)"
to
onclick="decrement(<?php echo $count; ?>)"
Then, since you're passing the id as an argument to your js functions, you shouldn't hard code the values in that function.
You also need to output the javascript after your loop or you will create multiple functions with the same name which, obviously, won't work.
Change it to:
function increment(id) {
document.getElementById(id).value++;
}
function decrement(id) {
document.getElementById(id).value--;
}
Now there's no hard coded values in your function so you can reuse it.
You don't need to use id attributes - a purely integer based id is not valid anyway ( or wasn't until HTML5 ). You can use sibling selectors for convenience. As demonstration the javascript functions can be radically altered / simplified
<style>
div.entry{ display:inline-block;width:2rem;border:1px solid black; height:2rem; line-height:2rem; text-align:center; font-size:1rem; clear:none; cursor:pointer; }
input[type='text']{display:inline-block;height:2rem; }
</style>
<script>
function decrement(e){
e.target.nextElementSibling.value--;
}
function increment(e){
e.target.previousElementSibling.value++;
}
</script>
for( $i=1; $i < 10; $i++ ){
$value=mt_rand(20,50);
echo "
<div>
<div class='entry value-minus1' onclick='decrement(event)'>-</div>
<input class='entry value1' type='text' value='$value' />
<div class='entry value-plus1' onclick='increment(event)'>+</div>
</div>";
}
Better yet would be to remove any inline function calls and use an externally registered event handler - this keeps the HTML nice and clean and separates HTML and javascript.
<script>
document.addEventListener('DOMContentLoaded',()=>{
document.querySelectorAll('div.entry').forEach( div=>{
div.addEventListener('click',function(e){
switch( this.dataset.dir ){
case 'increment':
this.previousElementSibling.value++;
break;
case 'decrement':
if(this.nextElementSibling.value > 0) this.nextElementSibling.value--;
break;
}
});
})
});
</script>
for( $i=1; $i < 10; $i++ ){
$value=mt_rand(5,50);
echo "
<div>
<div class='entry value-minus1' data-dir='decrement'>-</div>
<input class='entry value1' type='text' value='$value' />
<div class='entry value-plus1' data-dir='increment'>+</div>
</div>";
}
I have rewritten my question to better elaborate as to what I am trying to accomplish and what I have tried thus far.
I have a table on my website which dynamically loads the table rows from a database. I have successfully integrated the jQuery UI "Sortable" and "Draggable" functionality to this page. the outcome is the numeric value changes as you are dragging the rows above or below their neighboring rows and as a result always update the first column of numbers within the table.
Here is the table
<form action="" method="post" id="sort_picks">
<div class="sort-picks-container">
<table class="table-preference-order" id="sortable">
<tbody class="ui-sortable">
<?php
$counter = 1;
foreach ( $result as $query ){
$pickcheck = "SELECT * FROM picks";
$pickcutoffcheck = $wpdb->get_results( $wpdb->prepare ($pickcheck, OBJECT_K ));
foreach ($pickcutoffcheck as $pickcutoffresult) { ?>
<div style="display:none;"><?php echo $pickcutoffresult->pickCutoff; ?></div>
<?php } ?>
<?php $maxlimit = $wpdb->get_row("SELECT count(*) as CNT1 FROM picks where User='$userid'" ); ?>
<tr class="ui-state-default preference-row">
<td class="index preference-pick-order">
<input type="text" class="pick-order" id="sort" name="sort[]" pattern="[1-<?php echo $maxlimit->CNT1; ?>]{1,2}" value="<?php echo $counter; ?>" style="border:0px;max-width:60px;font-size:20px;" readonly>
</td>
<td class="preference-pick-order">
<input type="text" name="rem[]" class="borderless" style="text-align:left;width:25px;display:none;" value="<?php echo $query->REM; ?>" readonly><?php echo $query->REM; ?>
</td>
<td class="preference-emp-info">
<input type="text" name="empname[]" class="borderless" style="display:none;" value="<?php echo $query->EmpName; ?>" readonly><b><?php echo $query->EmpName; ?></b>
</td>
<td class="preference-start-class">
<input type="text" name="starttime[]" class="borderless" style="text-align:left;max-width:75px;display:none;" value="<?php echo $query->StartTime; ?>" readonly><?php echo $query->StartTime; ?>
</td>
<td class="preference-details">
<input type="text" name="job_details[]" class="borderless" value="<?php echo $query->Job_Details; ?>" readonly style="display:none;"><?php echo $query->Job_Details; ?>
<br>
<input type="text" name="startdate[]" class="borderless" style="font-weight:bold;width:100%;text-align:left;display:none;" value="<?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>" readonly><?php if($query->StartDate!=""){echo date('l\, F jS Y', strtotime($query->StartDate)); }?>
</td>
</tr>
<?php $counter++; ?>
<?php }?>
</tbody>
</table>
</div>
<br>
<div class="sorters-holder">
<button onclick="upNdown('up');return false;" class="sorters">∧ </button><br>
<button onclick="upNdown('down');return false;" class="sorters">∨</button>
</div>
<div style="display:block;margin:auto;text-align:center;">
<input type="submit" name="submit[]" value="Next" class="job-select-submit" id="validate"> <input type="button" onclick="window.history.go(-1); return false;" value="Back" class="job-select-submit">
</div>
</form>
This is the working jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.js"></script>
<script src="../wp-content/themes/Excellence_At_Work/jquery.ui.touch-punch.min.js"></script>
<script>
var $j = jQuery.noConflict();
var sort;
$j(function() {
$j("#sortable tbody").sortable({
change: function(event, ui) {
sort = 0;
$j('#sortable tr.ui-state-default:not(".ui-sortable-helper")').each(function() {
sort++;
if ($j(this).hasClass('ui-sortable-placeholder'))
ui.helper.find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
else
$j(this).find('td input[name^=sort]').attr('name', 'sort[]').attr('value', sort).val(sort);
});
}
});
$j("#sortable tbody").disableSelection();
});
</script>
<script>jQuery('#sortable').draggable();</script>
As you can see in the html code, I have successfully integrated the buttons that I need to relocate the rows however when doing so I need the value of the first td to also update accordingly as does the drab and drop method. What would I add to the below javascript to get the value of the input with the name sort[] to change to its corresponding numeric place within the table rows newly changed order onclick?
<script>
var order; // variable to set the selected row index
function getSelectedRow()
{
var table = document.getElementById("sortable");
for(var i = 0; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
if(typeof order !== "undefined"){
table.rows[order].classList.toggle("selected");
}
order = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction)
{
var rows = document.getElementById("sortable").rows,
parent = rows[order].parentNode;
if(direction === "up")
{
if(order > 0){
parent.insertBefore(rows[order],rows[order - 1]);
// when the row go up the index will be equal to index - 1
order--;
}
}
if(direction === "down")
{
if(order < rows.length){
parent.insertBefore(rows[order + 1],rows[order]);
// when the row go down the index will be equal to index + 1
order++;
}
}
}
</script>
I hope this better explains whatt I am trying to accomplish. I have hit a road block and could really use some insight, thanks in advance for all those who can provide insight.
UPDATE
I have been able to successfully update the rows first td values onclick by adding the following script after order-- and order++ however this solution is causing the input fields to drop out of the td. Any insight on how to modify this script to include the input field?
Array.prototype.forEach.call(document.querySelectorAll('td:first-child'), function (elem, idx) {
elem.innerHTML = idx + 1;
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
FINAL UPDATE
I have succeeded in my mission and with a minor adjustment to the snippet from the last update I was able to get the form above working as noted.
Array.prototype.forEach.call(document.querySelectorAll('td:first-child input[name^=sort]'), function (elem, idx) {
elem.value = idx + 1;
By changing
'td:first-child'
to
'td:first-child input[name^=sort]'
I was able to reference the specific input field as opposed to all input fields in the first td column and no longer am replacing the input fields with plain text.
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
}
Jquery :
$('.question_title').click(function () {
var value = $('#question_id').val();
alert(value);
});
Friends in this code question_id will be carrying different values for the looping . Here I have writtern code to get the value according to the LOOPING on click of ahref class I would like to fetch the value of hidden value for example in the first iteration title is cow on click ahref it should alert 0 (question_id value). on click on 2nd title cat it should get alert 1 like on clicking 5 different title it should display 0-4 respectively but now onclick on different title it alerts only 0 not the other values . could any one suggest me how to achieve it .
Get the parent h2 and then next .question_id like following.
$('.question_title').click(function() {
var value = $(this).parent().next('.question_id').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Title 0</h2>
<input type="hidden" name="question_id" value="0" id="question_id" class="question_id">
<h2>Title 1</h2>
<input type="hidden" name="question_id" value="1" id="question_id" class="question_id">
BTW you are using same id question_id for multiple elements.
As 'id' is unique value, it will get only the first element.
Try this:
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
}
Jquery :
$('.question_title').click(function()
{
alert(event.target.id);
});
For
<?php
for($i=0;$i<5;i++)
{
?>
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
<?php } ?>
And in script use
$('.question_title').click(function() {
alert($(this).attr("data-tell"));
});
You are having the same id question_id in all five hidden fields.
you can have it like this..
for($i=0;$i<5;i++)
{
echo '<h2>'.$value['asked_title'].'</h2>';
}
jquery
$('.question_title').click(function()
{
var value = $(this).data('value');
alert(value);
});
I have next form :
<?php
echo "<form action=\"test.php\" method=\"post\">";
$rez = mysqli_query($kon, "SELECT * FROM shops");
while($red = mysqli_fetch_assoc($rez)){
$niz = array(
array($red["id"],$red["naam"])
);
echo "<div class=\"col-xs-12 col-sm-12\">
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces();\"/>
</div>
</div>
<div class=\"col-sm-10 col-xs-8\">
Informacije
</div>
</div>
<div class=\"footer\" style=\"position: fixed;bottom: 0;width: 100%;left:0;\">
<span class=\"glyphicon glyphicon-chevron-left\"></span> Niets toevoegen
<button class=\"col-xs-6 col-sm-6 btn btn-danger\" type=\"submit\" name=\"btnNaruci\" id=\"btnNaruci\">
Leg in winkelmand <span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span>
</button>
</div>";
}
echo "</form>";
?>
I want to update this hidden field for every result. I have now 5 results but if i increase quantity, the hidden field get value only if i increase quantity of first result.
I have onChange by the quantity input field and then in javascript i get the value of that field and add it to the value of the hidden field, but the value of the hidden field is changed only for the first result in while loop..
Thanks in advance...
I would need the body of your proces() function to say for sure, but I think you reference your input field by id, all 5 input fields have the same id. Only first gets updated and that's the problem. Either give different ids (by adding count) or reference by class. That would work, however having same id for multiple fields is not a good idea.
Post the body of the function and I can give more detailed help.
Ok, so they do have the same id. You could go by class to update them like this:
var quan = document.getElementById("quan").value;
var hiddenfields = document.getElementsByClassName('hidd');
for (var i = 0; i < hiddenfields.length; ++i) {
var item = hiddenfields[i];
item.value = quan;
}
Or if it's ok tu use JQuery:
var quan = $("#quan").val();
$( ".hidd" ).val(quan);
Based on your comment:
I see. I think simplest would be to do the following:
In your php code add id (concat as string), and add it to the call of your updating function
This might not compile, but gives you the idea:
$i = 1;
while($red = mysqli_fetch_assoc($rez)){
// ...
echo "<div class=\"col-xs-12 col-sm-12\">
// ...
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd".$i."\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan".$i."\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces('quan".$i."', 'txtHidd".$i."');\"/>
</div>
</div>
// ...
</div>";
$i++;
In javascript the updating function would use the parameter
function proces(quanID, hiddenID) {
var quan = document.getElementById(quanID).value;
document.getElementById(hiddenID).value = quan;
}
EDIT AGAIN
I found that the /" at the id fields were in wrong position.
Updated sample code. Basically your html output is supposed to look like this (I didn't include name, as it doesn't matter, now we are only looking at id-s):
...
<input class="hidd" type="hidden" name="xxxxx" id="txtHidd1" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan1" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan1', 'txtHidd1');"/>
</div>
</div>
...
...
<input class="hidd" type="hidden" name="xxxxxx" id="txtHidd2" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan2" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan2', 'txtHidd2');"/>
</div>
</div>
...
Looking at the id-s and the call of the function. If it's like that, the javascript update part will work perfectly.
That is my test.php page
<?php
session_start();
include("config.php");
global $kon;
ob_start();
print_r($_POST["txtHidd"]);
foreach ($_POST["txtHidd"] as $id => $id_prod) {
foreach ($id_prod as $kolicina) {
echo "<br />Id : {$id} and quantity : {$kolicina}<br />";
}
}
ob_flush();
?>
And result tha i get when i hit a post is next :
Array ( [17] => Array ( [kolicina] => ) [18] => Array ( [kolicina] => ) [19] => Array ( [kolicina] => ) [20] => Array ( [kolicina] => ) )
Id : 17 and quantity :
Id : 18 and quantity :
Id : 19 and quantity :
Id : 20 and quantity :
here is what i have so far :sql that gets data from the database, the data is passed through a loop and then displayed with the html code
$sql = "SELECT items_available.title,
items_available.item_number,
items_available.subtitle,
items_available.image_name,
users.username
FROM items_available
INNER JOIN users ON items_available.owner_id = users.user_id
WHERE items_available.status ='pending'
LIMIT $query_limit ;";
$query = mysql_query($sql);
while ($dbData = mysql_fetch_assoc($query)) {
$item_id = $dbData['item_number'];
$sel_title = $dbData ['title'];
$sel_Image = $dbData['image_name'];
$sel_subtitle = $dbData['subtitle'];
$sel_owner = $dbData['username'];
echo "<span style='display:inline-block;width:185px;margin:4px;'>
<a href='#'>
<img src='upload/$sel_Image' style='width:180px; height:160px;' />
<h5 style='display:inline;'>$sel_title </h5><br>
<h7 style='display:inline;'> $sel_subtitle</h7><br>
<h6 style='display:inline;'>Posted by $sel_owner</h6>
</a>|
<div style= \"display:inline-block;\">
<input type=\"checkbox\" id=\"check\" name='item_ids[]' value='1' />
</div>
</span>";
}/
the checkbox below the block of codes should grab the ids of each element so an update to the database is possible.Hope my description is clear enough to be aided
you did nt give any specfic so it is like a guide for what u asking
you need to create a form here with a hidden field
like
<div style= \"display:inline-block;\">
<form method=\"post\">
<input type=\"hidden\" name=\"value\" =". $item_id.">
<input type=\"checkbox\" name=\"update\" value = '1' />
</form>
</div>
php for that ll look like
if (isset($_REQUEST['value']))
{
//update after validation
}
P.S $_REQUEST Deals with both for GET or POST method
it actually depends what you want
You can make the VALUE of the checkbox into the id you want to get back in the $_POST['item_ids'] array.
<div style= \"display:inline-block;\"> ";
echo '<input type="checkbox" id="check" name="item_ids[]" value="' . $item_id . '" />';
echo "</div>
Now in your PHP code you can process them like this, remember checkboxes are only returned in the $_POST/$_GET array if they are actually checked.
I am assuming $_POST.
if ( isset($_POST['item_ids']) ) {
foreach ( $_POST['item_ids'] as $item_id ) {
// do whatever you want to with this information
}
}