I am new to HTML. I have written an app, which allows user to add data and it's a local application. I have used forms int this application and I am facing a problem when form submission happens. I don't want the page to navigate/redirect and even don't want the same page to reload. Currently it's reloading the page. Please let me know what stops redirecting/reloading this app. I don't want any php code, application needs to be pure HTML and JS only.
Below is the HTML app code.
function addInfo() {
var InfoForm = document.forms["InfoForm"];
var trelem = document.createElement("tr");
for (var i = 0; i < InfoForm.length - 1; i++) {
var tdelem = document.createElement("td");
tdelem.innerHTML = InfoForm[i].value;
trelem.appendChild(tdelem);
}
document.getElementById("current_table").appendChild(trelem);
return false;
}
function done(e) {
e.preventDefault();
return false;
}
<div id="current_div">
<h2>Table Heading</h2>
<table border="1" id="current_table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</div>
<div id="input_div">
<form name="InfoForm" accept-charset="utf-8" onsubmit="done(e)">
Name :
<input type="text" name="Name" value="">
<br>
<br>Age :
<input type="number" name="Age" value="">
<br>
<br>
<input type="submit" value="Add_Info" onclick="addInfo()">
</form>
</div>
This is not the right case to use a <form>. A <form> is used when you send via GET or POST method data to the server.
Therefore just use a <button> and two <input>.
It's easier to insert a row with insertRow and insertCell.
Complete example :
var nName = document.getElementById("nName");
var nAge = document.getElementById("nAge");
var btn = document.getElementById("addData");
var tbl = document.getElementById("myData");
function addData() {
var row = tbl.insertRow(0);
var d1 = row.insertCell(0);
var d2 = row.insertCell(1);
d1.innerHTML = nName.value;
d2.innerHTML = nAge.value;
}
btn.addEventListener("click", addData);
table {
margin: 15px 0;
}
#inputData > div {
margin: 5px 0;
}
#inputData > div > span {
display: inline-block;
width: 100px;
}
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="myData"></tbody>
<!-- Insert data -->
</table>
<div id="inputData">
<div><span>Name:</span>
<input type="text" id="nName">
</div>
<div><span>Age:</span>
<input type="number" id="nAge">
</div>
<div>
<button id="addData">Add data</button>
</div>
</div>
A form submission made a GET/POST request to the server. You can't use only JS for get data from a form submission.
If you don't want use server side language for some simple applications you can make your own function without really submit your form.
Example without form
function gocalc()
{
var number = document.getElementById("number").value;
var text = document.getElementById("text").value;
if(number>0 && number <11 && text !="")
{
for(var i=0;i<number;i++)
{
document.getElementById("content").innerHTML=document.getElementById("content").innerHTML+"<p>"+text+"</p>";
}
}
else
alert("You must write some text and choose a number between 1 and 10");
}
Choose a number between 1 and 10 <input type="number" max="10" id="number"> <br>
Write some text <input type="text" id="text"><br>
<button onclick="gocalc()">Ok</button>
<div id="content"></div>
You can use onsubmit attribute and call your function. don't forget to return false for prevent the form submission.
Example with form
function myfunction(myform)
{
alert(myform.mytext.value);
return false;
}
<form onsubmit="return myfunction(this)">
<input name="mytext" type="text">
<button type="submit">Submit</button>
</form>
Related
So, I've been trying to provide a user interface in an html page whereby the user can type a number in an input field and hit apply (using addRowsForm), to see rows of various input fields being appended to another separate form (named createRecordForm) and later submit this form (including all those appended inputs and two other hidden fields) via ajax.
My problem is that I cannot find a way to group the data and post it due to the unpredictable number of input fields that would be added, depending on the user's interaction with the page. Your help is greatly appreciated.
Here are my codes:
addRowsForm
<form action="#" name="addRowsForm" id="addRowsForm" method="post">
<div class="form-group">
<input type="number" min="1" max="10" name="addRowCounter" id="addRowCounter">
</div>
<button type="submit" name="applyBtn" id="applyBtn">Apply</button>
</form>
createRecordForm
<table class="table table-bordered table-striped table-sm">
<thead class="bg-brand-4th-color">
<th>Link Type</th>
<th>Link</th>
<th>Recorded Time</th>
<th>Video Visibility</th>
</thead>
<form action="" method="POST" name="createRecordForm" id="createRecordForm">
<input type="hidden" name="ats_id" value="{{atsIdForFrag}}">
<input type="hidden" name="tot_rows" value="">
<tbody id="tBody">
</tbody>
<tfoot>
{# submit btn #}
<tr>
<td colspan="4">
<div class="form-group">
<button class="btn btn-success" type="submit" name="create_recorded_session_btn" id="create_recorded_session_btn">Create</button>
</div>
</td>
</tr>
</tfoot>
</form>
</table>
Javascript part:
<script>
$( document ).ready(
function(){
$("#addRowsForm").on("submit", function(e) {
e.preventDefault();
var rowCounter = $("input[name=addRowCounter]").val();
$("input[name=tot_rows]").val(rowCounter);
//reset any previous content
$("#tBody").html('');
for (var i = 1; i <= rowCounter; i++)
{
var newRowContent =
"<tr><td><div class='form-group p-0 m-0'><select class='form-control' name='link_type_row_"+i+"' required><option value='google_drive' selected>Google Drive</option></select></div></td><td><div class='form-group p-0 m-0'><input class='form-control' type='text' name='link_row_"+i+"' value='' required></div></td><td><div class='form-group p-0 m-0'><input type='datetime-local' name='datetime_row_"+i+"' class='form-control' required/></div></td><td><div class='form-check'><input class='form-check-input' type='radio' name='visibilityRadio_row_"+i+"' id='showOption_row_"+i+"' value='show'><label class='form-check-label' for='showOption_row_"+i+"'>Show to student</label></div><div class='form-check'><input class='form-check-input' type='radio' name='visibilityRadio_row_"+i+"' id='dontShow_row_"+i+"' value='dont_show'><label class='form-check-label' for='dontShow_row_"+i+"'>Don\'t show to student</label></div></td></tr>";
$("#tBody").append(newRowContent);
}
$("#createRecordForm").on("submit", function(e) {
e.preventDefault();
var ats_id = $("input[name=ats_id]").val();
var tot_rows = $("input[name=tot_rows]").val();
// here is my broblem, I need to change this hard-coded lines into dynamic data and process it in php
var link_type_row_1 = $("select[name=link_type_row_1]").val();
var link_row_1 = $("input[name=link_row_1]").val();
var datetime_row_1 = $("input[name=datetime_row_1]").val();
var visibilityRadio_row_1 = $("input[name=visibilityRadio_row_1]:checked").val();
var link_type_row_2 = $("select[name=link_type_row_2]").val();
var link_row_2 = $("input[name=link_row_2]").val();
var datetime_row_2 = $("input[name=datetime_row_2]").val();
var visibilityRadio_row_2 = $("input[name=visibilityRadio_row_2]:checked").val();
var url = "{{ path('ao__frg_persist_st_rec_session')|escape('js') }}";
var type = "POST";
$.ajax({
url : url,
type: type,
data : {
'ats_id': ats_id,
'tot_rows': tot_rows,
'link_type_row_1': link_type_row_1,
'link_row_1': link_row_1,
'datetime_row_1': datetime_row_1,
'visibilityRadio_row_1': visibilityRadio_row_1,
'link_type_row_2': link_type_row_2,
'link_row_2': link_row_2,
'datetime_row_2': datetime_row_2,
'visibilityRadio_row_2': visibilityRadio_row_2
},
success: function(returnedMsg) {
// do something
}
});
});
});
});
</script>
[UPDATE : Check my answer below this paragraph]
If I implement the batch approach as suggested by #Kinglish, I will end up having a big single radio while each row should have its own radio input separately from the rest.
[SOLUTION TO THE UPDATE ISSUE ABOVE]
So I used the loop index number to remain the unique name and ID for each row's radio inputs. Now the row 1 has input name/id of visibilityRadio_row_1 and 2nd row's name/id is visibilityRadio_row_2. Then I used the ^ wildcard selector and the :checked property to target the value of the checked radio in each row independent of other rows.
let obj = [];
$('.data-group').each(function() {
obj.push({
link_type: $(this).find('select[name="link_type_row"]').val(),
link: $(this).find('input[name="link_row"]').val(),
created_at: $(this).find('input[name="datetime_row"]').val(),
is_active: $(this).find('input[name^="visibilityRadio_row"]:checked').val()
})
})
I would approach this differently. Consider that you can process these in batches, rather than a finite loop. Without rewriting your script, look at how these are processed. you end up with an array of objects that appear in the order they are in your form. This does away with the messy bit of appending a number to each field. In your remote script that receieves these, you can just iterate through them and, if desired, add the number at that point.
$(document).ready(function() {
$('.submit').click(function() {
let obj = [];
$('.data-group').each(function() {
obj.push({
name: $(this).find('input[name="name"]').val(),
gender: $(this).find('select[name="gender"]').val(),
favorite_color: $(this).find('input[name="favorite_color"]').val()
})
})
console.log('obj:', obj);
})
})
// I accidentally did this in vanillaJS first, so for posterity, here is that version:
/*
window.addEventListener('DOMContentLoaded', () => {
document.querySelector('.submit').addEventListener('click', () => {
let obj = [];
document.querySelectorAll('.data-group').forEach(e => {
obj.push({
name: e.querySelector('input[name="name"]').value,
gender: e.querySelector('select[name="gender"]').value,
favorite_color: e.querySelector('input[name="favorite_color"]').value
})
})
console.log('obj:', obj);
})
})
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='data-group'>
<input name='name' value='john' />
<select name='gender'>
<option selected value='this'>this</option>
<option value='that'>that</option>
<option value='other'>other</option>
</select>
<input name='favorite_color' value='blue' />
</div>
<div class='data-group'>
<input name='name' value='mary' />
<select name='gender'>
<option value='this'>this</option>
<option value='that' selected>that</option>
<option value='other'>other</option>
</select>
<input name='favorite_color' value='green' />
</div>
<hr>
<button class='submit'>click</button>
I have a webpage with a form on it for entering patient information (all dummy data of course). I set up the form and a table to display the information that is submitted. I just can't seem to figure out why the data is not getting stored in the array when the user clicks the "Add Patient" button. I have attempted to submit data multiple times and then I used "console.log(patientArray)" to check the array, and it says that the information I attempted to store is undefined.
This is my web page:
#using OnboardingProject.App_Code
#using OnboardingProject.Controllers
#{
ViewBag.Title = "Patients";
}
<div class="title">
<div>
<h1 style="float: left">#ViewBag.Title</h1>
</div>
<div class="rmm" style="float: right; display: inline-block">
<ul>
<li><button id="NewPatient">New Patient</button></li>
</ul>
</div>
</div>
<div id="modal_content">
<div id="modal_window" title="Complete the form below to add a new patient:">
<div style="text-align: right;"><a id="modal_close" href="#">close <b>X</b></a></div>
<form id="add_patient" method="POST" action="#" accept-charset="UTF-8">
<p><label>First Name<strong>*</strong><br>
<input type="text" autofocus required size="48" id="fname" value=""></label></p>
<p><label>Last Name<strong>*</strong><br>
<input type="text" autofocus required size="48" id="lname" value=""></label></p>
<p><label>Birthdate (mm/dd/yyyy)<strong>*</strong><br>
<input type="text" autofocus required size="48" id="bday" value=""></label></p>
<p><label>Site Name<strong>*</strong><br>
<input type="text" autofocus required size="48" id="location" value=""></label></p>
<p><label>SSN<strong>*</strong><br>
<input type="text" autofocus required size="48" id="pat_ssn" value=""></label></p>
<p><input type="button" value="Add Patient" onclick="addPatient()"></p>
</form>
</div>
</div>
<div class="content">
<div id="patient_table">
<table id="patients">
<tr>
<th id="p_name">Patient Name</th>
<th id="p_site">Site</th>
<th id="dob">Date of Birth</th>
<th id="ssn">SSN</th>
<th id="edits"></th>
</tr>
</table>
</div>
</div>
<script src="#Url.Content("~/Scripts/PatientInfo.js")" type="text/javascript></script>
This is my javascript file:
//Display the modal when New Patient button is clicked
$("#NewPatient").click(function () {
$("#modal_window").show();
});
//Hide the modal when close is clicked
$("#modal_close").click(function () {
$("#modal_window").hide();
});
//Create an array to store Patient Information
var patientArray = [];
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var bDate = document.getElementById("bday").value;
var sName = document.getElementById("location").value;
var SSN = document.getElementById("pat_ssn").value;
function addPatient( fName, lName, bDate, sName, SSN ) {
patientArray.push(fName, lName, bDate, sName, SSN);
$("#modal_window").hide();
}
//Create a table from the array
var table = document.getElementById("patients");
var tbody = document.createElement("tbody");
table.appendChild(tbody);
patientArray.forEach(function (items) {
var row = document.createElement("tr");
items.forEach(function (item) {
var cell = document.createElement("td");
cell.textContent = item;
row.appendChild(cell);
});
tbody.appendChild(row);
});
The html button calls the function addPatient(). Note that calling the addPatient function has got nothing to do with executing the previous five lines (outside the function) , which is where the values are getting picked up into the variables. That's why, when the function is called, nothing happens. Also, the function expects 5 parameters in its definition. Then you must call the function with 5 parameters. Or put the act of picking up the values, inside the function, and calling with no parameters.
In other words, here are the two ways :
Option 1 :
Move this code inside the function addPatient.
Remove the parameters definition for the function and make it a function with no parameters.
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var bDate = document.getElementById("bday").value;
var sName = document.getElementById("location").value;
var SSN = document.getElementById("pat_ssn").value;
Option 2 :
Keep the addPatient function as it is. But, make another function, say, Fetch_And_Add_Patient() that has the following code :
function Fetch_Add_Patient() {
var fName = document.getElementById("fname").value;
var lName = document.getElementById("lname").value;
var bDate = document.getElementById("bday").value;
var sName = document.getElementById("location").value;
var SSN = document.getElementById("pat_ssn").value;
addPatient(fName, lName, bDate, sName, SSN);
}
And then in the HTML button, call the above function, without any parameters, instead of calling addPatient without any parameters.
<p><input type="button" value="Add Patient" onclick="addPatient()"></p>
Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});
In my form i am having a button to Add More EmailId where i have to give ten textbox one by one can anybody please tell about appropriate javascript..
Try something like this, its something I ripped from another project.
Wrap your form around the div and when you submit your email addresses will be in an array as the name of the input box is email[].
<div class="cntdelegate">
<div id="readroot" style="display:none;">
<table cellspacing="0">
<tr>
<td><label for="theiremail"><span>Email</span></label><input type="text" name="email[]" id="theiremail" value="Email" class="emailbox" maxlength="100" onFocus="if(this.value=='Email'){this.select()};" onClick="if(this.value=='Email'){this.select()};" /></td>
</tr>
</table>
Remove
<div class="clear"></div>
</div>
<span id="writeroot"></span>
<button style="float:right!important;" type="submit" class="withArrow" name="submit" id="submit" value="submit" alt="Send" title="Send">Book now</button>
<div class="addDelegate" style="float:left!important;">
Add another delegate
</div>
<div class="clear"></div>
</form>
</div>
<script>
var counter = 0;
function init() {
moreFields();
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = function ()
{
if (self.init)
init();
}
</script>
I'm unsure what html you have but I've created a simple jQuery example here http://jsfiddle.net/TsmTg/2/
Here's the code
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
emailAddress.after(emailAddress.clone());
});
});
This will copy your email input and just add a clone after the original. All the email address inputs will have the same name so you will have to handle parsing the data on the server side. You could modify it so each email address input has a different name by using a counter to append a number to the end of each input, like so:
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
var newEmail = emailAddress.clone();
newEmail.attr("name", newEmail.attr("name") + ($("[name^=emailAddress]").length + 1));
emailAddress.after(newEmail);
});
});
Are you using Tables to put the textboxes? In that case, cloning rows from the table easily adds a new row with the contents in a table.
Add your HTML code. This will help finding the solution easier.
The code below fetches a list of files that have been selected for upload.
It basically appends input elements inside a div above a form element:
<div id = "files_list"> </div>
How do I store all the attributes names in an array - fileNamesArray - on clicking the submit button.?
My attempt I'm yet to check if this works:
// beginning of attempt
// my approach:
// alert the user if no file is selected for upload and submit is clicked else
// I'd have to iterate through the input elements and contained in the div id="files_list", fetch all the file names and push all the values into an array $filesArray.
//rough attempt
$("Submit").click(function () {
$filesArray
$(div#files_list).getElementById('input').each(function($filesArray) {
filesArray.push($this.attr("value"))
});
while( $filesArray.size != 0) {
document.writeln("<p>" + $filesArray.pop() + "</p>");
}
}
//end of attempt: I print out the names just to verify
Code Below:
$(document).ready(function(){
var fileMax = 6;
$('#asdf').after('<div id="files_list" style="border:1px solid #666;padding:5px;background:#fff;" class="normal-gray">Files (maximum '+fileMax+'):</div>');
$("input.upload").change(function(){
doIt(this, fileMax);
});
});
function doIt(obj, fm) {
if($('input.upload').size() > fm) {alert('Max files is '+fm); obj.value='';return true;}
$(obj).hide();
$(obj).parent().prepend('<input type="file" class="upload" name="fileX[]" />').find("input").change(function() {doIt(this, fm)});
var v = obj.value;
if(v != '') {
$("div#files_list").append('<div>'+v+'<input type="button" class="remove" value="Delete" style="margin:5px;" class="text-field"/></div>')
.find("input").click(function(){
$(this).parent().remove();
$(obj).remove();
return true;
});
}
};
Code for the HTML form:
<td><form action="test.php" method="post" enctype="multipart/form-data" name="asdf" id="asdf">
<div id="mUpload">
<table border="0" cellspacing="0" cellpadding="8">
<tr>
<td><input type="file" id="element_input" class="upload" name="fileX[]" /></td>
</tr>
<tr>
<td><label>
<textarea name="textarea" cols="65" rows="4" class="text-field" id="textarea">Add a description</textarea>
</label></td>
</tr>
<tr>
<td><input name="Submit" type="button" class="text-field" id="send" value="Submit" /></td>
</tr>
</table><br />
</div>
</form>
<p class="normal"></td>
var my_array = new Array();
$('#asdf').bind('submit', function() {
$.each(this.elements, function() {
if ( this.type == 'file' ) {
$('#file_list').append($(this).clone());
my_array.push(this.value);
}
});
for ( var i=0; i < my_array.length; i++ )
alert(my_array[i]);
});
Here you go!
EDIT Updated due to OP's comment.