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
Related
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.
I am facing an issue with the existing code which is using html and JS. The page has a html table which has a radio button and 4 other fields. The table is created dynamically when we set values through controller. Also I can add new rows in the table which is done completly through JS. Now the problem is I inserted 2 rows from controller and added a new row through a button click. So I have 3 radio button now. If I select one radio button among the controller inserted row it selects only one, which is fine, If I select the 3rd one I can see two selected radio button, which is not correct. In any case it should select only one. when I take view source I am not seeing the entry for the javascript added new row, so I hope the problem is because of the Id generated ? please let me know how can I solve this issue?
Java controller
List <MyQuestion> fetchedQuestions = AppImpl.getMyQuestions(id);
for (int index=0; index< fetchedQuestions.size() ; index++){
MyQuestion questionsToAdd= fetchedQuestions.get(index);
questionList.add(questionsToAdd);
}
myqstntemplate.setMyQuestions(questionList);
templatebean.setQuestionTemplate(myqstntemplate);
}
JScode
function addRow(){
isDirty=true;
if(document.getElementById('value').value != 'value'){
rowNumber = document.getElementById('questionsSize').value;
document.getElementById('value').value='value';//other option is novalue
}
var questionId=document.getElementById('questionsSize').value;
questionId=parseInt(questionId)+1;
document.getElementById('questionsSize').value = questionId;
var newRow = $('<tr/>').attr('id', 'row' + rowNumber);
//Add some HTML to the row
newRow.html('<td><input type="hidden" id="newQuestion'+rowNumber+'" value="'+questionId+'"/><input id="question" name="question" type="radio" style="width:20px;" value="" onclick="setSelectedQuestion(\''+rowNumber+'\',\'new\')"/></td><td class="newRow" align="center" style="vertical-align: middle;">'+questionId+'<input type="hidden" value="newQuestion"/></td> <td colspan="2"><input style="width: 397px;" id="myQstnTemplate.questions['+rowNumber+'].question" name="myQstnTemplate.questions['+rowNumber+'].question" type="text" value="" maxlength="256" onclick="enableDirty()" style="text-align:left;"/><div id="pencil" title="Edit helptext" class="pencil-img fltRight" style="border: 0pt;padding-right: 15px; " onclick="displayHelpText('+rowNumber+',\'new\');return false;"></div><input id="myQstnTemplate.questions['+rowNumber+'].questionId" name="myQstnTemplate.questions['+rowNumber+'].questionId" type="hidden" value="-1" /><input style="width: 350px;" id="myQstnTemplate.questions['+rowNumber+'].helptext" name="myQstnTemplate.questions['+rowNumber+'].helptext" type="hidden" value="" onclick="enableDirty()" style="text-align:left;"/></td><td><select style="width:100px;" id="myQstnTemplate.questions['+rowNumber+'].schemeId" name="myQstnTemplate.questions['+rowNumber+'].schemeId"><option value="-1">Select</option><c:forEach var="answer" items="${myqstionTemplateBean.answerTypes}"><option title="${answer.questions}" value="${answer.displaySchemeId}">${answer.answerTypeName}</option></c:forEach></select></td> <td><div><input type="hidden" id="question'+rowNumber+'" name="question'+rowNumber+'" value="'+rowNumber+'"/><select id="myQstnTemplate.questions['+rowNumber+'].ansId" name="myQstnTemplate.questions['+rowNumber+'].ansId" style="width:100%"><option value="-1">Select</option><c:forEach var="ansId" items="${myqstionTemplateBean.ansIds}"><option value="${ansId}" <c:if test="${ansId eq question.ansId}">selected</c:if>>${ansId}</option></c:forEach></select></div></td>');
//Append the new row to the body of the #myTable table
$('#qstionTable tbody').append(newRow);
//Iterate row number
rowNumber++;
}
If you want all the radio button working together you should have the same name for each in your template.
Check that.
Edit:
If several radio button can be selected it is because their name are differents. Your radio' name must not depend of the rowNumber. Set a hard name, not a variable name.
Check that.
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 :
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().
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