getElementById can't getting value of html id [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
If I chose select option value 3, then show 3 textbox.
1.this picture is result of what i want.
but now wrong result like this.
(use style_display_on(), visible / hidden, none)
But it dosen't work. Am I missing something?
(php array converts to javascript array ,
and then count array from php is being used by getElementById value from javascript....)
<?php
$arr[0] = "10.1.35.31";
$arr[1] = "10.1.35.122";
$arr[2] = "10.1.35.133";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/main.css">
<script type="text/javascript">
function getR() {
document.getElementById("ipcnt").value = "<?php echo count($arr); ?>";
<?php
for($i = 0; $i < count($arr); $i++) {
echo "document.getElementById(\"" . "mmeremoteip" . $i . "\").value = \"" . $arr[$i]. "\";\n";
}
?>
}
function mmeswitch(){
<?php
for($i = 0; $i < 8; $i++){
echo "document.getElementById(\"mmeremoteip". $i . "\").style.visibility = \"hidden\";\n";
echo "document.getElementById(\"mmeremoteip". $i . "\").style.display = \"none\";\n";
}
for($i = 0; $i < 8; $i++){
echo "if( document.getElementById(\"ipcnt\").value == " . ($i+1) . " ) { \n";
for($j = 0; $j < $i+1; $j++) {
echo "document.getElementById(\"mmeremoteip". $j . "\").style.visibility = \"visible\";\n";
echo "document.getElementById(\"mmeremoteip". $j . "\").style.display = style_display_on();\n";
}
echo "}\n";
}
?>
</script>
</head>
<body onLoad="getR();">
<form name="save" method="post">
<h1>TEST</h1>
<table>
<tr id="ipcnt"><td colspan="2">No. of IP</td>
<td><select name="ipcnt" size="1" onChange="mmeswitch();">
<?php
for($i = 1; $i <= 8; $i++) {
echo "<option value='". $i ."'>". $i ."</option>\n";
}
?>
</select></td>
</tr>
<?php
for($i = 0; $i < 8; $i++) {
echo "<tr id=\"mmeremoteip".$i."\"><td class=\"param\" colspan=\"2\">MME Remote IP" . ($i+1) . "</td>\n";
echo "<td><input type=\"text\" name=\"mmeremoteip" . $i . "\" class=\"inputParam\" size=\"20\" maxlength=\"15\" value=\"".$arr[$i] ."\"></td></tr>\n";
}
?>
</table>
</body>
</html>

In this fiddle I posted a working example of your code in vanilla js. The js code for this is:
document.body.onload = init;
let arr = [1,2,3,4,5]; // Array is from php like
/*
let arr = JSON.parse('<?php echo json_encode($arr); ?>'); // In case you don't know what is does read more about json
*/
// function called when page is loaded
function init () {
// this creates textfields for each 'ip'
for(let i=0;i<arr.length;i++){
let el = document.createElement('input'); // create textfield
el.setAttribute('type','text'); // set it to text field
el.className = 'textField'; // set class for later use
el.id = 'textField'+i; // set id
el.value = arr[i]; // set value(IP)
document.getElementById('container').appendChild(el); // add to the page
}
document.getElementById('textFieldSelect').addEventListener('change',onSelectChange); // add action to select
onSelectChange(); // "trigger" select when page is loaded
}
function onSelectChange(){
var val = document.getElementById('textFieldSelect').value; // how many textfields shall there be
// hide all textfields
document.querySelectorAll('.textField').forEach(function(elem,idx){
elem.style = 'display: none';
});
//show exactly 'val' textfields
for(let i = 0;i<val;i++){
document.getElementById('textField'+i).style='display:block;';
}
}
https://jsfiddle.net/tnrrhx0d/1/

Related

Retrieve the filtered data from HTML table and format it into array

I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
$conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);
echo "<table id='myTable'>";
echo "<thead><tr><th>Article</th>
<th>Description</th>
<th>Property Number</th>
</tr></thead>";
echo "<tbody>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['article'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['propertyNumber'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Close the database connection
mysqli_close($conn);
?>
<form action="" method="POST">
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
<input type="submit" id="generate" name="generate" value="Submit">
</form>
This is my code in filtering the records:
<script>
function filterTable() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
if (isset($_POST['generate'])) {
$spreadsheet = IOFactory::load('Template.xls');
//This is the part where I don't know what to put.
$data = array();
$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
$worksheet->setCellValue('A'.$row, $item['article']);
$worksheet->setCellValue('B'.$row, $item['description']);
$worksheet->setCellValue('C'.$row, $item['propertyNumber']);
// ...
$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>
I tried every possible way that I know but still didn't got my expected result.
If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;
I strongly suggest you use AJAX here instead.

cannot get id of li on click event

I have this code to show tabs.
$start = strtotime($_GET['date']);
$dates = array();
for ($i = 0; $i <= 7; $i++) {
$date = date('Y-m-d', strtotime("+$i day", $start));
$date1 = $date;
$day = date('D', strtotime($date1));
$date = explode('-', $date);
$dateinput = date('Y-m-d', strtotime("+$i day", $start));
$date = $date[2];
echo '<li class="lia" id="'.$dateinput.'"><input type="hidden" class="getdate" value="'.$dateinput.'">' . $date . ' ' . $day . '</li>';
}
I have a date-picker and i want to get the id of li by on change function of datepicker. I am using this code at moment.
$("#calendar-<?php echo $post->ID?>").on("change",function(){
var date = $(this).val();
console.log(date);
var libtn= $("li.lia").find("li").attr("id");
console.log(libtn);
alert(libtn);
});
It is showing undefined in alert box. Where i am doing wrong?
Replace
var libtn= $("li.lia").find("li").attr("id");
With
var libtn = $("li.lia").attr("id");
And check.
You can not find element itself inside same element.
EDIT
I am expecting you will have lia class everywhere means on every li.
Then,
Here is the code,
$("li.lia").each(function(i,j){
console.log($(this).attr("id")); // use as per your requirement
});

PHP/HTML button picture change and script call

I have a page with buttons that a user clicks on.
When the button gets clicked I need it to change the image and call a php script to save the change.
I somehow can't get the button to do both, it changes the pic but won't call the php.
CODE:
<?php
$db = new PDO('mysql:host=localhost;dbname=MySettings;charset=utf8mb4', 'TestUser', '1234567890');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$mytable = $_SESSION["SESS_myuserid"];
if($mytable == null)
{$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';}
$stmt = $db->prepare("SELECT * FROM ".$mytable);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn = null;
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo "$('#newCode').load('Monitor.php?id=".$TheId."&Table=".$mytable."');";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo '}';
}
echo'</script>';
$myLeft=0;
$myTop=0;
$myRow=0;
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
$ThePic = "images/Boff.png";
}
else{
$ThePic = "images/Bon.png";
}
echo '<div>';
echo ' ';
echo '</div>';
$myTop=$myTop + 30;
$myRow=$myRow + 1;
if ($myRow == 12){
$myRow=0;
$myTop=0;
if ($myLeft == 0){
$myLeft = 292;
}
else {
$myLeft = 615;
}
}
}
}
catch(PDOException $e) {
$url='login.php';
echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$url.'">';
}
?>
Fixed :
Changed the script function. Added a hidden div to be called to load the php which outputs nothing so stays invisible.
echo'<script>';
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$TheId = $result[$i]['Id'];
$TheFunction = $result[$i]['TheFunction'];
$TheSetting = $result[$i]['TheSetting'];
if ($TheSetting == "0"){
echo 'var newsrc'.$TheId.' = "on.jpg";';
}
else{
echo 'var newsrc'.$TheId.' = "off.jpg";';
}
echo 'function changeImage'.$TheId.'() {';
echo 'if ( newsrc'.$TheId.' == "off.jpg" ) {';
echo "document.getElementById('pic".$TheId."').src = '/images/Boff.png';";
echo 'newsrc'.$TheId.' = "on.jpg";';
echo '}';
echo 'else {';
echo "document.getElementById('pic".$TheId."').src = '/images/Bon.png';";
echo 'newsrc'.$TheId.' = "off.jpg";';
echo '}';
echo' $("#HtmlConvo").load("Monitor.php?id='.$TheId.'&Table='.$mytable.'");';
echo '}';
}
echo'</script>';

