I've got a form that displays user data in php. Then I've got an input field where the qty should be inputted. Then the JS that executes calculates the total and updates the total input element.
The problem is the referencing to the relevant id element of the input. The JS I have is only referencing to the last element in the php array. So eg the id name is id="qty" . $userid, so for example the id name will be qtyuser001, qtyuser002, qtyuser003, etc, but JS only refers to qtyuser003.
I've been struggling with this for more than a day trying different methods, I can't get it to work. Is there an alternative method I should be approaching to solve this problem?
The php code
$get2 = mysqli_query($con,"SELECT * FROM table WHERE ...");
echo '<form method="post" action="">';
while($row2 = mysqli_fetch_array($get2)) {
$userID = $row2['userID'];
$fn = $row2['FirstName'];
$ln = $row2['LastName'];
echo '<tr>';
echo '<td><input readonly name="userID[]" id="userID ' . $userID . '" value="' . $userID . '"></td>';
echo '<td>' . $fn . ' ' . $ln . '</td>';
echo '<td><input type="text" size="5" name="nrOfQ[]" id="nrOfQ' . $userID . '" onchange="calc()"></td>';
echo '<td><input readonly type="text" size="5" name="total" id="total' . $userID . '"></td>';
echo '</tr>';
}
echo '</table>';
The JS code
<script>
function calc() {
var userid = <?php echo json_encode($userID); ?>;
var myrate = <?php echo json_encode($FieldInterviewerRate); ?>;
var myqty = document.getElementById('nrOfQ' + userid).value;
myResult = myqty * myrate;
var elem = document.getElementById('total' + userid);
elem.value = myResult;
}
</script>
I don't now Javascript that well
your problem that you are not init the JS function each time and you shouldt. The JS code shouldn't depend of PHP and mast be dynamic.
Please Try this
php
$get2 = mysqli_query($con,"SELECT * FROM table WHERE ...");
echo '<form method="post" action="">';
while($row2 = mysqli_fetch_array($get2)) {
$userID = $row2['userID'];
$fn = $row2['FirstName'];
$ln = $row2['LastName'];
echo '<tr>';
echo '<td><input readonly name="userID[]" id="userID ' . $userID . '" value="' . $userID . '">
<input type="hidden" id="myRate' . $userID . '"></td>';
echo '<td>' . $fn . ' ' . $ln . '</td>';
echo '<td><input type="text" size="5" name="nrOfQ[]" id="nrOfQ' . $userID . '" onchange="calc(this)"></td>';
echo '<td><input readonly type="text" size="5" name="total" id="total' . $userID . '"></td>';
echo '</tr>';
}
echo '</table>';
<script>
function calc(obj) {
var id = obj.id;
var userId = id.substr(5);
var myrate = document.getElementById('myRate' + userId).value;
var myqty = document.getElementById('nrOfQ' + userId).value;
myResult = myqty * myrate;
var elem = document.getElementById('total' + userId);
elem.value = myResult;
}
</script>
Related
Here i am creating table rows with two dropdowns
`
counter = 0;// Global Variable
function addNewRow(){
counter++;
$('#purchase_order').append('<tr id='+counter+'>' +
'<td>' +
'<select name="code'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id="code'+counter+'">' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM product_packing_relation WHERE sub_cat_id !=0000";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . "PT_".$row['product_type_id']."_".$row['id'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td>' +
'<select name="product'+counter+'" onchange="return getItemNamesByTypeID('+counter+')" class="form-control" id=product'+ counter +'>' +
'<option value="0">--Item Code --</option>' +
'<?php
$query = "SELECT * FROM vw_product_packing_relation";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["id"] .'">' . $row['product_name'].'_'.$row['item_size'].$row['item_unit'].'_'.$row['bundle_type'].'_'.$row['pack_size'] .'</option>';
}
?>' +
'</select>' +
'</td>' +
'<td><input class="form-control" type="test" name=uom'+ counter +' id=uom'+ counter +' /></td>' +
'</tr>');
$("#code"+counter).select2();
$("#product"+counter).select2();
}`
Now i try to do that if user change any dropdown the selected key change the other dropdown here is the code.
`function getItemNamesByTypeID(counter){
event.preventDefault();
var product_packing_id=0;
product_packing_id = $("#code" + counter + " option:selected").val();
if(product_packing_id == 0)
{
product_packing_id = $("#product" + counter + " option:selected").val();
}
alert(product_packing_id);
debugger;
$("#code"+counter).val(product_packing_id);
$("#code"+counter).change();
$("#product" + counter).val(product_packing_id);
$("#product" + counter).change();
return false;
}`
Now the problem is if i change any dropdown it starts calling onchange function infinite times.
I am trying to get my Javascript variables passed back to my PHP function. I am aware that I need to use the GET method but am unsure how to implement it here.
My PHP Function:
function showRailroadSchedule()
{
global $conn;
global $thisPHP;
$sql = "SELECT * FROM trip";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo '<div class="limiter">';
echo '<div class="container-table100">';
echo '<div class="wrap-table100">';
echo '<div class="table100 ver2 m-b-110">';
echo "<h2>Available Trip Reservations</h2>";
echo '<table data-vertable="ver2" id="tableMain">';
echo "<thead><tr class='row100 head'><th>Trip ID</th><th>Arrival Time</th><th>Departure Time</th><th>Train ID</th><th>Arrival Station</th><th>Track ID</th><th>Departure Station</th></tr></thead>";
while($row = $result->fetch_assoc())
{
echo '<tbody><tr class="row100">';
$TRIP_ID = $row["TRIP_ID"];
echo
' <td class="column100 column2" data-column="column2"> ' . $row["TRIP_ID"] .
' </td> <td class="column100 column3" data-column="column3"> ' . $row["TRIP_ARR_TIME"] .
' </td> <td class="column100 column4" data-column="column4"> ' . $row["TRIP_DEP_TIME"] .
' </td> <td class="column100 column5" data-column="column5"> ' . $row["TRAIN_ID"] .
'</td> <td class="column100 column6" data-column="column6"> ' . $row["TS_ARRIVAL"] .
'</td> <td class="column100 column7" data-column="column7"> ' . $row["TRACK_ID"] .
'</td> <td class="column100 column8" data-column="column8"> ' . $row["TS_DEPARTURE"] .
'</td> ';
echo "<form action='{$thisPHP}' method='post' style='display:inline' >";
echo "<input type='hidden' name='cID' value='{$cID}'>";
echo "</td></tr></tbody>";
}
echo "<tfoot><tr><td>'$_GET[w1]'</td><td>Arrival Time</td><td>Departure Time</td><td>Train ID</td><td>Arrival Station</td><td>Track ID</td><td>Departure Station</td></tr></tfoot>";
echo "</table>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
else
{
echo "0 results";
}
}
My Javascript Function:
<script>
$(document).ready(function() {
//=================================================================
//click on table body
//$("#tableMain tbody tr").click(function () {
$('#tableMain tbody').on('click', 'tr', function() {
//get row contents into an array
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
var tripid = tableData[0];
var arrivaltime= tableData[1];
var departuretime = tableData[2];
var trainid = tableData[3];
var arrivalstation = tableData[4];
var trackid = tableData[5];
var departurestation = tableData[6];
//var arrivaltime = tableData[1] + '*' + tableData[2] + '*' + tableData[3] + '*' + tableData[4] + '*' + tableData[5] + '*' + tableData[6] + '*' + tableData[7];
alert(tripid);
window.location.href = "railroadutils.php?w1=" + tripid;
});
$("#thebutton").click(function() {
$('#tableMain > tbody').append('<tr class="datarow"><td>11111</td><td>22222</td><td>33333</td><td>44444</td><td>55555</td></tr>')
})
});
</script>
After a row is clicked, the page refreshes and a blank screen appears, however the link does have the w1 variable in it. I am just wanting to display this w1 variable inside my table.
Thank you in advance!
Without seeing the rendered HTML, it's hard to see what's happening but I think this is your issue:
echo "<tfoot><tr><td>'$_GET[w1]'</td><td>Arrival Time</td><td>Departure Time</td><td>...
^^^^^^^^^^^
I think you need to concatenate it like you did the other echo statements like this:
echo "<tfoot><tr><td>'" . $_GET[w1] . "'</td><td>Arrival Time</td><td>Departure Time</td><td>...
^^^^^^^^^^^^^^^^^^
In my code of wordPress I am trying to clone <select> box with its options it works but the problem is all of its option went outside ending select tag </select> I am not confirm whats wrong with it
Preview Image
HTML Output: https://jsfiddle.net/h5voq4nt/
PHP Code
$output .= '<label for="_jwppp-video-url-' . $number . '">';
$output .= '<strong>' . __( 'Media URL', 'jwppp' ) . '</strong>';
$output .= '<a class="question-mark" href="http://www.ilghera.com/support/topic/media-formats-supported/" title="More informations" target="_blank"><img class="question-mark" src="' . plugins_url('jw-player-7-for-wp-premium') . '/images/question-mark.png" /></a></th>';
$output .= '</label> ';
$output .= '<p>';
$output .= '<input type="text" id="_jwppp-video-url-' . $number . '" name="_jwppp-video-url-' . $number . '" style="margin-right:1rem;" placeholder="' . __('Video (YouTube or self-hosted), Audio or Playlist', 'jwppp') . '" ';
$output .= ($video_url != 1) ? 'value="' . esc_attr( $video_url ) . '" ' : 'value="" ';
$output .= 'size="60" />';
$output .= '<input type="text" name="_jwppp-' . $number . '-main-source-label" id ="_jwppp-' . $number . '-main-source-label" class="source-label-' . $number . '" style="margin-right:1rem;';
$output .= '" value="' . $main_source_label . '" placeholder="' . __('Label (HD, 720p, 360p)', 'jwppp') . '" size="30" />';
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
$output .= '<option name="NoAds" value="NoAds"';
$output .= ($ads_client == 'NoAds') ? ' selected="selected"' : '';
$output .= '>No Ads</option>';
$output .= '<option name="AdCode1" value="AdCode1"';
$output .= ($ads_client == 'AdCode1') ? ' selected="selected"' : '';
$output .= '>Ad Code 1</option>';
$output .= '<option name="AdCode2" value="AdCode2"';
$output .= ($ads_client == 'AdCode2') ? ' selected="selected"' : '';
$output .= '>Ad Code 2</option>';
$output .= '<option name="AdCode3" value="AdCode3"';
$output .= ($ads_client == 'AdCode3') ? ' selected="selected"' : '';
$output .= '>Ad Code 3</option></select>';
JQuery Code
<script>
(function($) {
$(document).ready(function() {
var number = <?php echo $number; ?>;
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
//CHANGE PLAYLIST-HOW-TO
var tot = $('.jwppp-input-wrap:visible').length;
if(tot > 1) {
$('.playlist-how-to').show('slow');
var string = [];
$('.order:visible').each(function(i, el) {
string.push($(el).html());
})
$('.playlist-how-to code').html('[jw7-video n="' + string + '"]');
} else {
$('.playlist-how-to').hide();
}
$('.jwppp-more-options-' + number).hide();
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
};
$('#_jwppp-video-url-' + number).on('change',function() {
var $url = $('#_jwppp-video-url-' + number).val();
var $ads = $('#_jwppp-video-ad-' + number).val();
var $ext = $url.split('.').pop();
var $arr = ['xml', 'feed', 'php', 'rss'];
if($.inArray($ext, $arr)>-1) {
$('.more-options-' + number).hide();
$('.jwppp-more-options-' + number).hide();
} else {
$('.more-options-' + number).show();
}
});
});
})(jQuery);
</script>
In PHP code has
$output .= '<select style="margin-top: 0; margin-left: 0.8rem;" id="_jwppp-video-ad-' . $number . '" name="_jwppp-video-ad-' . $number . '" />';
this has an end slash (/), please remove it.
I am having some difficulties with the following code. I am attempting for the users that are outputted after this form is pressed to be given a number like - 1, 2, 3 , 4 ,etc
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
</form>
However, the echoed out item id 'undefined'. I'm not sure if my Javascript is wrong for what I am trying to do, but the rest outputs/echos correctly.
Then when I submit it by hitting the Finalyze Draft Order button. All of this is sent into my database successfully, except the drafted_order column (the column I am trying to send this count to) displays at 4. It seems like it is counting the number of records in that database table and displaying it in there. The thing I don't get is on the page, it shows the number is undefined?
If I don't have this input added to the Js, the script fails..
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
I don't get why it is coming up as undefined and why this isn't counting in a 1, 2, 3, 4, etc order as the user's are outputted.
What am I doing wrong?
echo 'Users to be given draft order: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="POST" name="form">
<input type="submit" value="Create Draft Order" name="shuffle">
</form>
Shuffled results: <br>
<div class="main-bag">
<div class="shuffle_results" id="results"></div>
<form method="post">
<?php
$count = 0;
foreach ($array as $result) :
$count++;
$shuffle_count = $count;
$shuffle_firstname = htmlentities($result['firstname']);
$shuffle_lastname = htmlentities($result['lastname']);
$shuffle_id = htmlentities($result['id']);
$shuffle_username = htmlentities($result['username']);
$shuffle_email = htmlentities($result['email']);
?>
<input type="hidden" name="count[]" value="<?php echo $shuffle_count; ?>">
<input type="hidden" name="firstname[]" value="<?php echo $shuffle_firstname; ?>">
<input type="hidden" name="lastname[]" value="<?php echo $shuffle_lastname; ?>">
<input type="hidden" name="id[]" value="<?php echo $shuffle_id; ?>">
<input type="hidden" name="username[]" value="<?php echo $shuffle_username; ?>">
<input type="hidden" name="email[]" value="<?php echo $shuffle_email; ?>">
<?php
endforeach;
if ( isset($_POST['shuffle'] ) ) :
echo '<input type="submit" value="Finalize Draft Order" name="insert">';
endif;
?>
</form>
<?php
if (isset($_POST['insert'])) {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$draft_stmt1 = $con->prepare("INSERT INTO user_players (user_id, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?)");
$draft_stmt2 = $con->prepare("INSERT INTO drafted_players (user_id, drafted_order, firstname, lastname, username, email) VALUES (?, ?, ?, ?, ?, ?)");
if ( false===$draft_stmt1|| false===$draft_stmt2 ) {
// Check Errors for prepare
die('Add to user players prepare() failed: ' . htmlspecialchars($con->error));
}
$draft_stmt1->bind_param('issss', $shuffle_id, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
$draft_stmt2->bind_param('iissss', $shuffle_id, $shuffle_count, $shuffle_firstname, $shuffle_lastname, $shuffle_username, $shuffle_email);
foreach ($_POST['id'] as $i => $shuffle_id) {
$shuffle_firstname = $_POST['firstname'][$i];
$shuffle_lastname = $_POST['lastname'][$i];
$shuffle_username = $_POST['username'][$i];
$shuffle_email = $_POST['email'][$i];
$draft_stmt1->execute() or
die('Add to user players execute() failed: ' . htmlspecialchars($draft_stmt1->error));
$draft_stmt2->execute() or
die('Add to user
Javascript
var displayResults = function(data){
var i = 0;
var lineheight = 24;
var time = 3000;
var interval = setInterval(function(){
if( i <= data.length){
console.log( data[i] );
$('#results').append('<div class="result">' +
//'<div class="shuffle_results">' + data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<div class="shuffle_results">' + data[i].drafted_order + ' '+ data[i].firstname + ' ' + data[i].lastname + '</div>' +
'<input type="hidden" name="count[]" value="' + data[i].drafted_order + '">' +
'<input type="hidden" name="firstname[]" value="' + data[i].firstname + '">' +
'<input type="hidden" name="lastname[]" value="' + data[i].lastname + '">' +
'<input type="hidden" name="id[]" value="' + data[i].id + '">' +
'<input type="hidden" name="username[]" value="' + data[i].username + '">' +
'<input type="hidden" name="email[]" value="' + data[i].email + '">' +
'</div>');
in
if( i <= data.length){
try replacing <= with <. Indexes of array doesn't include length (because start with zero).
I am using a date picker in PHP, but I experience a small problem.
When selecting a month, I automatically submit the form to change the amount of days:
<script>
function change()
{
document.getElementById("datepickerform").submit();
}
</script>
But, when I press submit, I also want to execute some extra code (querying a database for some info with the selected date.
Is there a way to make a difference when the OK button is pressed or when the form is "submitted" via the function above?
Hereunder is the entire code (not finished, leap year also not included yet) of my datepicker.php:
<script>
function change(){
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// http://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>
Could anybody help?
Most JS libraries that preform AJAX calls pass an extra header with the request, typically X_REQUESTED_WITH with a value of XMLHttpRequest. If you were using something like jQuery you can check for this using PHP, or you could just use a hidden field that your JS creates and fills in when it is submitted that way.
function change()
{
var form = document.getElementById('datepickerform'),
el = document.createElement('input');
el.type = 'hidden';
el.name = 'js';
el.value = '1';
form.appendChild(el);
form.submit();
}
And then when handling in PHP, use
if (isset($_POST['js'])) {
// ...
}
You can Keep a hidden field in form and if the form is beig submitted using js then change the value of hidden field before submitting the form.
You could change it so that there is an Ajax call when the month changes, and use a button that can be used to invoke processing prior to submit.
Thanks for the above tips, this solved my problem. Also Change value of input then submit form in javascript helped solving my problem.
<script>
function change(){
document.getElementById("datepickerform").submitform.value = '1';
document.getElementById("datepickerform").submit();
}
</script>
<?php
// Include global Definitions and variables
// https://stackoverflow.com/questions/18179067/select-from-drop-down-menu-and-reload-page
// Form
define("FORM_DAY", "theday");
define("FORM_MONTH", "themonth");
define("FORM_YEAR", "theyear");
// Date related
$days = array(31,28,31,30,31,30,31,31,30,31,30,31);
// Get result from FORM POST
$submitform = $_POST["submitform"];
$submittedday = $_POST[FORM_DAY];
$submittedmonth = $_POST[FORM_MONTH];
$submittedyear = $_POST[FORM_YEAR];
if ($submittedday != '')
{
$currentday = $submittedday;
$currentmonth = $submittedmonth;
$currentyear = $submittedyear;
}
else
{
$currentday = intval(date("d"));
$currentmonth = intval(date("m"));
$currentyear = intval(date("Y"));
}
//DEBUG ON
echo $submitform."<br>\r\n";
echo $submittedday."/".$submittedmonth."/".$submittedyear."<br>\r\n";
echo $currentday."/".$currentmonth."/".$currentyear."<br>\r\n";
if ($submitform == '0')
{
echo 'Button pressed.<br>';
}
else
{
echo 'Javascript executed.<br>';
}
// DEBUG OFF
echo '<form id="datepickerform" action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
echo '<table border="1" cellpadding="2">';
echo '<tr><td>';
echo '<table border="0" cellpadding="2">';
echo '<tr><th>Day</th><th>Month</th><th>Year</th></tr>';
echo '<tr>';
echo '<td><select name=' . FORM_DAY . '>';
$i = 1;
for ($i==1; $i<=$days[$currentmonth-1]; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentday)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_MONTH . ' onchange="change()">';
$i = 1;
for ($i==1; $i<=12; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentmonth)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '<td><select name=' . FORM_YEAR . '>';
$i = 2015;
for ($i==2015; $i<=2020; $i++)
{
echo '<option value="' . $i . '"';
if ($i == $currentyear)
{
echo ' selected';
}
echo '>' . $i . '</option>';
}
echo '</select></td>';
echo '</tr>';
echo '</table>';
echo '</td></tr>';
echo '<tr><td align="middle">';
echo '<input type="hidden" name="submitform" value="0">';
echo '<input type="submit" value="OK"></td>';
echo '</td></tr>';
echo '</table>';
echo '</form>';
?>