This page generates a table contaning routes, and in the end of every "tr" there is a button that should copy the text inside those 2 fields in each line to the Name3 and Name 4 inputs, respectively.
But when I click, nothing is happening, I think that getElementById("Name1_".index) is making the hole code invalid, but how to make it correctly?
<script type="text/javascript">
function copyTextValue(key) {
var index = key;
var text1 = document.getElementById("Name1_".index).value;
var text2 = document.getElementById("Name2_".index).value;
document.getElementById("Name3").value = text1;
document.getElementById("Name4").value = text2;
}
</script>
<input type="text" id='Name3' />
<input type="text" id='Name4' />
<?php
$get_rotas = file_get_contents('routes.txt');
$array = explode("\r\n", $get_rotas);
foreach($array as $key=>$rota) {
//Route(rota) Example: TRM J169 BLH V16 BXK|3666
$rota_distance = explode("|", $rota);
echo "<tr bordercolor='#FFFFFF'>";
echo "<td><input type=\"text\" id=\"Name1_$key\" value='" . $rota_distance[0] . "'/></td>";
echo "<td><input type=\"text\" id=\"Name2_$key\" value='" . $rota_distance[1] . "'/></td>";
echo "<td><input type=\"button\" onclick=\"copyTextValue($key);\" value=\"Copy\" ></td>";
echo "</tr>";
}
?>
For concatenating strings in JavaScript use + instead of ..
Related
while ($row= mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row["madh"] . "</td>";
.....
echo "<td><input type='button' onclick='detail()' value='d'></td>";
echo "</tr>";
}
function detail(data){}
i want to pass $row["madh"] to detail() but I have problem with "" and ''.
put Id here
echo "<td id="id_madh">" . $row["madh"] . "</td>";
when you click on button as in your code
echo "<td><input type='button' onclick='detail()' value='d'></td>";
you can get value using jquery like this
function detail(){
var value_madh = $('#id_madh').val();
}
Though isn't the best option, you can try to separate that echo line into different parts
echo "<td><input type='button' onclick='detail(" . $row["madh"] . ")' value='d'></td>";
I think you just need to escape the quotes?
echo "<td><input type='button' onclick='detail($row[\"madh\"])' value='d'></td>";
note that the function will be immediately involved on page load, you probably want to wrote this within a closure so it's not actually invoked until it's clicked:
echo "<td><input type='button' onclick='function(){ detail($row[\"madh\"]) }' value='d'></td>";
First put $row["madh"] in a variable;
$var = $row["madh"];
then
echo "<td><input type='button' onclick='detail('$var')' value='d'></td>";
I'm using solr solarium for a multilingual corpus. Everything works as expected with regard to the retrieval of information in every language. In the following code I have two hidden input elements where I pass two php variables and then I'm trying to post the values of those elements to a javascript function in order to add a row to an existing table and display the values of my variables in its cells.
My php code is this:
...
if ($highlightedDoc) {
foreach ($highlightedDoc as $field => $highlight) {
$hlight = implode(' (...) ', $highlight);
echo '<table id="lngData" text-align:left; border:none; cellpadding="02" cellspacing="02">';
echo '<tr><td><b>' . $counter . '</b></td><td>' . $subj_en. '</td><td>' . $hlight . '</td></tr>';
echo '<tr><td>' ."" . '</td><td>' . $subj_el . '</td><td>' .$con_el. '</td></tr>';
echo '<tr><td><input id="q" name="q" type="hidden" value=' . $subj_fr . '/></td></tr>';
echo '<tr><td><input id="s" name="s" type="hidden" value='. $con_fr . '/></td></tr>';
echo '<tr><td>' ."" . '</td><td><button onclick="showLng(q, s);">Create row</button></td><td><button onclick="myDeleteFunction()">Delete row</button></td></tr>';
echo '</table>';
}
This is my javascript function showLng:
function showLng(x, y) {
var table = document.getElementById("lngData");
x = document.getElementById("q").value;
y = document.getElementById("s").value;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "";
cell2.innerHTML = x;
cell3.innerHTML = y;
}
The above onclick event adds the table row but it truncates the result sentence. It outputs the first word only of each sentence. Could someone help me with this? I read quite a few posts on how to pass php string variables to javascript but no good.
Any help would be greatly appreciated. Thank you in advance.
Your main question is how to "pass" PHP data to Javascript... I remember this was confusing to me at first so let me explain step by step:
Let's say you output Javascript with PHP like this:
echo '<script> console.log("Hello"); </script>';
That will output string that is a script tag, and inside it we call console.log function passing as parameter the string "Hello". It all is just a string.
Now let's put the "Hello" string inside a variable in PHP:
$log = 'Hello';
echo '<script> console.log("' . $log . '"); </script>';
Now we've "passed" PHP data to Javascript. It's the same string as above.
Another example:
echo '<script>';
echo 'var hello = "";';
echo 'var world = "World";';
echo 'console.log(hello + " " + world);';
echo '<script>';
We want to fill the hello variable with PHP. So we just add it:
$helloString = 'Hello';
echo '<script>';
echo 'var hello = "' . echo $helloString . '";';
echo 'var world = "World";';
echo 'console.log(hello + " " + world);';
echo '<script>';
Notice that the PHP output is surrounded by " in Javascript, because even though we're outputing a string with PHP, if we ommit the " like this:
echo 'var hello = ' . echo $helloString . ';';
PHP won't add them neither, therefore the output in the browser will look like this:
var hello = Hello;
which is invalid, it must be:
var hello = "Hello";
You made this mistake in your code, in the HTML:
echo '<tr><td><input id="q" name="q" type="hidden" value=' . $subj_fr . '/></td></tr>';
So your output would be (assuming $subj_fr is a string "Hello World"):
<input ... value=Hello World />
Which is incorrect.
I notice that you're creating many tables with the same id (lngData), and your hidden inputs all have the same id too. I doubt that's intended is it?
In the following code a unique id is created for each table. I've also removed the hidden elements, and instead, the values are directly passed to the showLng function, along with the id of the table. I've also changed the way you build your HTML with PHP, I did this only to show you a different way (I'd say it looks cleaner) to output HTML with PHP, instead of using echo.
I don't know if fixing the duplicated ids is the answer to your question, but try it.
if ($highlightedDoc) {
$i = 0;
foreach ($highlightedDoc as $field => $highlight) {
$hlight = implode(' (...) ', $highlight);
$tableId = 'lngData' . $i;
?>
<table id="<?= $tableId ?>" style="text-align:left; border:none;" cellpadding="02" cellspacing="02">
<tr><td><b><?= $counter ?></b></td><td><?= $subj_en ?></td><td><?= $hlight ?></td></tr>
<tr><td><?= "" ?></td><td><?= $subj_el ?></td><td><?= $con_el ?></td></tr>
<tr><td><!-- removed unneeded hidden input --></td></tr>
<tr><td><!-- removed unneeded hidden input --></td></tr>
<tr><td><?= "" ?></td><td><button onclick="showLng('<?= $tableId ?>', '<?= $subj_fr ?>', '<?= $con_fr ?>');">Create row</button></td><td><button onclick="myDeleteFunction()">Delete row</button></td></tr>
</table>
<?php
$i++;
}
}
The showLng function:
function showLng(tableId, x, y) {
var table = document.getElementById(tableId);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "";
cell2.innerHTML = x;
cell3.innerHTML = y;
}
I already get the id from a php loop for my checkboxes, and pass them as a string(maybe not because I could not split them with comma) in parameter, then I need to check if the checkbox is checked in javascript using the ids I passed through.
It doesnt seem like I can split it in javascript as well, and after I ran the for loop, the data is undefined in the new string.
Do you have any ideas? Please help
here is my php
echo "<div id='addstock'>";
$ids = '';
while($row_add = mysqli_fetch_array($result_add)){
$id=$row_add['id'];
$company = $row_add['companyname'];
//create checkbox for company
echo "<p class='checkbox'><input type='checkbox' name='stocks' id='".$id."' value='".$id."'>".$company."</p><br>";
$ids .= $id;
}
echo "</div>";
echo "<p class='input'><input type='submit' class='submitbutton' value='Submit' onclick='updatetable(".$ids.",".$user.")'></p>";
here is my javascript
//update table after add to stock
function updatetable(ids,user){
var url = "update.php";
//var res= ids.split(" ");
alert(ids);
var stocks = "";
//check if the checkbox is checked
for(var id in ids){
if(document.getElementById(ids[id]).checked)
{
stocks += ids[id];
alert(ids[id]);
}
}
//alert(stocks);
var data = "ids="+stocks+"&user="+user;
alert(data);
ajaxRequest(url, "POST", data, true, proceedUpdate);
}
function proceedUpdate(response){
target_div = document.getElementById("tablediv");
target_div.innerHTML = response;
}
Try this:
<div id="addstock">
<?php
$ids = array();
while($row = mysqli_fetch_array($result_add)) {
$ids[] = $row_add['id'];
echo '<p class="checkbox"><input type="checkbox" name="stocks" id="' . htmlspecialchars($id) . '" value="' . htmlspecialchars($id) . '">' . htmlspecialchars($company). '</p><br>' . "\n";
}
?>
</div>
<p class="input">
<input type="submit" class="submitbutton" value="Submit" onclick="updatetable('<?php echo htmlspecialchars(implode(',', $ids)); ?>', '<?php echo htmlspecialchars($user); ?>')">
</p>
I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.
I have multiple input elements arranged in 16 rows and 5 columns (Just like a grid) . The contents of the 16 rows are inserted into a mysql table as 16 records with each record contains 5 fields. I want a method to get the value of all the input into an array using jquery and pass this to a ajax post request.
dataentry.php contains this code
jQuery('#metentry').submit(function(e){
e.preventDefault();
// getting data from form to variables
var date=jQuery('#stddate').val();
var kgsunit=jQuery('#unit').val();
var kgsshift=jQuery('#shift').val();
//sending data to script
jQuery.post("get_blank_form.php", {
"date":date,
'unit':kgsunit,
'shift':kgsshift,
}, function(data) {
//displaying message
jQuery('#blankform').html(data);
jQuery('#formpanel').hide();
});
get_blank_form.php contains this code:
echo'<form id="shiftentry" name="shiftentry" >';
echo "Date:<input id=shiftdate value='".$date."'/>";
echo "Unit:<input id=shiftdate value='".$unit."'/>";
echo "Shift:<input id=shiftdate value='".$shift."'/><br/>";
echo "<table><tr><th>No</th><th>Ele</th><th>Location</th><th>Drate </th><th>H3 Val </th><th>Part </th> <th>Iod</th><th>Cont. </th></tr>";
while($row2=mysql_fetch_array($result_sec))
{
echo "<tr>";
echo "<td>".++$rc."</td>";
echo "<td><input size='5' id='".$row2['ele']."' value='".$row2['ele']."' /></td>";
echo "<td><input id='".$row2['loc_id']."' value='".$row2['loc']."' /></td>";
echo "<td><input size='5' id='drate".$rc."' value='".$row2['drate']."'/></td>";
echo "<td><input size='5' id='h3".$rc."' value='0' /></td>";
echo "<td><input size='5' id='part".$rc."' value='0' /></td>";
echo "<td><input size='5' id='iod".$rc."' value='0' /></td>";
echo "<td><input size='5' id='cont".$rc."' value='0' /></td>";
echo "</tr>";
}
echo " </table>";
echo '<div align="center">';
echo '<input type="submit" id="submit2" name="submit2" value="Submit" width="30" />';
echo '</div>';
echo '</form>';
Both the above scripts are working and this will add a form"shiftentry" to the DOM in dataentry.php. This form conains around 21 rows and 8 columns containing input elements. I want a method to get the values in this 21 x 8 input elements and pass it to a jQuery post request. Since the form is added after the DOM is loaded, how to get the value?
My final aim is to append this 21 rows into a mysql table. This part I knew, once I get all the values. Any suggestions ?
I have this function which create a multi dimensional array of input values. But in this casethe 'form1' is loaded before DOM is completed. But in the above scenario, form is dynamically added after DOM loding is completed
jQuery('#form1').submit(function(e){
e.preventDefault();
var arr = jQuery('#form1 tr:gt(0)').map(function() {
return [jQuery('input', this).map(function() {
return this.value;
}).get()];
}).get();
});
I also have another jquery script in this page which is used to traverse through the input boxes (obviously, these input boxes are loaded after DOM)
jQuery(document).delegate('input','keyup',function(e){
if(e.which==39)
jQuery(this).closest('td').next().find('input').focus();
else if(e.which==37)
jQuery(this).closest('td').prev().find('input').focus();
else if(e.which==40)
jQuery(this).closest('tr').next().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
else if(e.which==38)
jQuery(this).closest('tr').prev().find('td:eq('+jQuery(this).closest('td').index()+')').find('input').focus();
});
How can I use the delegate option in the script used for traverse in the script for getting input values?