Saw other examples close to this, but I seem to still be having issues. The issue is with the script for the third error checker below (#bid < #budm). The amount of the bid field cannot be lower than the amount of the set budget, which #budm should be storing. Pulling a value for #budm from database related to the post id, using php. trying to pass that variable into a js error checker that compares the hidden input field (id="budm"), which stores the php variable, against a user entered input field (id="bid"). Seems to work on random. For instance, on a post where the value of $budgetmin was 400, most entries under 400 were not accepted (which is good), but for some reason, the value '9' was.
<?php
global $current_user;
get_currentuserinfo();
$cid = $current_user->ID;
$cwd = str_replace('wp-admin','',getcwd());
$post = get_post($pid);
$budgetmin = get_post_meta($pid, 'budget_start', true); ?>
<input type="hidden" id="budm" value="<?php echo $budgetmin; ?>">
<script type="text/javascript">
function check_submits()
{
if( jQuery("#days_done").val().length == 0 )
{
alert("<?php _e('Error text3'); ?>");
return false;
}
if( jQuery("#bid").val().length == 0 )
{
alert("<?php _e('Error text2'); ?>");
return false;
}
if (jQuery('#bid').val() < jQuery('#budm').val())
{
alert("<?php _e('Error text'); ?>");
return false;
}
return true;
}
</script>
<input type="text" name="bid" id="bid" class="bid_field" value="<?php echo $bid; ?>" size="10" />
<input class="green_btn grey" style="font-size: 20px; padding-left: 15px; padding-right: 15px; font-weight: 400;" id="submits_crt" type="submit" name="bid_now_reverse" value="<?php echo "Submit"; ?>" />
Any assistance is greatly appreciated!
The problem is that .val() returns a string, not a number. The test is comparing the 2 values as strings, which is not what you want and doesn't behave as you expect.
You need to cast your values as numbers before the test will work. If you know they're always going to be integers, you could use:
var bid=parseInt(jQuery('#bid').val()),
budm=parseInt(jQuery('#budm').val());
if (bid < budm) {
alert("Bid is lower than budget");
}
You could use parseFloat() if the inputs could be floats.
Here's a jsFiddle showing this working.
Related
I have a checkdate php code and I need to replace the dates with some kind of php/jscript code. Maybe some html form element, where I can insert the date how it is needed, submit it and then the date inside the file gets replaced. In this example the date inside this lines:
<?PHP
function isValidDate($sd, $ed, $currentDate = null)
{
if ($currentDate === null) {
$currentDate = date('Y-m-d');
}
return ($currentDate >= $sd && $currentDate <= $ed);
}
$startDate = '2016-10-30';
$endDate = '2016-10-31';
if (isValidDate($startDate, $endDate)) {
header("Location: x.php");
} else {
header("Location: y.htm");
}
?>
In this example in these lines
$startDate = '2016-10-30';
$endDate = '2016-10-31';
the date should be replaced.
It should be possible with some kind of html5 input/form element, where someone can insert the date like
<input type="text" value="XXXX-XX-XX" name="start"/>
<input type="submit" value="startdate"/>
and <input type="text" value="XXXX-XX-XX" name="end"/>
<input type="submit" value="enddate"/>
After submitting the date should be replaced via php/jscript or something like this.
Is this even possible? Can anybody push me in the right direction, maybe with some tutorial links f.e.?
Thanks in advance.
I think you need to use the $_POST array.
First have a form like:
<form method="POST" action="your_file_name.php">
<input type="text" name="start_date"/>
<input type="text" name="end_date"/>
<input type="submit" value="my_form_dates"/>
</form>
and then change your program to
<?php
function isValidDate($sd, $ed, $currentDate = null)
{
if ($currentDate === null) {
$currentDate = date('Y-m-d');
}
return ($currentDate >= $sd && $currentDate <= $ed);
}
if (is_set($_POST['start_date']) && is_set($_POST['end_date'])) {
$startDate = $_POST['start_date'];
$endDate = $_POST['end_date'];
}
if (isValidDate($startDate, $endDate)) {
header("Location: x.php");
} else {
header("Location: y.htm");
}
?>
As you may see, you don't need that value="XXXX-XX-XX" attributes, because the values of the fields will be typed by the user at runtime.
Don't forget make your_file_name.php in the form match with the name of your program, be it .php or .html.
I suggest you to read more about this $_POST array at this page.
Well, I have a form where the user can select an item with a checkbox, the user type how many items he wants to send with an input text, but there are some items that requires a serial number that a checkbox holds.
This is my approach:
<script>
function checkall()
{
var ok=true;
$('input:checkbox[id^="art"]:checked').each(function() {
var vals = $(this).val();
//first attempt
if (typeof document.getElementById(vals+"existencia") === 'undefined') {
ok=false;
return false;
alert("Error message");
}else
if (typeof document.getElementById(vals+"-serie")==='undefined') {
ok=false
return false;
alert("Error message 2");
}
//second attempt
if (obj.hasOwnProperty(vals+'existencia')) {
art = document.getElementById(vals+"existencia").value;
alert(art);
}else if (obj.hasOwnProperty(vals+'serial')) {
sert=document.getElementById(vals+"-serie").value;
alert(sert);
}
});
if(ok)
{
document.getElementById("myform").submit();
}
}
</script>
The script is intended to loop all checked checkboxes and if the input is empty stops and alerts the user and the other stage is when he checks an article with serial number, at least 1 have to checked and also alerts the client
The first attempt, I tried, got passed cause those elements are defined and second attempt throws obj is not defined, maybe I missunderstood the codes and answers I searched, can someone help to achieve my goal or explain me what I did wrong, thank you.
UPDATE:
if ($inicio == 0) {
echo "<tr bgcolor= '#f4f4f4' >";
$inicio = 1;
} else {
echo "<tr bgcolor= white>";
$inicio = 0;
}
?>
<td style="width: 10%;text-align: center;">
<input type="checkbox" name="art[]" id="art" value="<?php echo $articulo; ?>" /></td>
<td width="12%" align="center"><?php echo $diferencia_dias ?> días</td>
<td width="8%" style="text-align: center;"><?php echo $articulo; ?></td>
<td width="45%"><?php echo $descripcion; ?></td>
<?php
if($numserie>0){
$esto = trim($articulo);
$bus_serie = mssql_query("execute serial_madness '$esto','$almacen'");
echo "<td style='width:10%;text-align:left;'>";
while($res_serie = mssql_fetch_array($bus_serie))
{
echo '<input type="checkbox" id="'.$articulo.'-serie" name="'.$articulo.'-Serie[]" value="'.$res_serie["ARTICULO"].','.$res_serie["NUMSERIE"].'_'.$valor.' "> '.$res_serie["NUMSERIE"].' <br>';
}
echo "</td>";
}else{
?><td style="width:10%;text-align:center;"><input type="number" style="text-align:center;width:30px; height:30px;" id="<?php echo $articulo_c; ?>existencia" name="<?php echo
$articulo_c; ?>existencia" value="<?php echo (int)$existencias; ?>" min="1" max="<?php echo (int)$existencias; ?>"/></td>
<?php
} ?>
So, in order to check a checkbox you can just use jquery.
Example: $("#checkboxId").prop('checked', true);
The example above will check the checkbox with id "checkboxId", changing the true to false will uncheck the box;
If you want to check how many or which inputs are checked you can use the .length of the array returned by the jquery selector.
The following will check if all the checkboxes with ids starting with the word "test" are checked:
if($('[id^="test"]:checkbox').length == $('[id^="test"]:checkbox:checked').length)
{
// Do stuff here
}
Likewise you can check if nothing is checked if the length is equal to zero.
I prepared a simple example that I think tackles the general issue you are solving here.
https://plnkr.co/edit/2v6x1DXRpAiaKiBFSMz6?p=preview
Notice that when you click 'Submit' in my plunker example all checkboxes will automatically become checked.
If you click the 'Validate' button it will verify that all checkboxes are indeed checked.
You should be able to use my example to create a solution for your specific case.
You may also want to use the .is() jquery function
example:
$('#' + id).is(":checked")
See the following answer for some similar solutions and explanations: Check if checkbox is checked with jQuery
I have a form that gives me data from database, i have number input type. By default it is "0" showed for empty entries. I want to hide "0" from the field and show the value just if is different of 0.
I tried with the code below but it doesn't work.
<input data-validate="number" value="<?php echo $value; ?>" class="form-control" onload="if(this.value == '0') { this.value = ' '; } " >
Add ternary operator to PHP block instead:
<input data-validate="number" value="<?php echo ($value != '0' ? $value : ''); ?>" class="form-control">
I wrote a minimal php function to do this
function fnB($input){
//function to make values blank in number input boxes
if ($input==0) $r="";
else $r=$input;
return $r;}
?>
So in the form one can then enter
value = <?php echo fnB($value);?>
i have a form that includes several text inputs and checkboxes (the checkboxes comes from a DB), so... i know how to validate them separetly but i need to validate them together, the way i'm doing this only validate checkboxes, i know why its happening but i don't know how to write the right way... ¿can you help me? here is the code:
<form action="sendreq.php" name="contact" onsubmit="return valida_frm(this)" method="post">
<label>Name</label>
<input name="name" type="text" />
<label>Email</label>
<input name="email" type="text"/><!-- And Severeal inputs then the checkboxes-->
<?php $list3 = mysql_query("SELECT * FROM products ORDER BY id ASC LIMIT 20");
while($row = mysql_fetch_object($list3)){ ?>
<input id="product" name="product[]" class="label" type="checkbox" value="<?php echo $row->name?>"><label class="label"><?php echo $row->name?></label>
<?php }?>
The Validation doesn't work fine its evident why, i just need the right way to write and unify the return of the alert:
function valida_frm(form){
var alerta="Ooops:\n";
if (form.name.value == "") {alerta+="Name.\n";}
if (form.email.value == "") {alerta+="Email.\n";}
for(var i = 0; i < form.product.length; i++){
if(form.product[i].checked)return true;}
alert('Oooops');
return false;
if (alerta!="Error:\n"){
alert(alerta);
return false;
}else{
return true;
}
}
Thanks for your time!
Do not call a field for "name" and then test form.name since it already has a .name
Then test form["product[]"] and not form.product - you cannot have id="product" since ID has to be unique!
I suggest you give id="product<?echo $somecounter; ?>" />...<label for="product<? echo $somecounter; ?>">...</label>
Also test against Error (or nothing as in my suggesion) and not Oops
Also more issues fixed
DEMO
function valida_frm(form){
var alerta="";
if (form.name.value == "") {alerta+="Name.\n";} // Please use FullName or such
if (form.email.value == "") {alerta+="Email.\n";}
var chks = form["product[]"],
checked = false;
for(var i = 0; i < chks.length; i++) {
if(chks[i].checked) {
checked = true;
break;
}
}
if (!checked) {
alerta+='Product.\n';
}
if (alerta){
alert("Error:\n"+alerta);
return false;
}
return true;
}
I have a simple HTML files with book seats field as array , the code below
<input type="checkbox" name="book[]" value="<?php echo $i; ?> /><?php echo $i; ?>
<input type="submit" value="BOOK" onclick = "checkIfSeatEmpty()" />
The javascript I used to validate if the field book is empty is:
var x=document.forms["bkfrm"].getElementById("chkbx").value;
//alert(x); alerts 'undefined' !
// var x=document.forms["bkfrm"].getElementById("book").length;
alert(x);
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
return TRUE;
But the above code alerts as undefined ! How can I check if the field is empty?
try like following
var x=document.forms["bkfrm"].getElementById("book").checked;
there is no such id as chkbx or book in your html code.. use the following code
Jquery
$("input[name='book']:checked").val();