Issue with the way data is displayed in confirm box - javascript

I have a form with multiple text boxes where I can type a material name and in another box I can type the material price.
When the user clicks submit I am displaying a confirm box with the entered material(s) and price(s). In this confirm box I want to show all entered matr_name with the associated matr_price (one per line). I just can not seem to make it display as I want, the below script outputs like this:
matr_name
matr_price
matr_name
matr_price
etc.
I want it to display like this:
matr_name: matr_price
matr_name: matr_price
matr_name: matr_price
etc.
All I got is the below script which gives me the correct output, just not displayed as I want it in the confirm box.
Script
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val()}).get().join('\n');
var confirm_form = confirm("Rep:\n" + matr_name);
console.log("Mart.: " + matr_name);
if(confirm_form == true)
{
return true;
}
else {
return false;
}
}
Part of the form:
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<input type="submit" name="submit_name" id="submit_id" class="submit" value="Done" onclick="javascript:return show_confirm();"/>

You can put different strings after the value depending on the name:
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val() + ($(this).attr('name') == 'matr_name[]' ? ': ' : '\n');
}).get().join('');
or:
var matr_name = $("input[name*='matr']").map(function() {
if ($(this).attr('name') == 'matr_name[]') {
return $(this).val() + ': ';
} else {
return $(this).val() + '\n';
}
}).get().join('');

Related

On Press Tab append input field

I working in an attendance register where I have a table with a date on which the user should enter the work duration like 1 or 1.5 or 2 which means 1 as a full day, 1.5 as one and half day and so on.
The Problem which I am facing is I have javascript where I have given on click to append the input field. but what I am looking for is whenever the user press tab it should go to the next input field.
Please take a look at the screenshot of the layout.
Here is javascript code :
$(function () {
$("td").on("click", function() {
var $this = $(this);
var tdID = $(this).attr("id");
var $input = $("<input>", {
value: $this.text(),
type: "text",
style: "width:40px",
id:"myInput",
blur: function() {
$this.text(this.value);
saveEidatedData(tdID);
},
keyup: function(e) {
if ((e.which === 13)&&(e.which === 9)) $input.blur();
},
}).appendTo( $this.empty() ).focus();
});
});
Any help will be highly appreciated. Thanks in advance.
I think something like this? You may also use arrow keys, to remove the arrow key functionality just delete it from the 'arr' array
var sftDown = false;
$(document).on({
keydown: function(e) {
//37 - 40 = arrows keys
//13 = enter
//9 = tab ( should auto move with tab)
var arr = [9,13,37,38,39,40];
if ( e.which == 16 ) sftDown = true;
if ( $.inArray(e.which, arr) !== -1 ) {
var main = $(this).closest('#table');
var rows = main.find('tr');
var cells = main.find('input[type="text"]');
var downAmount = cells.length/rows.length;
var move = 1;
switch (e.which) {
case 9:
move = 0;
break;
case 40:
case 13:
move = downAmount;
break;
case 38:
move = downAmount * -1;
break;
case 37:
move *= -1;
break;
}
if ( sftDown ) move *= -1;
var i = cells.index(this) + move;
if ( i >= cells.length ) i %= cells.length;
if ( i < 0 ) i = cells.length + i;
cells[i].focus();
}
},
keyup: function(e) {
if ( e.which == 16 ) sftDown = false;
}
},'#table input[type="text"]');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id="table">
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
</tbody>
</table>
instead of doing it in JavaScript, you should populate the day with the text box having attribute of tabindex starting from some number and increment it to +1 for each row it should be start from where the last row tabindex ended.
if you doing it in JavaScript it would take extra time to make it work also you need to place extra checks.
like below example click on the first field and press tab it will move to the next input field.
To do as per my suggestion, it helps you to update time easily for specific day, as well as to populate the day's from array / object data type.
<tr>
<td><input type="text" tabindex="1" value="1" /></td>
<td><input type="text" tabindex="2" value="2" /></td>
<td><input type="text" tabindex="3" value="3" /></td>
</tr>
<tr>
<td><input type="text" tabindex="4" value="4" /></td>
<td><input type="text" tabindex="5" value="5" /></td>
<td><input type="text" tabindex="6" value="6" /></td>
</tr>

enter key to follow the tabindex (in scenario where enter key is changed to behave as tab)

