How to update first td value onclickthe way it does when dragging - javascript

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">&wedge; </button><br>
<button onclick="upNdown('down');return false;" class="sorters">&vee;</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.

Related

How to append multiple checkbox values into textarea with a click of one checkbox

hi guys need your help again. I have a javascript function which pass checkbox values into a textarea 'recipients', it works fine on check/uncheck and pass values accordingly into a textarea. What i want is to have one checkbox to check all checkbox and append values into a textarea.
Below is my javascript to pass vales into textarea 'recipients':
var textbox = document.getElementsByName("recipients")[0];
var checkboxes = document.getElementsByName("email");
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = (function(chk){
return function() {
var value = "";
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
if (value === "") {
value += checkboxes[j].value;
} else {
value += ", " + checkboxes[j].value;
}
}
}
textbox.value = value;
}
})(checkbox);
}
Please help.
(1) When you make a change to checkbox you need to check all checkboxes and update to textarea.
(2) function updateAllChecked will handle all the check and update.
(3) for check all, if it is checked, set all email checkboxes to checked and call .change() to trigger the change event.
$("input[name=email]").change(function() {
updateAllChecked();
});
$("input[name=addall]").change(function() {
if (this.checked) {
$("input[name=email]").prop('checked', true).change();
} else {
$("input[name=email]").prop('checked', false).change();
}
});
function updateAllChecked() {
$('#recipients').text('');
$("input[name=email]").each(function() {
if (this.checked) {
let old_text = $('#recipients').text() ? $('#recipients').text() + ', ' : '';
$('#recipients').text(old_text + $(this).val());
}
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="email" value="email_1">email_1<br>
<input type="checkbox" name="email" value="email_2">email_2<br>
<input type="checkbox" name="email" value="email_3">email_3<br>
<input type="checkbox" name="email" value="email_4">email_4<br>
<br>
<input type="checkbox" name="addall">Add All Email<br>
<textarea id="recipients"></textarea>
Try something like this, using an array with a final join() once your array is populated. I think it's a lot cleaner:
checkbox.onclick = (function(chk){
return function() {
var valueArray = [];
for (var j = 0; j < checkboxes.length; j++) {
if (checkboxes[j].checked) {
valueArray.push(checkboxes[j].value); //add value to array
}
}
textbox.value = valueArray.join(", "); //join with comma separators
}
})(checkbox);
You could also extract the function and invoke the extracted function rather than adding the content of the function to every checkbox, but w/out seeing your HTML, it's a little hard to discern exactly what you're doing and why you're looping the way you are.
Hi guys here is my html and php, I retrieve recipients email from db:
here is my html with php, I retrieve recipients email from db.: <?php
$i='';
if($result_applied_jobs): ?>
<div class="tg-wrap">
<table id="tg-s6tTH" class="tg" style="width: 100%;">
<tr><th style="width: 12%"><label><input type="checkbox" name="addall" id="addall"/> Select all</label></th><th style="width: 7%">Sl. No.</th><th style="width: 20%">Applicant's Name</th><th style="width: 25%">Job Title</th><th style="width: 13%">Apply Date</th><th>Cover Letter</th></tr><?php
foreach($result_applied_jobs as $row_applied_job):
$i++;
?>
<tr>
<td><input type="checkbox" value="<?php echo $row_applied_job->email;?>" name="email" id="email"></td>
<td><?php echo $i;?></td>
<td><?php echo $row_applied_job->first_name.' '.$row_applied_job->last_name;?></td>
<td><?php echo $row_applied_job->job_title;?></td>
<td><i class="fa fa-calendar-check-o" aria-hidden="true" style="color: #5f6f81"></i> <?php echo date_formats($row_applied_job->applied_date, 'M d, Y');?></td>
<td><?php echo $row_applied_job->c_letter;?></td>
</tr>
<?php endforeach; ?>
</table>
</div><?php
else:?>
<div class="alert alert-danger"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> No application received</div>
<?php endif;?>
here is another portion for textarea:
<textarea class="form-control" id="recipientss" readonly="" placeholder="check the checkbox against applicants you want to send a message"><?php echo set_value('recipients');?></textarea>

How to select all checkbox and get value in jquery

In foreach loop there is checkbox for each row.
Code As Bellow.
foreach($rpd_records as $rpd_newslater_records)
{
$rp_ne_value = maybe_unserialize($rpd_newslater_records->meta_value); ?>
<tr>
<input type="hidden" class="rpd_meta_id" name="rpd_meta_id" value="<?php echo $rp_ne_records->meta_id; ?>">
<td><input type="checkbox"></td>
<td><?php echo $rp_ne_value['product_id']; ?></td>
<td> <div class="send_mail_btn" style="display: inline;">
Send</div></td>
</tr>
<?php
} ?>
<button type="button" id="sendAll" class="main"><span class="sub"></span> Send All </button>
What I should : when i click on SendAll Button then its all checkbox are selected and get each of Row Hidden Value using Jquery.
Can you suggest me.
Thanks.
This will help you;
$("#sendAll").click(function(e) {
$(":checkbox").attr("checked", true);
var values = $('input.rpd_meta_id[type="hidden"]').map(function(){
return this.value;
}).get();
alert(values);
});
You can
1) traverse to closest tr element
2) find hidden input in it.
3) use .map() and get jquery object of all hidden input values
4) convert to array using .get()
$('#sendAll').click(function(){
var inputcheckboxes = $('input:checked').attr("checked", true);
var hiddenValForChecked = inputcheckboxes.find('.rpd_meta_id').map(function(){
return this.value;
}).get();
console.log(hiddenValForChecked);
});
Here hiddenValForChecked represents array of values of hidden fields.

