Check empty field from html array in javascript - javascript

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();

Related

Changeing code inside a html file

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.

Pass PHP variable to javascript/jquery for error checking

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.

Hide zero values of an empty input(number type)

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);?>

Dynamically add text box in javascript

I dynamically add a text box whenever a user clicks a button to add more, which works fine. However, in PHP when I get the submitted field values by $_POST['skills'] , I only receive the first text box value, not the dynamically added ones. I'm almost positive there is something wrong with the way I am adding the text boxes in javascript.
I use the following method to add a text box field:
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
The HTML code I have for the text box is :
...
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td><div class="button">+ Add</div></td>
Here is the php code as well:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$allskills = $_POST['skills'];
$size = count($_POST['skills']);
print_r($allskills);
}
The output is the following, even though I inputted three values
Array ( [0] => java )
Your field name is skills not skill .So it should be $_POST['skills'].$_POST['skills'] is an array in this case. So access try with var_dump($_POST['skills']); and you will see all the values.
As far as the $_POST['skills'] is an array, Try this..
$skill = $_POST['skills'];
foreach($skill as $value){
echo $value;
}
do you mean the values of $_POST['skills']
i dont think there is something wrong with your javascript, what is wrong is how you read the post data in your php. The post data will be an array in this case, so you access it like this $_POST['skills'][0] //value of 1st input $_POST['skills'][1] //value of 2nd input
$_POST['skills'] is an array,So use print_r() to view the array.You may use as follows
<script type="text/javascript">
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
</script>
<form method ="post">
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
</form>
<td><div class="button">+ Add</div></td>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){
echo "<pre>";
print_r($_POST['skills']);
echo "</pre>";
}
?>
you could use the array length. Try to this
for($i=0;$i<=count($skills)-1;$i++)
{
$per=$skills[$i]*$skills[$i];
echo $per;
}

Validating check box and input

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;
}

Categories

Resources