I want to add start time and end time dynamically using JavaScript:
Below is the code:
HTML:
<table id="timeTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" placeholder="Enter Start Time" value="" id="vTime" class="vTime" />
</td>
<td>
<input type="text" placeholder="Enter End Time" value="" id="vTime" class="vTime" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
JS:
$('#timeTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
});
$('#add-more').click(function () {
var vTime = $(".vTime:last-child").last().val();
$('#myTable').append('<tr><td><input type="text" placeholder="Enter Start Time" class="vTime" /></td><td><input type="text" placeholder="Enter End Time" value="" id="vTime" class="vTime" /></td><td><input type="button" value="Delete" /></td></tr>');
});
If I enter start time and end time first time then end time should not be less that start time, when I enter second row for start and end time then it should not be less than previous time and so on....
Can anyone please help?
Here is jsFiddle: https://jsfiddle.net/pathik2012/45La1q0s/5/
I hope the below snippet will do you good. Read inline comments for the basics.
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
});
$('#add-more').click(function () {
//add new entry form
$('#myTable').append('<tr class="t-row"><td><input type="time" onfocus="clearError(this)" class="vTimeStart" /></td><td><input onfocus="clearError(this)" type="time" value="" class="vTimeEnd" /></td><td><input type="button" value="Delete" /></td></tr>');
});
$('#submit').click(function () {
$('.t-row').each(function(i, obj) {
//Get first time entries
var currentStartTimeValue = $('#myTable .vTimeStart').eq(i).val();
var currentEndTimeValue = $('#myTable .vTimeEnd').eq(i).val();
if(i > 0){
//at this point we now have a previous input to validate
//hence we check for validity
var previousIndex = i - 1;
var lastEndTimeValue = $('#myTable .vTimeEnd').eq(previousIndex).val();
if(currentStartTimeValue < lastEndTimeValue){
$(this).css('background-color','#ff0000');
$(this).attr('title','Current StartTime must be lesser than current EndTime!');
alert('Current StartTime cannot be lesser than previous EndTime');
return false;
}
}
if(!currentStartTimeValue){
$(this).css('background-color','#ff0000');
$(this).attr('title','Enter value for Start Time!');
alert('Enter value for Start Time!');
return false;
}else if(!currentEndTimeValue){
$(this).css('background-color','#ff0000');
$(this).attr('title','Enter value for End Time!');
alert('Enter value for End Time!');
return false;
}else if(currentStartTimeValue >= currentEndTimeValue){
$(this).css('background-color','#ff0000');
$(this).attr('title','Current StartTime must be lesser than current EndTime!');
alert('Current StartTime must be lesser than current EndTime');
return false;
}
if(i === $('.t-row').length - 1){
//last item in the loop. all good!
alert('All good!');
}
});
});
function clearError(el){
//reset error state
$(el).parent().closest('tr').css('background','#ffffff');
$(el).parent().closest('tr').attr('title','');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<thead>
<td>
Start Time
</td>
<td>
End Time
</td>
<td>
</td>
</thead>
<tr class="t-row">
<td>
<input type="time" onfocus="clearError(this)" class="vTimeStart" />
</td>
<td>
<input type="time" onfocus="clearError(this)" class="vTimeEnd" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<input id="add-more" type="button" value="Add more">
<input id="submit" type="button" value="Submit">
Related
First of all, sorry for the post's title.
I am trying to get references from these questions:
GetElementsByName with array like name
getElementsByName: control by last partial name
How can I select an element by ID with jQuery using regex?
And more or less I understood how to proceed.
I am using this code to check all the <input> and prevent the form from being submitted if any of the field is empty:
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel");
var inp = form.getElementsByTagName('input');
for(var i in inp){
if(inp[i].type == "text"){
if(inp[i].value == ""){
inp[i].focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
}
});
The "problem", is that I was asked to add an exception, and one of these <input> can be empty.
The form is similar to this, what I post here is simplified:
<form id="insertForm" >
<div id="insertPanel">
<input type="text" name="FOO1" id="FOO1" />
<input type="text" name="FOO2" id="FOO2" />
<input type="text" name="FOO3" id="FOO3" />
<input type="text" name="FOO4" id="FOO4" />
<button type="submit" name="submit" value="Submit" >Send</button>
<table id="tab_logic">
<thead>
<tr>
<th>Bar1</th>
<th>Bar2</th>
<th>Bar3</th>
<th>Bar4</th>
<th>Bar5</th>
<th>Bar6</th>
<th>Bar7</th>
<th>Bar8</th>
<th>Bar9</th>
</tr>
</thead>
<tbody>
<tr id='addr_100'>
<td>
<input type="text" name='prefs[0][FooBar_A]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_B]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_C]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_D]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_E]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_F]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_G]' />
</td>
<td>
<input type="text" name='prefs[0][FooBar_H]'/>
</td>
<td>
<input type="text" name='prefs[0][FooBar_I]' />
</td>
</tr>
<tr id='addr_101'/>
</tbody>
</table>
<a id="add_row">Add Row</a>
<a id='delete_row'>Delete Row</a>
</form>
I removed all the CSS. Kept is really simple.
I was asked to NOT check the input <input type="text" name='prefs[0][FooBar_G]' />
As you can see, it is an array, at every "add row" click, there is a jquery that adds a new row with name='prefs[1][FooBar_A]' and so on.
I tried to work on the for():
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel");
var inp = form.getElementsByTagName('input');
var SKIP = form.querySelectorAll('input[name$="FooBar_G]"]');
for(var i in inp){
if(inp[i].type == "text"){
if(inp[i].value == ""){
if (SKIP){ console.log("Element " + SKIP.innerText + " found. "); continue; }
inp[i].focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
}
});
And many other versions.. failing.
Anyone knows how to make this working?
let inputs = [...document.querySelectorAll('input')]
let reg = new RegExp('FOO[0-9]', 'g')
let filtered = inputs.filter(({ name }) => name.match(reg))
console.log(filtered)
<input type="text" name="FOO1" id="FOO1" />
<input type="text" name="FOO2" id="FOO2" />
<input type="text" name="FOO3" id="FOO3" />
<input type="text" name="FOO4" id="FOO4" />
<input type="text" name='prefs[0][FooBar_A]' />
<input type="text" name='prefs[0][FooBar_B]' />
<input type="text" name='prefs[0][FooBar_C]' />
<input type="text" name='prefs[0][FooBar_D]' />
$('form[id="insertForm"]').on("submit", function (e) {
var form = document.getElementById("insertPanel")
var reg = new RegExp('FOO[0-9]', 'g')
var inputs = [...document.querySelectorAll('input')].filter(({name}) => name.match(reg))
inputs.forEach((inp, i) => {
if(inp[i].type === "text" && inp[i].value === ""){
inp[i].focus();
$("#formAlert").show(400);
}
})
});
Use querySelectorAll to exclude that input (and to shorten your code). Specifically, the :not([name$=FooBar_G\\]]) selector to exclude the one you want to keep out. It can also be used to specify the text inputs.
You can simply the selector using the *= contains selector if you know that there will not be false positives. :not([name*=FooBar_G])
$('form#insertForm').on("submit", function(event) {
var inputs = this.querySelectorAll("#insertPanel input[type=text]:not([name$=FooBar_G\\]])");
for (var i = 0; i < inputs.length; i++) {
if (!inputs[i].value) {
inputs[i].focus();
event.preventDefault()
$("#formAlert").show(400);
break;
}
}
});
And to do it in a more modern way, I'd do this:
document.querySelector('form#insertForm').addEventListener("submit", function(event) {
const inp = Array.from(
this.querySelectorAll("#insertPanel input[type=text]:not([name$=FooBar_G\\]])")
).find(inp => !inp.value);
if (inp) {
inp.focus();
event.preventDefault()
$("#formAlert").show(400);
}
});
Some things:
1) if(SKIP) will always enter the branch as objects are truthy. You need compare sth (===)
2) If you already include such a heavy library like jquery you should use it everywhere to make it worth it
$('form[id="insertForm"]').on("submit", function (e) {
const inputs = $("#insertPanel > input").toArray();
const skip = $('input[name$="FooBar_G]"]')[0];
for(const input of inputs){
if(input === skip) continue;
if(!input.value){
input.focus();
e.preventDefault();
$("#formAlert").show(400);
break;
}
}
});
I need to solve some calculations and I'm using an .each() loop. I'm populating rows <tr> dynamically so I use .each() to loop through the table but I can't get different values when I have to sort them by vat value.
function callSum(id) {
var counter = 1;
var sum = document.getElementById("sum" + id).value;
var vat = document.getElementById("vat" + id).value;
$('.sumall').each(function() {
$('.vatall').each(function() {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
} else { //if value of VAT is > 0 sum it to vatTotal
document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control"/>
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control "/>
</td>
</tr>
<br><br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control "/>
<br><br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control "/>
Please see disrciptive comments in the source code.
function callSum(id) {
var counter = 1,
sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
if ($(this).val() == 0) { //if value of VAT is 0 sum it to vatTotalZero
//document.getElementById("vatTotalZero").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotalZero").val( sumallVal )
} else { //if value of VAT is > 0 sum it to vatTotal
//document.getElementById("vatTotal").value = $(this, ".sumall").val; // don't know how to solve this
/* set the value */
$("#vatTotal").val( sumallVal )
}
counter++;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" onchange="callSum(1)" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
Here we go with an enhanced version.
In this version I removed unused stuff, set an appropriate event handler and shortened the syntax slightly
function callSum(id) {
var sum = document.getElementById("sum" + id).value,
vat = document.getElementById("vat" + id).value,
sumallVal;
$('.sumall').each(function () {
/* get the value */
sumallVal = $(this).val();
$('.vatall').each(function () {
/* set the value */
$( $(this).val() == 0 ? "#vatTotalZero" : "#vatTotal" ).val( sumallVal )
});
});
}
$(document).ready(function() {
$('.sumall.form-control').on('input', function() {
// get number id directly from string id by deleting all non numbers
callSum( this.id.replace(/[^0-9]/gi, '') );
})
});
<tr>
<td class="col-sm-1">
<!-- <input type="text" name="sum[]" id="sum1" onfocus="callSum(1)" class="sumall form-control" /> -->
<input type="text" name="sum[]" id="sum1" class="sumall form-control" />
</td>
<td class="col-sm-1">
<input type="text" name="vat[]" id="vat1" class="vatall form-control " />
</td>
</tr>
<br>
<br>
<label>All Sums without VAT (vat 0)</label>
<input type="text" name="vatTotalZero" id="vatTotalZero" class="form-control " />
<br>
<br>
<label>All Sums with VAT (vat > 0)</label>
<input type="text" name="vatTotal" id="vatTotal" class="form-control " />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have created one form with dynamically created fields. and i have a one check box with unique ID . when user clicks that check box then only those two fields are visible ("name and age"). after clicking only "age" field need to be validate .
here is my code :
$(document).ready(function() {
$('#person').click(function() {
function formValidator(){
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
});
});
$(document).ready(function() {
$('#person').click(function() {
$('#name').attr('required','required');
$('#age').attr('required','required');
});
});
style is :
.selectContainer{
display:none;
}
input[type=checkbox]:checked ~ .selectContainer {
display:block;
}
Html code is:
<form action="" method="post" onSubmit="return formValidator()">
<label for="name">Any Accompanying Person ?:</label>
<input type="checkbox" name="person" id="person" >Yes
<div class="selectContainer">
<br>
<label>Person Details</label>
<p>
<div style="padding-left:70px;">
<input type="button" value="Add Person" onClick="addRow('dataTable')" />
<input type="button" value="Remove Person" onClick="deleteRow('dataTable')" />
</div>
</p>
<table style="padding-left:50px;" id="dataTable" class="form" border="1" >
<tbody>
<tr>
<p>
<td><input type="checkbox" name="chk[]" checked="checked" /></td>
<td>
<label>Name</label>
<input type="text" size="20" name="name[]" id="name" >
</td>
<td>
<label>Age</label>
<input type="text" size="20" name="age[]" id="age" >
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
</div>
</div>
<h3>Choose Your Payment Option</h3>
<h1>
<div style="padding-left:150px;">
<input type="radio" name="type" value="visa">VISA/MASTER CARD:<br />
<input type="radio" name="type" value="cheque"> CHEQUE/DEMAND DRAFT<br />
<input type="radio" name="type" value="neft">NEFT<br /><br/>
</div>
<label></label>
<input type="submit" name="submit" value="submit"><br />
</form>
problem: the form field "age" is validating successfully by clicking check box ("Any Accompanying Person ?:"). problem is when user try to submit the form without clicking that check box then all so its asking for validate . how get salutation for this ? please help
The validator is within a click handler, which should live outside of that (On the base on the document.ready()).
Also if you just want to validate when that checkbox is clicked you could check it within the javascript and select it via the name of the checkbox (If it has a unique ID each time).
function formValidator(){
var age = document.getElementsByName('age[]');
if($("input[name = 'chk[]']").prop('checked')){
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
Bring all javascript functions outside of click events. Try this formValidator function
function formValidator(){
if($("#person").is(":checked")) {
var age = document.getElementsByName('age[]');
for (var i = 0; i< age.length; i++) {
if(!isNumeric(age[i], "Please enter a valid Age")){
return false;
}
}
}
return true;
}
I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.
I have this code:
<div id="star-rating">
<script type="text/javascript">
$(function(){
$('#star-rating form').submit(function(){
$('.test',this).html('');
$('input',this).each(function(){
if(this.checked)
//$('.test',this.form).append(''+this.name+': '+this.value+'<br/>');
$('.test',this.form).append(this.value);
});
return false;
});
});
</script>
<form name="form1" method="post" action="<?=base_url();?>rate/student">
<div class="dbtable">
<table cellpadding="0" cellspacing="0" border="0"><tbody>
<th colspan="4" align="left">Personal Appearance</th>
<tr><td width="10px"></td><td width="60%">Neatness</td>
<td width="20%">
<input name="neat" type="radio" class="neat-star" value="1" title="Poor"/>
<input name="neat" type="radio" class="neat-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td>Health</td>
<td>
<input name="health" type="radio" class="health-star" value="1" title="Poor"/>
<input name="health" type="radio" class="health-star" value="2" title="Fair"/>
</td>
</tr>
<tr><td></td><td align="right"></td>
<td><input type="submit" value="Submit scores!" /></td>
<td><div class="test Smaller">
<span style="color:#FF0000">Results</span>
</div>
</td></tr>
So now I have 2 radio star rating. What I want is when I click the submit score it will add up the 2 selected radio box. E.g when click radio button neat with the value of 1 and radio button health with the value of 2 then the result will show 3 coz 1+2=3 in my div class=test. Could anyone help me with this.
$('#star-rating form').submit(function() {
$('.test', this).html('');
var total = 0;
$('input', this).each(function(){
if(this.checked) {
total += parseInt(this.value, 10);
}
}
//Do something with total
return false;
});
You need to use parseInt to convert a String into a Number. Otherwise, you'll just be concatenating values onto a string.
$('#star-rating form').submit(function() {
var score = $(this).find('.neat-star').val()
+ $(this).find('.health-star').val();
$(this).find('.test').html(score);
return false;
});
Try this
(function(){
$('#star-rating form').submit(function(){
var neatVal, healthVal;
neathVal = $(this).find("input[name=neat]:checked").val();
healthVal = $(this).find("input[name=health]:checked").val();
$('.test', this).append(praseInt(neatVal) + parseInt(healthVal ));
return false;
});
});