while loop set only first value in input field in php

I want to add users present in a given table. I am iterating whole table and sending each value to javascript file.
<?php
$sql = "select * from user where user_id not in (select second_user_id from friends where first_user_id = '$user_id'\n"
. " union\n"
. " select first_user_id from friends where second_user_id = '$user_id') limit 20";
$result_not_friends=mysqli_query($dbc,$sql)
or die("error in fetching");
// print_r($row_not_friends);
?>
<table class="table table-hover table-bordered">
<h1>Users</h1>
<tbody>
<?php
while ( $row_not_friends = mysqli_fetch_array($result_not_friends))
{
if ( $row_not_friends['user_id'] != $user_id )
{
?>
<tr>
<td>
<?php echo $row_not_friends['user_name']; ?>
</td>
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i></td>
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>">
</tr>
<?php
}
}
?>
</tbody>
</table>
Now I am accessing each value in a javascript file as follow:
// Here a request is send
$('.send_request').on('click',
function (e) {
e.preventDefault();
var first = $('.send_first').val();
var second = $('.send_second').val();
alert('firt id is ' + first);
alert('second id is ' + second);
$.ajax(
{
url:'send_process.php',
type:'POST',
dataType:"json",
data: { first: first, second: second },
success:function(data)
{
if(data.send_success)
{
window.location.href = "friend.php";
}
else
{
alert("something went wrong");
window.location.href = "friend.php";
}
},
error : function() { console.log(arguments); }
}
);
});
But here var second = $('.send_second').val(); gives only top-most element value of $row_not_friends['user_id'] . When I am echoing the value, it gives correct result.
Please help me.
Because you are selecting ALL the elements in the page and the default behavior of val() is it returns the first item. It has no clue you want the nth item.
First thing is you need to fix your HTML it is invalid. You can not have an input as a sibling of a tr element. You need to move it inside of a TD.
<!-- here I am sending request and processing it via ajax -->
<td><i class="fa fa-user-plus send_request"></i> <!-- removed the closing td from here -->
<input type="hidden" class="send_second" value="<?php echo $row_not_friends['user_id']; ?>">
<input type="hidden" class="send_first" value="<?php echo $user_id; ?>"></td> <!-- moved the closing td to here -->
</tr>
You need to find the elements in the same row as the button you clicked. Since the hidden inputs are npw siblings of the button you can use the siblings() method.
var btn = $(this);
var first = btn.siblings('.send_first').val();
var second = btn.siblings('.send_second').val();

Javascript Price and Quantity adjustment within an array loop

