Checking times with regular expressions - javascript

I have the following function:
function calcTotal(event)
{var myId = event.currentTarget.id;
myId = myId.replace(/[^0-9]/g, '');
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
{ alert('win');
var minutes = 0;
var n = $('#end'+myId).val().split(':');
minutes = parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#start'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#pause'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert(hours + ':' + minutes);
$('#total' + myId).val(hours + ':' + minutes);
}
else
{ alert('fail');
$('#total' + myId).val('00:00');
}
}
</script>
Let's assume myID equals 1 and the lets assume the following values:
start1 = 00:00
end1 = 10:00
pause1 = 02:00
I would like to for this function to match the previous three values to a regular expression to determine if they are valid times.
After that I would like to calculate the total time worked that day: end1-start1-pause1.
For some reason even with these correct values the function nevers enters the if(....){ alert('win')...}.
I think there is something wrong with my regex, but I already checked (stackoverflow question) and used that regex.
Could anybody tell me what I am doing wrong?
the entire code:
<?php
if(isset($_POST['date']))
{ $sql = "INSERT INTO `hour_administration`.`hours` (`h_id`, `date`, `start`, `end`) VALUES";
foreach($_POST['date'] as $k => $v)
{
if(empty($_POST['date'][$k]))
break;
if($k > 0)
$sql .= ",";
$sql .= "(NULL, '".$_POST['date'][$k]."', '".$_POST['start_time'][$k].":00', '".$_POST ['end_time'][$k].":00')";
}
$sql .= ";";
echo " Query: ".$sql. "</BR>";
mysql_query($sql) or die('Could not query: ' . mysql_error());
}
if(isset($_POST['rows']))
{
$rows = $_POST['rows'];
}else
{
$rows = 5;
}
?>
<script>
$(document).ready(function() {
$( ".date" ).datepicker({ dateFormat: "yy-mm-dd" });
$(".time").mask("99:99");
$('.start_time').change(function(e) {
calcTotal(e);
});
$('.end_time').change(function(e) {
calcTotal(e);
});
$('.pause').change(function(e) {
calcTotal(e);
});
});
function calcTotal(event)
{ var myId = event.currentTarget.id;
myId = myId.replace(/[^0-9]/g, '');
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
{
var minutes = 0;
var n = $('#end'+myId).val().split(':');
minutes = parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#start'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var n = $('#pause'+myId).val().split(':');
minutes -= parseInt(n[0])*60 + parseInt(n[1]);
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert(hours + ':' + minutes);
$('#total' + myId).val(hours + ':' + minutes);
}
else
{ alert($('#start'+myId).val());
$('#total' + myId).val('00:00');
}
}
</script>
<div class="inner_container">
<form name="input" method="POST" id="input">
<table border="1">
<tr>
<td>Date</td>
<td>Start time</td>
<td>End time</td>
<td>Pause</td>
<td>Total</td>
</tr>
<tr>
<?php for($i = 0;$i < $rows;$i++)
{?>
<td><input type="text" class="date" name="date[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="start_time time" name="start_time[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="end_time time" name="end_time[]" id="end<?php echo $i;?>" ></td>
<td><input type="text" class="pause time" name="pause[] " id="pause<?php echo $i;?>"></td>
<td><input type="text" class="total" name="total[]" id="total<?php echo $i;?>"></td>
</tr>
<?php }?>
</table>
<input type="submit" id="submit_inner_container"value="Submit">
</form>
<form name="amount" method="POST">
<label for="name">How many rows would you like?</label>
<input type="text" name="rows" size="3" id="rows" value="<?php echo $rows; ?>"/>
<input type="submit" value="Rows"
</form>
</div>

Your HTML shows that you have two input fields with the same id attribute:
<td><input type="text" class="date" name="date[]" id="start<?php echo $i;?>"></td>
<td><input type="text" class="start_time time" name="start_time[]" id="start<?php echo $i;?>"></td>
Should the first one here use "date" instead of "start"?

var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
timeRegex.test('00:00') // true
timeRegex.test('10:00') // true
timeRegex.test('02:00') // true
Meaning your problem is not with the regex, and I do not see a problem with the if statement. The problem must be with either the selector, or the value in the text box. I would look for whitespace or other characters coming through in the val.

The regex is working fine.
See this jsfiddle
var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
var start = "00:00"
var end = "10:00"
var pause = "02:00"
if(start.match(timeRegex) && end.match(timeRegex) && pause.match(timeRegex))
{
alert('win');
}
else
{
alert('fail');
}
Please post your HTML code that your selectors are accessing, if you want more of an answer

Related

How to display a JavaScript ID on page as well as send same ID to another page

The code below displays and updates the time like a stop watch and works fine. But as well as displaying the running time, I need to send the "register" ID to another PHP page. The "register" ID value is not passing. Thanks in advance for any help.
<script>
function startTime() {
var today = new Date();
var local_year= today.getFullYear();
var local_month= today.getMonth()+1;
if (local_month < 10) {local_month = "0" + local_month};
var local_day= today.getDate();
if (local_day < 10) {local_day = "0" + local_day};
var h = today.getHours();
if (h < 10) {h = "0" + h};
var m = today.getMinutes();
if (m < 10) {m = "0" + m};
var s = today.getSeconds();
if (s < 10) {s = "0" + s};
var db_registration_date = local_year + "" + local_month + "" + local_day + "" + h + "" + m + "" + s;
document.getElementById('txt').innerHTML = local_month + "-" + local_day + "-" + local_year + " " +
h + ":" + m + ":" + s;
document.getElementById('register').innerHTML = db_registration_date;
}
</script>
<body onload="startTime();" style="max-height:auto;margin-top:auto;margin-bottom:auto;" >
<html>
<span id="txt"></span>
<form action="menu_scriptV3.php" method="post">
<input type="hidden" name="last_customer" value="<?php echo $last_customer ?>"
<input type="hidden" name="local_day_name2" id="local_day_name" />
<input type="hidden" name="reg_date" id="register" />
<button class="center-block" type="submit" style="color:black;padding:40px;font-size:35px;width:550px;padding:40px" >
Last Customer
</button>
</form>
</html>
</body>
What you're trying to do should be relatively straight-forward and trivial, so it should be easy to solve / debug what the issue is, however, there are little things that could be tripping you up.
Just make sure you cover everything, failing that try some rudamentary debugging techniques.
Try fixing your HTML
Change this line:
<input type="hidden" name="last_customer" value="<?php echo $last_customer ?>"
To this line:
<input type="hidden" name="last_customer" value="<?php echo $last_customer ?>" />
Debug the request:
When trying to debug, see what your request looks like by analysing the request data submitted using the network tab in chrome inspector, or just var_dump() ing the $_POST variable inside menu_scriptV3.php
// line 1 inside menu_scriptV3.php
<?php var_dump($_POST); exit(); ?>
If the value you want to pass is inside the input field, then you can use javascript to push it to another page.
Try this.
$('#push').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var name = button.data('push_name')
var modal = $(this)
modal.find('.modal-body #push_name').val(name);
})
<input type="hidden" name="reg_date" id="reg_push" />
<?php $reg = 'reg_date'; ?>
<button type="button" name="send" class="btn btn-warning" data-toggle="modal" data-target="#push" data-push_name="<?= $reg ?>" >Send</button>
<!-- This will go to the new php page -->
<input type="text" class="form-control" id="push_name" name="push_name">

