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>";
}
Related
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.
Using SQLite I can list the values in
<div class="text-middle">
<?php foreach($result as $row) ?>
<button class="button button1" id="myBtn" value="<?php echo $row['Id']; ?>" onclick="myFunction()"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
However when I click on the button it's showing the only the first value in popup alert.
function myFunction() {
var x = document.getElementById("myBtn").value;
alert(x);
}
How can I get the corresponding values in each button?
All of your buttons have the same id attribute. they must be unique within the page. To fix this you can remove the id attribute and pass the reference of the button to the function:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button button1" value="<?php echo $row['Id']; ?>" onclick="myFunction(this)"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
function myFunction(el) {
var x = el.value;
console.log(x);
}
Better still would be to place the same class on all the buttons and use unobtrusive JS code to attach your event handler, like this:
<div class="text-middle">
<?php foreach($result as $row) { ?>
<button class="button" value="<?php echo $row['Id']; ?>"><?php echo $row['Id']; ?></button>
<?php } ?>
</div>
// native JS:
var buttons = document.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
var x = this.value;
console.log(x);
});
}
// jQuery:
$('.button').click(function() {
var x = this.value;
console.log(x);
});
Do not use the same id for more then one element: id="myBtn"
Change your function:
onclick="myFunction()"
to:
onclick="myFunction(this)"
And so:
function myFunction(element) {
var x = element.value;
alert(x);
}
You need to get the elements by their class, not by the id that they all share (which is a bad thing to do).
<script>
function myFunction() {
var x = document.getElementsByClassName("button1");
for (var i = 0; i < x.length; ++i) {
alert(x[i].value);
}
}
</script>
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'".');" > ';
I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>
Ok maybe I've overlooked something really simple here, but I can't seem to figure this out. I am trying to make my form dynamicly extendable.
My Problem is i can't get this code working:
<html>
<head>
<?php
$i = 1;
$p = 1;
$r = 1;
?>
<script language="javascript">
function add()
{
document.getElementById("groesse").innerHTML = document.getElementById("grosse").innerHTML+"<input type='text' name='groesse[<?php echo $i;?>]'>";
document.getElementById("preis_l").innerHTML = document.getElementById("preis_l").innerHTML+"<input type='text' name='preis_a[<?php echo $p;?>]'>";
document.getElementById("preis_a").innerHTML = document.getElementById("preis_a").innerHTML+"<input type='text' name='preis_l [<?php echo $r;?>]'><br>";
<?php
$i = $i + 1;
$p = $p + 1;
$r = $r + 1;
?>
}
</script>
</head>
<body>
<?php
if ($_REQUEST['Selected'] == 'Speisekarte')
{
echo '<br><br><br><br>';
echo '<input type="button" value="+" onClick="add()">';
echo '<form action="insert.php" method="submit">';
echo '<table border="1">';
echo '<tr><td>ID</td><td>Name</td><td>Beschreibung</td><td>Größe</td><td>Preis_L</td><td>Preis_A</td></tr>';
echo '<tr><td><input type="text" id="ID" name="ID"></td>';
echo '<td><input type="text" id="Name" name="Name"></td>';
echo '<td><input type="text" id="Beschreibung" name="Beschreibung"></td>';
echo '<td id="groesse"></td>';
echo '<td id="preis_l"></td>';
echo '<td id="preis_a"></td>';
echo '</tr></table><input type="hidden" value="Speisekarte">';
echo '<button type="submit">OK</button></form>';
}
?>
</body>
</html>
I want when someone klicks the +-Button my Form gets 3 Textfields more in the table with the specific ids. I also tried it with div-Tags but that didn't worked too.
I hope someone can help me.
You can't use php clientside, it is parsed on the server only when visitor requests the page by GET or POST, so using $i = $i + 1 will not work clientside. By the way, use $i++ instead.
You could solve this with only javascript or, as an alternative, submit the form and present the form again with the extra fields needed so you can do it with php.
I recommend you have a look at jQuery and check out this answer with demo:
How to use jQuery to add form elements dynamically
(credits to PSL)