I'm using a text box as a "quantity" field that updates a < p > with the subtotal of the item. I have this working great for the first item in my while loop (php). Each consecutive item does not adjust the span however.
My PHP:
<?php $furniture = mysql_query("SELECT * FROM tbl_furniture WHERE furniture_active = '1'");
while($row = mysql_fetch_array($furniture))
{
?>
<div class="one-third column">
<h3><img src="images/<?php echo $row['furniture_image1'];?>" width="300" height="300"></h3>
<?php $furniture_price = $row['furniture_price'];
$furniture_id = $row['furniture_id'];?>
<div id="content">
<table width="100%" border="0">
<tr>
<td class="price">
<p class="furn_itemprice" id="price">£<?php echo $furniture_price;?></p><input name="price[]" type="hidden" value="<?php echo $furniture_price;?>"><input name="furniture_id[]" type="hidden" value="<?php echo $furniture_id;?>">
</td>
<td class="quantity">
<input name="qty[]" type="text" id="quantity" value="" class="calc"/><br />
</td>
</tr>
</table>
<br />
<p class="totals" id="subtotal">Sub-total:</p>
</div>
</p>
<?php } ?>
With the javascript function looking like this:
var stock = {}
window.onload=function() {
var inputs = document.getElementsByTagName('input');
for (var i=0;i<inputs.length;i++) {
if (inputs[i].type=="text" && inputs[i].id.indexOf('quantity')!=-1) {
var name = inputs[i].id.replace('quantity','');
stock[name] = parseFloat(document.getElementById('price').innerHTML.replace('£',''))
inputs[i].onchange=function() {
var total = 0;
for (var furn_item in stock) {
var q = document.getElementById("quantity").value;
total += (isNaN(q) || q=="")?0:parseInt(q)*stock[furn_item]
}
document.getElementById('subtotal').innerHTML="Sub-total: £"+total.toFixed(2);
}
}
}
}
I'm not sure what I need to do, but I presume somehow the problem lies with the Sub-total: not having a unique id/name??
you could give each element a unique id like:
<?php $furniture = mysql_query("SELECT * FROM tbl_furniture WHERE furniture_active = '1'");
$i=0 // init counter
while($row = mysql_fetch_array($furniture))
{...
...
<p class="furn_itemprice" id="price<?php echo $i++;?>">£<?php ec... // append counter to element id
...
and
var q = document.getElementById("quantity"+i).value;
Also you should not use mysql* for new code, it's been superceeded by mysqli*
personally I prefer PDO for php database connections
As said in the comment, your code generates multiple HTML elements with the same id. An id must be unique on the entire page. That's why your code doesn't work.
What you want to achieve is to give different ids for every row / piece of furniture and bind the JavaScript handlers accordingly. It's easier with jQuery. You could create quantity fields that have an attribute that contains the price:
<input name="qty[]" type="text" data-price="<?php echo $furniture_price;?>" value="" class="quantity"/>
Then, in jQuery, you could get all elements with the class quantity:
var sum = 0;
$(".quantity").each(function() {
sum += $(this).val() * $(this).attr('data-price');
});
$("#subtotal").text(sum);
So, you can achieve something similar without jQuery, for sure. I hope this gives you an idea how to solve your problem.

Problems with simple Javascript form validation

I'm working on putting together a multi-page set of forms that are interlinked by a session and use Javascript for form validation whenever each section is submitted. My first form is working fantastically. My second one, not so much. It's a dynamically created form that depends on the previous form for the number of drop down boxes (between 1 and 20) that are populated from a database. I will spare you all the query code to create the array that fills in my dropdowns and get straight to the form validation script and then the form itself.
The validation script from the head without the <script> tags:
function validateForm()
{
var count = <?php echo $_SESSION['credits']; ?>;
var i = 1;
for (i = 1; i <= count; i++)
{
var j = i;
for (j++; j <= count; j++)
{
var a = document.forms["addcredits"]["creditdropdown_"+i].value;
var b = document.forms["addcredits"]["creditdropdown_"+j].value;
if ((a == b) && (a != 0))
{
alert('Cannot select the same writer more than once.');
return false;
}
}
}
var foundOne = false;
var h = 1;
while (h <= count && !foundOne)
{
if (document.forms["addcredits"]["creditdropdown_"+h].value != 0)
{
foundOne = true;
}
h++;
}
if (!foundOne)
{
alert('You must select at least one writer to credit.');
return false;
}
}
The form code:
<form id="addcredits" class="appintro" method="post" action="recordcheck.php" onsubmit="return validateForm()">
<div class="form_description">
<h2>Song Title Submission</h2>
<p>Step 2: Select writing credits for song title</p>
</div>
<ul>
<?php
for ($i = 1; $i <= $_SESSION['credits']; $i++)
{ ?>
<li id="li_<?php echo $i; ?>">
<label class="description" for="creditdropdown_<?php echo $i; ?>">Song Credit #<?php echo $i; ?>:</label>
<select "creditdropdown_<?php echo $i; ?>">
<option value="0">Select a writer</option>
<?php foreach ($writers as $key => $writer) { ?>
<option value="<?php echo $key; ?>"><?php echo $writer; ?></option>
<?php } ?>
</select>
<p class="guidelines" id="guidelines_<?php echo $i; ?>">Writer not found in database? Add them here.</p>
</li>
<?php } ?>
<li id="buttons">
<input type="hidden" name="form_id" value="2">
<input type="hidden" name="submit" value="1">
<input id="nextButton" class="button_text" type="submit" name="submit" value="Next">
</li>
</ul>
</form>
Neither of the alert windows pop-up when I click Next and if I stick random debugg-ing alert windows into the validation script, the only ones I was able to get to show up were the ones I stuck at the beginning of the code. The furthest I got them to work was the first assignment of a after that, not even the debuggers would show. I'm assuming I'm doing something incorrectly in the assignment or there is something wrong with the values in the dropdown? Either way, I'm stumped.
I'd say the problem is in your HTML:
<select "creditdropdown_<?php echo $i; ?>">
You are specifying, presumably, the name attribute but you forgot the name= part. Try this:
<select name="creditdropdown_<?php echo $i; ?>">
In your validation function when you get to this line:
var a = document.forms["addcredits"]["creditdropdown_"+i].value;
You'll find you have an error because document.forms["addcredits"]["creditdropdown_"+i] is undefined because of the missing name= in the html and undefined can't have a .value property.
(By the way, debugging with alert() is useful very occasionally, but you're much better off using the built in developer tools in Chrome - just hit (I think) ctrl-shift-J to get the JS console - or download FireBug for Firefox. Or use IE's developer toolbar. Use console.log() instead of alert(), and/or step through the code until you find the problem.)

Categories