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>
Related
In my laravel application I have set of checkboxes inside a form.
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test List :</strong>
<br>
#foreach($ttype as $value)
<script type="text/javascript">
jQuery(function () {
var boxId='<?php echo''.$value->id.''; ?>';
var boxPrice='<?php echo''.$value->test_desc.''; ?>';
var sum=0;
jQuery("#cbox"+boxId).click(function () {
if (jQuery(this).is(":checked")) {
sum = sum + parseInt(boxPrice);
jQuery('#msg').val(sum);
} else {
jQuery("#text").hide();
}
});
});
</script>
<label>{{ Form::checkbox('samp_list[]', $value->test_name, false, array('class' => 'name','sumT'=>''.$value->test_desc.'','id'=>'cbox'.$value->id.'')) }}
{{ $value->test_name }}</label>
<br/>
#endforeach
</div>
</div>
Each checkbox has its own value called charge, Eg: for checkbox 1 the charge is 450, checkbox 2, it's 1000.... for the 10th check box charge is 2300...
Now when every time when a user selects a checkbox I'm trying to display the sum of those selected checkboxes in a text field.
{!! Form::text('samp_charges', null, array('placeholder' => 'Registration Charges','class' => 'form-control','id'=>'msg')) !!}
But My issue is, whenever I select more than 1 option it does not display the sum. Instead, it gives me the value of the last selected check box.
How can I display the sum of all selected checkboxes in that text field and once I unselect a checkbox, substract that value from the sum
Use class and data attribute - in plain HTML/PHP it would look like
<input class="cbox" type="checkbox" data-price="<?= $boxprice ?>" />
Delegate:
$(function() {
$(".cbox").on("change", function() {
const vals = $(".cbox:checked")
.map(function() {
return +this.dataset.price
})
.get();
// test we have an array of values
const sum = vals.length>0 ? vals.reduce((a, b) => a + b) : 0; // if no, zero sum
$('#msg').val(sum)
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
100: <input class="cbox" type="checkbox" data-price="100" /><br/> 200: <input class="cbox" type="checkbox" data-price="200" /><br/> 300: <input class="cbox" type="checkbox" data-price="300" /><br/>
<input type="text" readonly id="msg" />
If you do not like to use class class, then use $("[id^=cbox]") instead of $(".cbox")
I had created Ul which add the student input field with value and user can remove the field as well,Initially I am comparing student field value with each input field which are created to avoid duplication but it works only for first input field value not for others I used loop as well but its not working and not able to remove one input field at a time.
Here is my fiddle code
$('#addBtn').click(function () {
var studentArray = $(".students").text();
var i=" " ;
console.log(studentArray);
var studentSplitResult = studentArray.split('Remove');
console.log(studentSplitResult);
for (var i = 0; i < studentSplitResult.length; i++) {
if ($("#selectStd").val() !== $(".students").val()) {
$(".stdList").show();
var input_value = $('#selectStd').val();
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
console.log($(".students").val());
// console.log(studentSplitResult[i]);
};
return false;
}
});
//prevent default action
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
You can simplify your code like below.
Just check any text input has the new value before adding using filter. It will also handle case insensitivity (remove if required).
Also while removing consider the removing the text input only.
Added e.preventDefault() to restrict the form posting. change or remove it as per requirement.
$('#addBtn').click(function(e) {
e.preventDefault();
var input_value = $("#selectStd").val();
var isValid = $('input.students').filter(function() {
return this.value.toLowerCase() == input_value.toLowerCase();
}).length <= 0;
if (isValid) {
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
} else {
alert('Duplicate');
}
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).prev('.students').remove();
$(this).remove();
});
<body>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
</div>
</body>
I have encountered two issues: input validation itself (your question) and the removal of the element when you click on the anchor element.
For input validation, I have rewritten it a bit. What I did is
1. Obtain new student value
2. Check if not empty by if(newStudent). If it's empty, nothing happens
3. obtain other inputs
4. match the new input against the values inside other inputs
4a. if match, don't add it.
4b. if no match, add it
For removing the element, You need to revise your HTML. It's not so correct. I have wrapped it around with a <section> element to have a save removal and corrected the HTML use.
A side note, you may also reconsider this
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
If your HTML page has multiple anchor (<a>) elements, this function is used too on another anchor elements. If you click on these, it will remove these from the page upon click. If you don't want it, please revise the above function.
$('#addBtn').click(function(e) {
// obtain new student value
var newStudent = $('#selectStd').val();
// check if it is not empty
if (newStudent) {
// obtain other names and check if there is no match
var studentArray = $(".students");
var hasMatch = false;
studentArray.each(function(i, el) {
if (el.value === newStudent) {
hasMatch = true;
return; // stopping loop
}
});
// if there is no match, add student
if (!hasMatch) {
$('ul.stdList').append('<section><input class="students" value="' + newStudent + '" />Remove</section>');
}
}
return false;
});
//prevent default action
$(document).on('click', 'a', function(e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br>
<br>
</ul>
</form>
</div>
</div>
When adding you try this:
$('ul').append('<input class="students" value="' + input_value + '">Remove</input>');
Unfortunately this will not result in what you expect. The anchor will be adding by your browser next to the input not nested. Like this:
<input class="students" value="thevalue" />
<a href class="deleteStd">Remove</a>
So if you do this afterwards for removing $(this).parent().remove(); you will remove the entire container.
What you need to do is this:
$('ul').append('<div><input class="students" value="' + input_value + '" />Remove</div>');
This will work. I have updated your fiddle: https://jsfiddle.net/Lojdfyhn/1/
So based on your requirements, try this below code:
Student names can't be duplicate
And on removing, all names shouldn't removed.
While adding, code checks if the student name exists. If yes, it throws an error/alert.
$('#addBtn').click(function() {
var valueToCheck = $("#selectStd").val();
var flag = true;
$(".students").each(function() {
if ($(this).val() === valueToCheck) {
flag = false;
}
});
if (flag) {
$('ul').append('<span class="addedStudent"><input class="students" value="' + valueToCheck + '" />Remove</span>');
} else {
alert(valueToCheck + " already exists.");
}
return false;
});
//prevent default action
$(document).on('click', 'a.deleteStd', function(e) {
e.preventDefault();
$(this).parents(".addedStudent:first").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style=" width:422px;border: 1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType">
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td><input class="form-control" id="selectStd" placeholder="Please select students"></td>
<td><button id="addBtn" class="btn btn-default" style="margin-left: 17px;">Add</button></td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label><br>
<br>
</ul>
<table>
</table>
</form>
</div>
</div>
You are trying to delete the parent element of anchor tag.
Just update your code like this
$('ul').append('<div><input class="students" value="' + input_value + '">Remove</input></div>');
then clicking on anchor will delete the parent of anchor element.
Hello first of all you need to get a good understanding of the DOM traversing, which can really help you to organise the students that you are adding to the list, and removing.
Here a simple solution can be implemented as follows.
First encapsulate all the students in a div tag with 'students' class name, and in that div, place the student text field with 'stdname' class and the anchor tag to help in removing the student details.
Now when traverse through all the students with 'stdname' class and check if there is a duplicate value.
Here is the code please check out.
and check on jsfiddle too.http://jsfiddle.net/naveen_namani/842bf5ke/1/
$('#addBtn').click(function () {
var student_list=document.querySelectorAll(".students .stdname");
var selectStd=document.getElementById("selectStd");
var duplicate=false;
for(var i=0;i<student_list.length;i++) {
if(student_list[i].value==selectStd.value) duplicate=true;
}
if(duplicate==false) {
$('ul').append('<div class="students"><input value="'+selectStd.value+'" class="stdname"/>Remove');
}
return false;
});
$(document).on('click', 'a', function (e) {
e.preventDefault();
$(this).parent().remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-body" style="width:422px;border:1px solid #00A4CC;">
<div id="errorLabel"></div>
<div id="parentType" >
<form id="parentForm" name="parentForm">
<table style="margin-left: 8px;">
<tr>
<th>Select Student</th>
<td>
<input class="form-control" id="selectStd" placeholder="Please select students">
</td>
<td>
<button id="addBtn" class="btn btn-default" style="margin-left: 17px;" >Add</button>
</td>
</tr>
</table>
<ul class="stdList">
<label>Selected Students:</label>
<br><br>
</ul>
<table ></table>
</form>
</div>
</div>
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>
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>
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.