Logical Operators doesn't work in javascript and about node counts by input value

I'm trying to make node counter by id, node name, and attribute name&value!
Here I would like to check if every is empty then show "HERE IS NO VALUE OF YOU ENTERED".
here in the end of I try to use <&&> but it doesn't work!
also is that impossible to use just tag instead of in the end of the code? when i tried, it show eror :(
** I have no idea of how to count attribute name&value number..**
I'm realy begginer of javascript ! thank you in advance guys!!
this is my form html.
function javascript_click() {
/* 자바스크립트 id값 찾기 */
if (document.getElementById("value1").value) {
var val = document.getElementById("value1").value;
if (document.getElementById(val)) {
//var myNodelist = document.getElementById("val").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 노드명 찾기 */
else if (document.getElementById("value2").value) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 attribute 찾기 */
/* 자바스크립트 속성명&값 찾기 */
else if (
document.getElementById("value3").value &&
document.getElementById("value4").value
) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
} else if (
(document.getElementById("value1").value &&
document.getElementById("value2").value &&
document.getElementById("value3").value &&
document.getElementById("value4").value) == 0
) {
document.getElementById("cnt").innerHTML += "THERE IS NO VALUE OF YOU ENTERED<br>";
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>id</td>
<td><input type="text" id="value1"></td>
</tr>
<tr>
<td>node name</td>
<td><input type="text" id="value2"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">자바스크립트</button>
</div>
You may do validation like this:
if (document.getElementById("value1").value!=='') {
let val1 = document.getElementById("value1").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val1 + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}

jQuery each function result how to do?

I have to build a form and I have been working on the jQuery, but I get stuck in one step if you can give me any advice please,
So let me explain a bit about the form I have 20 products with offer1, offer2, and monthly fee all this till now is working perfectly i just need after you choose the amount of the specific product and when you press on the next button to display again the result but only where the amount was filled so basically only the products what the customer is interesting about them, and here is my main problem I know I have to do in jQuery each function but I am not sure how to do it ?
I have attached a picture to with the form so you can see an example
form picture
Edit:
Here is my code at the moment:
function convert(value) {
return "" + ((Number(value) || 0).toFixed(2).replace(/(\d)(?=(\d{3})+
(?!\d))/g, "$1,")) + "";
}
function testing(id, normaloffer, talesalesoffer, montlyoffer) {
var normaoffertotal = normaloffer * $('#amount' + id).val();
var talesalestotal = talesalesoffer * $('#amount' + id).val();
var montlytotal = montlyoffer * $('#amount' + id).val();
$(".normaloffertotal" + id).html(normaoffertotal);
$(".telesalesoffertotal" + id).html(talesalestotal);
$(".montlytotal" + id).html(montlytotal);
$('#hnoffer' + id).val(normaoffertotal);
}
console.log(convert(10496.470000000001));
function normaloffertotalcalc() {
var sumnormaltotal = 0;
$('span[id^="normaloffertotalspan"]').each(function () {
var text = $(this).text();
sumnormaltotal += parseFloat(text, 10);
});
$('#sumnormaltotal').html(sumnormaltotal);
var sum_telesale = 0;
$('span[id^="telesalesoffertotalspan"]').each(function () {
var text = $(this).text();
sum_telesale += parseFloat(text, 10);
});
$('#sumtelesaletotal').html(sum_telesale);
var sum_montly = 0;
$('span[id^="montlyofferspan"]').each(function () {
var text = $(this).text();
sum_montly += parseFloat(text, 10);
});
$('#summontlytotal').html(sum_montly);
console.log('Normal Total Offer ' + convert(sum_normal));
console.log('TeleSales Total Offer ' + convert(sum_telesale));
console.log('Montly Total Offer ' + convert(sum_montly));
}
</script>
and here is the html
<?php
$count = 0;
$query = mysqli_query($con, "SELECT * FROM products");
while ($row = mysqli_fetch_array($query)) {
$count++;
?>
<tr>
<td align="center"><?= $row[1] ?></td>
<td align="center"><input type="text" placeholder="0" id="amount<?= $count ?>"
name="amount<?= $count ?>" onblur="normaloffertotalcalc()"
onkeyup="testing(<?= $count ?>, <?= $row[2] ?>, <?= $row[3] ?>, <?= $row[4] ?>)"
style="-webkit-appearance: none; background: none; text-align: center; border: none; width: 40px;">
</td>
<td align="center">£<?= $row[2] ?></td>
<td align="center">£<span class="normaloffertotal<?= $count ?>"
id="normaloffertotalspan">0</span> <input type="hidden"
class="normaloffertotalspan"
id="hnoffer<?= $count ?>">
</td>
<td align="center">£<?= $row[3] ?></td>
<td align="center">£<span class="telesalesoffertotal<?= $count ?>" id="telesalesoffertotalspan">0</span>
</td>
<td align="center">£<?= $row[4] ?></td>
<td align="center">£<span class="montlytotal<?= $count ?>" id="montlyofferspan">0</span></td>
</tr>
<?php } ?>
I find a solution for me with this problem
$('input[type=text]').each(function(){
var val = parseInt($(this).val());
if(val > 0){
var id = $(this).attr('id');
if(id){
console.log(id);
}
console.log(val);
}
});
this is the code what I did and is working perfectly :)
Thanks to everyone who gives me advice
Ups one more thing, do you have any idea how can I export from MySQL only the products who have the id 2,7,1 example :)

Vaule javascript to php echo

<script type="text/javascript">
$(document).ready(function() {
var x;
var test = '';
var y = 0;
var a = 0;
day = 5;
for (i = 0; i < day; i++)
{
y++;
a++;
test = test + '<b>Masa Hari '+ y +' </b>- Masa Dari : <input type="text" placeholder="contoh 16:30" name="masakursus[]" value="<?php echo ' + a +'." ".$masakursus1['+ a +']; ?>"/> Masa Hingga : <input placeholder="contoh 16:30" type="text" name="masakursus[]" value="<?php echo $masakursus1[10];?>"/></br>';
}
document.getElementById("demo").innerHTML =test;
});
</script>
is it possible to put the value of var a into var test.? I want to view output from array php.

Repeating jquery script in every row in table automatically

I have problem with this script. When I change value in column "TO" in table, script substract automatically in column "Number of hours" only in first row value but others no. I need application script with name "PRO1" (updateDue) in every row in table.
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<body onload="changeText()">
<?php
$date = date('Y-m-01');
$end = date('Y-m-t');
//, strtotime('-1 months')//
?>
<?php include 'dbconfig.php' ?>
<table border="1" id="myTable">
<tr>
<td>Date</td>
<td>From</td>
<td>To</td>
<td>Number of hours</td>
</tr>
<tr class="item">
<?php
date_default_timezone_set('UTC');
while(strtotime($date) <= strtotime($end)) {
$day_num = date('d', strtotime($date));
$day_name= date('l', strtotime($date));
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
if (($day_name == "Saturday")||($day_name == "Sunday"))
{
echo "<td id='color'>$day_num $day_name</td><td></td><td></td><td></td></tr>";
}
else {
echo "<td>$day_num $day_name</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$starter= $query_row['start'];
echo "<input type='text' class='txtCal' id='num1' onchange='updateDue()' value=".$query_row['start'].">";
}
echo "</td><td>";
$query = mysql_query("SELECT * FROM norma") or die(mysql_error());
while($query_row = mysql_fetch_assoc ($query))
{
$finisher= $query_row['end'];
echo "<input type='text' class='txtCal' id='num2' onchange='updateDue()' value=".$query_row['end'].">";
}
echo "</td><td>";
$ts1 = strtotime($starter);
$ts2 = strtotime($finisher);
$seconds_diff = $ts2 - $ts1;
$time = ($seconds_diff/3600);
echo "<input type='text' class='txtCal2' id='remainingval' value=".number_format((float)$time, 2, '.', '').">";
echo "</td></tr>";
}
}
?>
</tr>
<tr>
<td></td>
<td></td>
<td>Sum:</td>
<td id="total_sum_value"><span id="total_sum_value"></span></td>
</tr>
</table>
<br>
<!-- SCRIPT NAME PRO1 -->
<script>
function updateDue() {
$('#myTable tr').each(function(){
var total = parseFloat(document.getElementById("num2").value);
var val2 = parseFloat(document.getElementById("num1").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
});
}
</script>
<script>
$(document).ready(function changeText(){
$(document).ready(function changeText(){
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
calculated_total_sum += parseFloat(get_textbox_value);
});
$("#total_sum_value").html(calculated_total_sum);
});
$("#myTable").on('change','input', '.txtCal2', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal2").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
</script>
I want dynamically change table. In column "FROM" and "TO" is value from database. This automatically subtract value (TO-FROM) and sum from this value is down. But when user change some value in column "FROM" or "TO", number will be count automatically. Thank you so much for every advice.
That's because you use the same ID for multiples TDs. You can't do that as an ID is supposed to be used once and help to identify a resource.
instead of an ID, you could use a class :
<table>
...
<tr>
<td><input type="text" class="txtCal num1" value="5" /></td>
<td><input type="text" class="txtCal num2" value="10" /></td>
<td><input type="text" class="txtCal2 remainingval" value="...">
</tr>
...
</table>
Then with jQuery, you can have access to your row values like this :
$('#myTable tr').each(function(){
var total = parseFloat($(this).find('.num2').val());
var val2 = parseFloat($(this).find('.num1').val());
...
var ansD = $(this).find(".remainingval");
ansD.val(total - val2);
});
Also let me point that mysql functions are deprecated and you should not use them anymore. Use PDO instead. (See Why shouldn't I use mysql_* functions in PHP?)

Categories

Resources