creating table header with javascript - javascript

I am having two issues with my table, One of them is that I want it to only show when I click a button but when i do it shows and then hides and the other is how do I send a parameter based on the select option to this createtable function
This is part of my code
<form class="form-inline" role="form">
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button type="submit" id = "load" class="btn btn-default">Load</button>
</form>
<div id ="test">
</div>
<script type = "text/javascript">
$(document).ready(function(){
$("#example").hide();
$("#load").click(function(e){
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
....
....
$('#test').append(contents); append it to div
}
$(document).ready(createTable(1));
</script>
Thank you

The reason that the table is getting hidden again is because you've set type="submit" on your button. This means that after the click event handler is done processing, it will submit the form, which causes the page to reload. When it reloads, the table is hidden again. If you change it to type="button" that will prevent that.
You can get the currently selected value of the select, using jquery, with this:
$('#theselect').val();
You can then pass this in to your createTable function (or just get the value using that code, from within the function itself).
Also, it's a really bad idea to create markup from within your JavaScript. It's going to make future maintenance a nightmare, and if it gets complex enough, it could start causing performance issues. It's much better to keep your markup separate, and then show/hide it as needed via JS.

Take a look at this example. It gets the selected values, and inserts them into a table, and table into the dom... HTH.
$(document).ready(function(){
$("#load").click(function(e){
var bits = $('#theselect').val();
$("#example").hide();
$('#test').html('');
createTable(bits)
$("#example").show();
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border><tbody><tr><td>"+param+"</td></tr></tbody></table>";
$('#test').append(contents)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple class="form-control" style = "width:250px"id = "theselect">
<option selected disabled> Chose a number </option>
<option> all </option>
<option> 1 </option>
<option> 2 </option>
</select>
<button id = "load" class="btn btn-default">Load</button>
<div id ="test"></div>

Try this:
$(document).ready(function(){
$("#load").click(function(e){
createTable($("#theselect").val());
$("#example").show(); // In case of class 'display' gives it 'display:none'
});
});
function createTable(param){
var contents = "<table id='example' class='display' cellspacing='0' width='100%' border>";
$('#test').append(contents);
}
#example doesn't exists at the beginning so I removed $("#example").hide().

Related

how can insert all table's rows from script to database at once

I have a problem ... here the create table's row each time user press Add button , How I can send all the data of the table to database at once cuz when press submit only last row inserted into database but not all the table but it should submit all rows with all data
I'm new in php so I don't have a lot in php code
this is the php code
<?php
include_once("dbinfo.php");
session_start();
$name= $_SESSION['user'];
if(isset($_POST['savepav'])){
date_default_timezone_set("Asia/Riyadh");
$pavdate= date("Y/m/d");
$pavtime=date("h:i:sa");
$pavloca=$_POST['pavlocation'];
$pavtype=$_POST['ddlPassport'];
$pavdist=$_POST['pavedist'];
$pavplan=$_POST['pavplan'];
$pavseve=$_POST['pavseverity'];
echo "<script>alert(' Pavement data saved successfully ');</script>";
$query="INSERT INTO `pevement`(`userName`, `plocation`, `pavType`, `padistr`, `pavplan`, `severity`, `pavdate`, `pavtime`) VALUES ('$name' ,'$pavloca', '$pavtype', '$pavdist' ,'$pavplan', '$pavseve', '$pavdate' ,'$pavtime')";
$result_query=mysqli_query($conn,$query);
}
?>
this is script code
<script>
function AddData() {
var rows = "";
var name = document.getElementById("locapavm").value;
var city = document.getElementById("sevepavm").value;
var plan = document.getElementById("planpavm").value;
rows += "<tr><td>" + name + "</td><td>" + city + "</td><td>" + plan + "</td><td><button onclick = deleterow(this)>Delete</button></td></tr>";
$(rows).appendTo("#list tbody");
}
function ResetForm() {
document.getElementById("person").reset();
}
function deleterow(el) {
$(el).closest('tr').remove();
}
</script>
and HTML
<html>
<div id = "data">
<form id = "person">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="col-12" style="width: 1514px">
<select id = "locapavm" name = "pavlocation" style="width: 26%">
<option value="">- Location -</option>
<option value="Runway 17">Runway 17</option>
<option value="Runway 35">Runway 35</option>
<option value="Runway 18">Runway 18</option>
<option value="Runway 36">Runway 36</option>
</select><br>
<div class="col-12">
<select id = "ddlPassport" name = "ddlPassport" style="width: 26%" onchange = "ShowHideDiv()">
<option value="">- Pavement Type -</option>
<option value="Flexible Pavement (Asphalt)">Flexible Pavement (Asphalt)</option>
<option value="Rigid Pavement (Concrete)">Rigid Pavement (Concrete)</option>
</select>
</div><br/>
<div class="col-12" style="width: 1514px">
<select id="pavdistrees" name="pavedist" style="width: 26%">
<option value="">- Distress selections - </option>
</select><br> </div>
<div class="col-12" style="width: 1514px">
<select id="sevepavm" name="pavseverity" style="width: 26%">
<option value="">- Severity -</option>
<option value="Low">Low</option>
<option value="Medium"> Medium</option>
<option value="High">High</option>
</select><br> </div>
<!----------------------------------------------------------------------->
<p class="auto-style1">Maintenance Plan:</p>
<textarea id="planpavm" name="pavplan" style="width: 572px; height: 129px" ></textarea><br>
<input id = "person" type = "reset" value = " Reset " onclick = "ResetForm()">
<input id = "button" type = "button" value = " Add " onclick = "AddData()">
</form>
</div>
<div id = "tab" style="width: 76%">
<table style="width: 96%" id = "list" cellspacing = "0px" cellpadding = "20px" text-align = "center">
<thead>
<tr>
<td>Location</td>
<td>Pavement Type</td>
<td>Type Distrees</td>
<td>Severity</td>
<td style="width: 396px">Maintenance Plan</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<br><input type="submit" name="savepav" value="Submit"/>
</html>
I see you are using JQuery, so just based on that I think XHR would be your best bet. If you are adding it to the table with the "add" button, then I don't really see the point of the "Submit" button other than to redirect to a different page, so I will omit it just for this example, and edit my answer later if you have a different plan for it.
Your PHP code looks fine, other than it is vulnerable to an SQL injection attack. To prevent this, I would call the mysql_real_escape_string method on all of the strings you are putting in the database like so:
$pavloca=mysql_real_escape_string($_POST['pavlocation']);
$pavtype=mysql_real_escape_string($_POST['ddlPassport']);
$pavdist=mysql_real_escape_string($_POST['pavedist']);
$pavplan=mysql_real_escape_string($_POST['pavplan']);
$pavseve=mysql_real_escape_string($_POST['pavseverity']);
For the HTML, I would give your Add button the type of submit, then add the action and method attributes to your opening form tag like so:
<form id = "person" method = "POST" action = "/path/to/php/page">
where /path/to/php/page is the path to the PHP page that adds everything to the database.
And finally for the JavaScript.
Instead of having the onclick attribute on your Add button, I would remove that then just add this bit of JQuery to your script tag:
$("#person").submit(function(d){
d.preventDefault();
AddData(new FormData(d.target));
})
Then for your AddData function add an input parameter for the form:
function AddData(form)
P.S, a little trick after you've done that, you can actually get the values by the name attribute rather than an id like so:
var name = form["pavlocation"];
var city = form["pavseverity"];
var plan = form["pavplan"];
Then last but not least, add this little bit of code to the end of your AddData() function:
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.send();
And that should be it!
NOTE: I did not test any of this, so I apologize for any typos or syntax errors. If this does not work, I will edit my answer accordingly.
EDIT: There were a couple out-of-order tags in the HTML you posted, so I ran it through an IDE to clean it up a bit, and created a JSFiddle for it here: https://jsfiddle.net/djy9vget/2/
You will have to change the action="/path/to/php/page.php" bit to the actual path, but other than that this should work. I also noticed a typo in my original answer where XmlHttpRequest(); should be XMLHttpRequest();.
I also changed the ID of the Reset button from person (which is the same as the form), to reset.

Multiple Lines for "Change Dropdown values based on input in textfield"

First of all, thank you very much for supporting me in: Change Dropdown values based on input in textfield
Now I need to extend this feature.
Here is the code for changing the drop down menue based on a text field value (Thank you very much, Rion Williams):
https://jsfiddle.net/q5s24th2/
Now I would like to add more persons for which I can also enter the textfield value so that the drop down menu changes its content. Here I have created something to add more people:
https://jsfiddle.net/xsnLc48o/
<p id="maintable">1:
<input name="Year1" type="text" value="" />
<select name="Results1">
<option selected="selected" value="">please choose:</option>
<option value="300" data-under-18="100" data-over-18="300">300.-</option>
<option value="500" data-under-18="200" data-over-18="500">500.-</option>
<option value="1000" data-under-18="300" data-over-18="1000">1000.-</option>
<option value="1500" data-under-18="400" data-over-18="1500">1500.-</option>
<option value="2000" data-under-18="500" data-over-18="2000">2000.-</option>
<option value="2500" data-under-18="600" data-over-18="2500">2500.-</option>
</select>
<input name="Additional1" type="checkbox" title="Option" value="1" />Option
</p>
<p>
<input type="button" value="+ Add Person" id="addRows" />
</p>
Unfortunately for the added persons the drop down feature does not work (I have tried several things).
If anybody has an idea how to do it, I would be very happy.
Maybe there is a much better possibility than using the addRows/append feature.
Thank you in advance.
Best regards,
Andy
You could accomplish this by creating a function that would clone one of your existing rows and append it to content. It may be best to consider using a table to more easily organize your content :
<table id="maintable">
<tr class='person-row'>
<td class='person-number'>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>
And then adjusting your "add rows" function to clone the first row and then store a counter of the number of current users so that you can append that to the name attribute as expected :
// When you add a new user
$("#addRows").click(function(){
// Determine the next users number
var nextUser = $('.person-row').length + 1;
// Clone the first row
var nextUserRow = $('#maintable tr:first').clone();
// Update your attributes
$(nextUserRow).find('.person-number').text(nextUser + ':');
$(nextUserRow).find('.person-year').attr('name','Year' + nextUser).val('');
$(nextUserRow).find('.person-value').attr('name','Results' + nextUser);
$(nextUserRow).find('.person-additional').attr('name','Additional' + nextUser);
// Set the defaults for the row
$(nextUserRow).find('select option:not(:first)').each(function() {
var valueToUse = $(this).attr('data-over-18');
$(this).val(valueToUse).text(valueToUse + '.-');
});
// Append the row
$("#maintable").append(nextUserRow);
});
You can see a working example of this in action here and demonstrated below :

Elements not staying visible when function is called

I am creating an input to capture data related to fish that are caught. When the submit button is clicked I see a tr quickly show up then disappear, likewise, I see the console.log message show up for a split second then disappear.
Code is posted below, however running the code snippet doesn't look like it does when seen through a browser. I set up a live site for this here: http://fishrecord.jwhdesign.net/
I realize this is probably simple for most of you to figure out, so no need to tell me how dumb I am as I already know that.
Any help is very much appreciated.
function displayFishData() {
var table = document.getElementById("test"); //find "test" AKA the table
var row = table.insertRow(); //add row to that table
row.insertCell(); //insert cell to table
console.log("adding a row to the table");
}
table {
border: 1px solid black;
margin: 0 auto;
width: 80%;
}
<h1>Fish Record</h1>
<form>
Species:
<select>
<option value="blank"></option>
<option value="Northern Pike">Northern Pike</option>
<option value="Largemouth Bass">Largemouth Bass</option>
<option value="Smallmouth Bass">Smallmouth Bass</option>
<option value="Chain Pickerel">Chain Pickerel</option>
<option value="Pike-Pickerel Hybrid">Pike-Pickerel Hybrid</option>
<option value="Panfish">Panfish</option>
<option value="Other">Other</option>
</select>
Weight (lbs):
<input type='number'></input>
Length (inches):
<input type='number'></input>
Comments:
<input rows="1"></input>
<br>
<button onclick="displayFishData()">Submit</button>
</form>
<table id="test">
<thead>
<tr>
<th>Species</th>
<th>Weight (lbs)</th>
<th>Length (inches)</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This is because your button is currently refreshing the page,
If you add
type="button"
to the button it will display an extra tr and show the message in the console
The default value for the type attribute of button element is submit. And thus on click of the button it is submiting the form
Replace
<button onclick="displayFishData()">Submit</button>
to
<button type="button" onclick="displayFishData()">Submit</button>
First of all add the displayFishData() to the form not the button! it would look like this <form onsubmit="displayFishData()"> this would help you to control the form output in a better way.
BTW using <input type="submit" /> is a better practice than <button></button>
And for a simpler data inserting do the following:
var table = document.getElementById("test");
var row = table.insertRow();
var e1 = row.insertCell(0);
var e2 = row.insertCell(1);
// keep adding as much rows as you got
// this change the innerHTML
e1.innerHTML = "the data you got from a form element";
// repeat that

Using Javascript to create element, then assign onclick to call pikadate

First time poster, long time forager. I have a system I am developing, cleaning up the process I would like to use pikaday.js to help users select the date insted of typing it in by hand.
The process:
From a dropdown (HTML) element, call to handleSelection(choice). handleSelection then looks at the option selected and either creates an input or a second select element with options. For two of the options I would like to create an input and add an onclick to kick pikadate...All I am getting is a input field with no call to the function on click, I can type in the date in the correct format and get a result so the post portion is working.
See code as follows:
JavaScript protion:
<script src='moment.js></script> <----used for date format only
<script src='pikaday.js></script>
<script>
function handleSelection(choice)
{
if(choice=='ordnum' || choice=='po' || choice=='serial' || choice=='asset') <----Works as intended
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
a.appendChild(input);
}
if(choice=='varified')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='y'>Validated</option><option value='n'>Not Validated</option>";
a.appendChild(valid);
}
if(choice=='loc')<----Works as intended
{
var a=document.getElementById('valid');
var valid=document.createElement('select');
valid.name='value';
valid.innerHTML="<option value='loc0'>loc0</option><option value='loc1'>loc1</option><option value='loc2'>loc2</options><option value='loc3'>loc3</option><option value='loc4'>loc4</option><option value=';loc5'>loc5</option>";
a.appendChild(valid);
}
if(choice=='drcv' || choice=='disrv') <---Isn't working as intended!
{
var a=document.getElementById('input');
var input=document.createElement('input');
input.type='text';
input.name='value';
input.id='pkr';
input.onclick='getDate()'; <----Tried with quotes and with out, will not call out to getDate()
a.appendChild(input);
}
}
<script>
function getDate()
{
var picker = new Pikaday({field:docuemnt.getElementById('pkr'),format:'YYYYMMDD'});
</script>
}
}
</script>
HTML portion:
<body>
<form class='container' name='report' action='somepage' method='post'>
<select id='select' onChange='handleSelection(value)' name='opt'>
<option value="ordnum">Order Number</option>
<option value="po">Po Number</option>
<option value="drecv">Date Received</option>
<option value="disrv">Date In Service</option>
<option value='serial'>Serial Number</option>
<option value='asset'>Asset Tag</option>
<option value='loc'>Location</option>
<option value='varified'>Verified</option>
<option value='*' selected>All Systems</option>
</select>
<input type="submit" name="submit" value="Fetch..">
</p>
<p id='input'>
</p>
<p id='valid'>
</p>
</form>
</body>
</div>
</html>
Replace
input.onclick='getDate()';
with
input.addEventListener('click', getDate, false);
you could also use input.onclick = getDate;, but addEventListener is the preferred way of adding event listeners.
And make sure the getDate function is in scope, that means that it's either inside the same script tag as the event listener, or a script tag above the one containing the event listener.
Hoisting doesn't help across script tags.
So playing around a bit, seems style was the issue. I had a div style set in my original CSS and it seems that the div in the pikaday.css was going off of that position causing the stretched effect. I adjusted the percentage of the div in pickaday.css to 55% and now have the full effect that was wanted.

Change selectbox to textfield and vice versa

I have a table in which there are three columns (A: datefield, B: selectbox, C: checkbox).
Now when someone checks on the checkbox, the column(B) having selectbox should convert to a column textfield. That means I want to convert selectbox to textfield and vice versa on change of the checkbox event. Is that possible?? If so how? (using js, no jquery please)
Reply is greatly appreciated.
Try as below,
<html>
<body>
<script type="text/javascript">
function toggleSelect() {
var isChecked = document.getElementById("check").checked;
if(isChecked) {
document.getElementById("toggle").innerHTML = "<input type='text' id='txt'></input>";
} else {
document.getElementById("toggle").innerHTML = "<select> <option value='1'>1</option> </select> ";
}
//alert(isChecked);
}
</script>
<table>
<tr>
<td> DateField </td>
<td id="toggle">
<select> <option value="1">1</option> </select>
</td>
<td> <input type="checkbox" id="check" onchange="javascript:toggleSelect();">change</input></td>
</tr>
</table>
</body>
</html>
Place two div tags where
one contains the component which you want to change (for this div give a class name "comp1 visible" and in the CSS set the style has display: block )
and another one div with the component you would want to replace ( for this div give a class name "comp2 hidden" and in the CSS set the style has display:none )
use the onclick event to call the function ...
function insertitem(rvalue){
if(rvalue.value==1){
var temp=document.getElementsByClassName("comp1");
temp[0].classList.remove("hidden");
temp[0].classList.add("visible");
}
else if(rvalue.value==2){
var temp=document.getElementsByClassName("comp2");
temp[0].classList.remove("hidden");
temp[0].classList.add("visible");
}
}
this should work.. PS: since you dint post any of ur code .. i couldnt explain much

Categories