Getting NAN on safari when using a javascript date

I am working on something, in which I am required to subtract 2 dates from one another, the difference would then be multiplied by the price per night of the event.
The issue I am having is that, while this works perfectly when using Chrome or Firefox, I am getting "NAN if I am using safari.
Date to and from are obtained using the php code below:
<?php
// displays days with leading 0s
$options = array();
for ($i=1; $i<32; $i++) {
$theday = date('d', mktime(0,0,0,0,$i,2000));
$sel = ($i == date('d') ? 'selected="selected"' : '');
$options[] = "<option value= \"{$theday}\" {$sel}>{$theday}
</option>";
}
$options_list = join("\r\n", $options);
echo "<div class='select' id='date'><select class=\"short-input day-to\" name=\"day_to\">{$options_list}</select></div>";
?>
<?php
$options = array();
for ($i = 1; $i<13; $i++) {
$themonth = date('F', mktime(0,0,0,$i,2, 2000));
$month = date('m', mktime(0,0,0,$i,2,2000));
$sel =($i == date('n') ? ' selected="selected"' : '');
$options[] = "<option value=\"{$month}\" {$sel}>{$themonth}
</option>";
}
$options_list = join("\r\n", $options);
echo "<div class='select' id='month'><select class=\"short-input month-to\" name=\"month_to\" size=\"1\">{$options_list}</select></div>";
?>
<?php
/* build selection list for the year */
$today = time(); // stores today's date
$startYr = date("Y", $today); // get the year from $today
echo "<div class='select' id='year'>
<select class=\"short-input year-to\" name='year_to'>\n";
for ($year=$startYr;$year<=$startYr+10;$year++)
{
echo " <option value= $year";
if ($startYr == $year)
{
echo "";
}
echo " > $year</option>\n";
}
echo "</select>\n</div>\n";
?>
http://jsfiddle.net/ju097j4z/#
Are there any solutions to this.
instead of Date.parse(monthFrom + ' ' + dayFrom + ' ' + yearFrom); in your fiddle use new Date(yearFrom, monthFrom, dayFrom); *note that in js month starts with 0