I have a 3x3 table within a form. By default tab key moves the cursor in horizontal directions on these input fields. When a tabindex is given ( Like in the example below) the tab key moves cursor columns wise instead of row wise, as I needed.
With various sources from SO answers, I came up with the Jquery to use enter key as tab. But, could not figure out how to follow the tabindex as achieved above , i.e by pressing enter key instead of cursor moving row-wise, i want it to move in column wise. Below is what I have so far, any help is appreciated.
Demo of how it currently works. http://jsfiddle.net/unCu5/125/
Source of below code: jquery how to catch enter key and change event to tab
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
})
#Dekel solution work for the html scenario he displayed, but I have a different type of HTML on view source. How do I fix this
Instead of just focus the next input element, you can find the next element (based on the tabindex) and focus on him:
$('input[tabindex^="2"]');
Check this example:
$(document).ready(function () { // Will only run once the page Document Object Model (DOM) is ready for JavaScript code
// Create a jQuery object containing the html element 'input'
// Create a .not() method to exclude buttons for keypress event
$(":input:not(:disabled)").not($(":button")).keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// get the attribute type and if the type is not submit
itype = $(this).prop('type');
if (itype !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="4" placeholder="4" /></td>
<td><input tabindex="7" placeholder="7" /></td>
</tr><tr>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="5" placeholder="5" /></td>
<td><input tabindex="8" placeholder="8" /></td>
</tr><tr>
<td><input tabindex="3" placeholder="3" /></td>
<td><input tabindex="6" placeholder="6" /></td>
<td><input tabindex="9" placeholder="9" /></td>
</tr>
</table>
The code doesn't support go back from the last input to the first. You will need to write it explicitly.
Updated version - fix wrong tabindex values
The original question didn't mention that tabindex could repeat or don't have sequential values.
This code will "fix" the values of tabindex based on the order in the code AND the values of the tabindex. It will support both repeated tabindex values and non sequential values (1, 2, 3, 6, 7):
function fixTabIndex() {
// Find all inputs. Their order will be the same order they appear inside your html.
inputs = $('input');
// Save the original HTML order of the inputs (we need this to compare their order in the HTML in case or equal two tabindex
inputs_original = $('input');
// Sort the inputs by their tabindex values and their position in the DOM
// More info on Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
inputs.sort(function(a, b) {
if ($(a).attr('tabindex') == $(b).attr('tabindex')) {
// If tabindex is equal - sort by the position in the DOM
if (inputs_original.index(a) < inputs_original.index(b)) {
return -1;
} else {
return 1;
}
} else if ($(a).attr('tabindex') < $(b).attr('tabindex')) {
return -1;
} else {
return 1;
}
});
// Set the new value of the tabindex based on the position in the sorted array
inputs.each(function(i, el) {
$(el).attr('tabindex', i+1);
});
}
$(document).ready(function () {
// First we need to fix the tabindex values:
fixTabIndex();
$("input").keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// Make sure this is not a submit input
if ($(this).prop('type') !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>

OCR Web Validation using Javascript

I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...

how to update several span elements based on user input HTML

I have a huge form with at least 200 input fields- text/radio/checkboxes.
I have divided this into several sections to structure it well and there is an update button for each section which takes the user input and persists it to the db. This is done by Ajax so I don't have to reload the page.
How can I easily update the <span>s corresponding to the input fields with whatever the user inputs without reloading the page? DO I have to do a $("#spanid").html($("#input1").val()) on each <span> item or is there an easy way to do this?
Here's the code for a fraction of the form.
HTML
<form id="history" name="history" action="" method="post">
<table class="normal">
<tr><th colspan="8">HISTORY</th>
</tr>
<tr><td style="width:200px"><b>Chief Complaint Location</b></td>
<td style="width:450px"><b>Comment</b></td>
<td><b> Previous</b> </td>
</tr>
<tr><td>Head</td>
<td ><input type="text" maxlength="100" name="headH" id="headH" ></td>
<td class="data2"><span id="headSpan"><%=msmtCommentHead%></span></td>
</tr>
<tr><td>Neck</td>
<td><input type="text" maxlength="100" name="neckH" id="neckH" ></td>
<td class="data2"><span id="neckSpan"><%=msmtCommentNeck%></span></td>
</tr>
<tr><td>Upper Extremeties</td>
<td><input type="text" maxlength="100" name="upperExtremetiesH" id="upperExtremetiesH"></td>
<td class="data2"><span id="ueSpan"><%=msmtCommentUpperExtremeties%></span></td>
</tr>
<tr><td>Thoracic Spine</td>
<td><input type="text" maxlength="100" name="thoracicSpineH" id="thoracicSpineH"></td>
<td class="data2"><span id="tsSpan"><%=msmtCommentThoracicSpine%></span></td>
</tr>
<tr><td><input type="button" id="submitHistory" value="Update"/></td></tr>
</table>
</form>
Javascript:
$(function(){
$("#submitHistory").click(function() {
var query = $("#history").serialize();
$.ajax( {
type: "POST",
url: "/oscar/cmcc/History.do",
dataType: "json",
data: query
});
document.getElementById('history_cmcc').reset();
var date = new String("<%=date%>");
$("#headSpan").innerHTML = $("#headH").val()+ "," + date;
$("#neckSpan").innerHTML = $("#neckH").val() + ","+ date;
$("#tsSpan").innerHTML = $("#thoracicSpineH").val() + ","+ date;
$("#lsSpan").innerHTML = $("#lumbarSpineH").val() + ","+ date;
$("#leSpan").innerHTML = $("#lowerExtremetiesH").val() + ","+ date;
$("#chSpan").innerHTML = $("#chestHeartH").val() + ","+ date;
}
Thanks!
In general you can do this:
$('input[type=text]').each(function() {
$(this).closest('tr').find('span').html($(this).val());
});
$('input:checked').each(function() {
$(this).closest('tr').find('span').html($(this).val());
});
Update per OP comment:
In your example if you wanted to put the label that is to the left of a radio button inside the span you could do this. This depends on your specific requirements.
$('input[type=radio]:checked').each(function() {
$(this).closest('tr').find('span').html($(this).closest('tr').find('td:eq(0)').text());
});
$(':input').each(function() {
$(this).closest('tr').find('span').html(this.value);
});
:input applied for all inputs. Also can use input.

Jquery: sum input text fields

I have a table including input text fields with the basic structure below. I am having trouble building a function to iterate all rows in the table and sum all the values of input fields beginning with BFObel where the value of the field beginning with BFOkto are the same. So for the basic example below the sum for value 1111 would be 2000 and the sum for value 1112 would be 3000. Each sum would then be written to an inputfield with the id field1111, field1112 etc...
<table>
<tr id="BFOrow1">
<td><input type="text" id="BFOtxt1" value="text"/></td>
<td><input type="text" id="BFOkto1" value="1111" /></td>
<td><input type="text" id="BFObel1" value="1000" /></td>
</tr>
<tr id="BFOrow2">
<td><input type="text" id="BFOtxt2" value="text"/></td>
<td><input type="text" id="BFOkto2" value="1111" /></td>
<td><input type="text" id="BFObel2" value="1000" /></td>
</tr>
<tr id="BFOrow3">
<td><input type="text" id="BFOtxt3" value="text"/></td>
<td><input type="text" id="BFOkto3" value="1112" /></td>
<td><input type="text" id="BFObel3" value="1000" /></td>
</tr>
<tr id="BFOrow4">
<td><input type="text" id="BFOtxt4" value="text"/></td>
<td><input type="text" id="BFOkto4" value="1112" /></td>
<td><input type="text" id="BFObel4" value="1000" /></td>
</tr>
<tr id="BFOrow5">
<td><input type="text" id="BFOtxt5" value="text"/></td>
<td><input type="text" id="BFOkto5" value="1112" /></td>
<td><input type="text" id="BFObel5" value="1000" /></td>
</tr>
</table>
You'll want to use an object literal to track your results and an "attribute starts with" selector to find the text inputs:
var accumulator = { };
$('table input[id^=BFOkto]').each(function() {
var sum_id = this.id.replace(/^BFOkto/, 'BFObel');
if(!accumulator[this.value])
accumulator[this.value] = 0;
accumulator[this.value] += parseInt($('#' + sum_id).val(), 10);
});
// accumulator now has your results.
Don't forget the second argument to parseInt() so that you don't get tripped up by values with leading zeros (which look like octal without a specified radix).
For example: http://jsfiddle.net/ambiguous/QAqsQ/ (you'll need to run this in a browser with an open JavaScript console to see the resulting accumulator).
var sum1111 = 0;
$('input[value="1111"]').each(function() {
var ordinal = $(this).attr('id').replace('BFOkto', '');
sum1111 += parseInt($('#BFObel' + ordinal).val());
});
At the end, sum1111 should equal 2000.
For reuse, wrap the logic in a function:
function getSum(BFOkto) {
var sum = 0;
var ordinal = null;
$('input[value="' + BFOkto + '"]').each(function() {
ordinal = $(this).attr('id').replace('BFOkto', '');
sum += parseInt($('#BFObel' + ordinal).val());
});
return sum;
}
And then call:
getSum('1111');
getSum('1112');
A different approach: find all input fields with prefix BFOkto, for each, find the input with prefix BFObel sharing same parent and accumulate its value
ref = $("table td input[id^=BFOkto]");
var sums = new Object();
ref.each(function(){
val = parseInt($(this).closest('tr').find("td input[id^=BFObel]").val(), 10);
property = 'i'+ this.value;
sums[property] = (sums[property] || 0 ) + val;
});
alert(sums['i1111']);
alert(sums['i1112']);
sums will be an object with properties
i1111 = 2000
i1112 = 3000
Despite javascript allows it, it is better not to use pure numeric properties for objects (associative arrays), hence the i prefix
The running example is here:
http://jsfiddle.net/TbSau/1/

Categories