Send and set 3 selected values from Dropdown menu to JavaScript function PHP

I have three drop down menus:
<?php
if(isset($som)) {
=======first drop down=======
echo "<select id="."som-patch1"." class="."form-control".">";
echo "<option value="."select".">Please Select SOM patch...</option>";
for ($i=0; $i < count($som) ; $i++) {
echo '<option value="'.$som[$i]['som'].'">'.$som[$i]['som'].' </option>';
}
echo "</select>";
=======second drop down=======
echo "<select id="."som-patch1-month"." class="."form-control".">";
echo "<option value="."select".">Please Select Month ...</option>";
for ($i=0; $i < 12 ; $i++) {
$month = date('F', strtotime('-'.$i.' month', strtotime(date('Y-m-01'))));
echo '<option value="'.$month.'">'.$month.'</option>';
}
echo "</select>";
=======third drop down=======
echo "<select id="."som-patch1-year"." class="."form-control".">";
echo "<option value="."select".">Please Select Year ...</option>";
for ($i=0; $i < 12 ; $i++) {
$year = date('Y', strtotime('-'.$i.' year', strtotime(date('Y-m-01'))));
echo '<option value="'.$year.'">'.$year.'</option>';
}
echo "</select>";
}
?>
I can successfully send the selected values to the following JavaScript function:
$('[id^=som-patch1]').on('change', function() {
alert( this.value );
});
The problem I have is:
I am unable to set the relevant values in the variables so that I could call the add_som_donut_chart_org_data() method.
Also I need to make sure all THREE values have been selected before the function call.
I have tried the following:
$('[id^=som-patch1]').on('change', function() {
var som = null;
var month = null;
var year = null;
if (id=='som-patch1'){
som = this.value;
}
alert( som );
});
But this doesn't set the som value.
The desired outcome should be:
if (som !== null && month !== null && year !== null) {add_som_donut_chart_org_data(som,month,year)}
Thanks in advance.
UPDATE: The following code resolved the issue
$('[id^=som-patch1]').on('change', function() {
var id = $(this).attr("id");
if (id == 'som-patch1') {
som = this.value;
}
if (id == 'som-patch1-month') {
month = this.value;
}
if (id == 'som-patch1-year') {
year = this.value;
}
if (som !== null && month !== null && year !== null) {
add_som_donut_chart_org_data(som,month,year);
}
});
As per your current code condition if (id=='som-patch1') would never be true, because id is not defined yet. Hence it will not set som variable. The reason is very basic that you have not defined id variable in your code. Before your condition use following code:
var id = $(this).attr("id");

Categories