How to button enable when all textbox has value in jQuery? - javascript

I am new in programming. Here I have given description of my problem
I have one pair of two text box. One text box is for URL and other is for instruction but all text-boxes created dynamically depending on what value comes from database.
For example $testing_type_id=2 so I get total two pair of text boxes, let it called bundle. $i is used to identify textbox uniquely.
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
Here what I wanted to do that if all bundle has value, either in one textbox or both textbox so and so enable submit button. If I removed value so disable submit button using jQuery.

I think this will work
$(document).ready(function(){
$("input[class^='uploadtxt']").keyup(function(e){
var alltxt=$("input[class^='uploadtxt']").length;
var empty=true;
$("input[class^='uploadtxt']").each(function(i){
if($(this).val()=='')
{
empty=true;
$('#checkout').prop('disabled', true);
return false;
}
else
{
empty=false;
}
});
if(!empty) $('#checkout').prop('disabled', false);
});
});​
An example is here.

if($('.uploadtxt1').val() !='' && $('.uploadtxt2').val() !='')
{
$('#checkout').hide();
}
else
{
$('#checkout').show();
}

So assuming you want to show/ enable the button if the textareas / inputs have values. You could do something like this using jQuery.
$(window).ready(function(){
if( $('input, textarea').val().length >=0 ){
//run function to enable button
}
else if ( $('input, textarea').val().length <=0 ){
//run function to disable button
}
});
I think this is what you are sort of looking for. Let me know if I am way off or not understanding you correctly.

I am going to suggest a minor markup changes so that will be easy to handle the traversing.
Wrap the elements in a <div>
<div class="item">
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
</div>
Then, Attach a snippet on the change event
$("input[type=text]", $(".item")).change(function() {
var allField = true;
$(this).closest(".item").find("input[type=text]").each(function() {
allField = allField && ($(this).val().length > 0)
});
if(allField) {
$(this).closest(".item").find("input[type=submit]").prop('disabled', false);
}
});
Demo of Working Solution

Related

How to make sure form cannot be submitted if text field is empty when user selects False Hit radio button?

I am doing something to prevent user from submitting HTML Form without leaving their remarks for False Hits.
Conditions:
Only if False Hit radio button is selected
The remarks text field cannot be empty (Compulsory)
Currently, I have used JavaScript to check if the text field (Remarks) is empty.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Please enter remarks for false hits selected.");
return false;
};
I am also able to check which radio button is selected with JavaScript.
<input type="radio" name="select" id="truehit" value="true" />
<input type="radio" name="select" id="falsehit" value="false" />
if(document.getElementById('falsehit').checked) {
//False Hit radio button is checked
}
else if(document.getElementById('truehit').checked) {
//True Hit radio button is checked
}
However, I am quite stuck at linking both conditions together. Is there a simpler method to this? Any help is greatly appreciated. Thank you in advance.
This is how my Form looks like.
<body bgcolor="#FFFFFF">
<br />
<div align="center" class="h1">
<h1>Entity Search</h1><br />
</div>
</html>
<br />
<?php
include("db_connect.php"); //connect to database
#$loginid = strtoupper(base64_decode($_POST['LanID'])); //to capture
the user's LanID as the UserID
if($loginid == "")
{
$userID = $_SESSION['loginid'];
}
else
{
$_SESSION['loginid'] = $loginid;
$userID = $_SESSION['loginid'];
}
$userID = $_SESSION['loginid'];
//to insert date and time of the records
date_default_timezone_set('Asia/Singapore');
$Date = date('Y-m-d');
$Time = date ('h:i:s a');
$userID = $_SESSION['loginid'];
$loginid = "";
$entityfromform = $_GET["entity"];
?>
<br />
<?php
//connection to database
$connectionInfo = array( "Database"=>"test","UID"=>$test,"PWD"=>$test);
$db_connect=sqlsrv_connect($serverName, $connectionInfo);
//to retrieve the department name from the user database and insert
department name of the user into the records
$namesql = "SELECT Name, DeptName, Role FROM RPDB.dbo.Userdb WHERE
LanID='$userID';";
$name_query = sqlsrv_query($db_connect,$namesql);
while($row = sqlsrv_fetch_array($name_query, SQLSRV_FETCH_ASSOC))
{
$nameontop = iconv("gb2312","UTF-8",$row['Name']);
$admincheck = iconv("gb2312","UTF-8",$row["Role"]);
$deptnamecheck = iconv("gb2312","UTF-8",$row["DeptName"]);
}
$negative = "Negative Hit: No results found.<br />";
$result = "$entityfromform <br />Negative Hit: No results found.<br />";
//variable to insert into the table as result
//search for keyword from form in the Entity Table List where Name =
keyword
$entitysql = "SELECT * FROM RPDB.dbo.entitysearch_table WHERE Name LIKE
'%" . $entityfromform . "%' OR Name = '".$entityfromform."'";
$entity_query = sqlsrv_query($db_connect,$entitysql);
//variables
$i=0;
while($row = sqlsrv_fetch_array($entity_query, SQLSRV_FETCH_ASSOC))
{
$name[$i] = $row["Name"];
$brn[$i] = $row["Business_Registration_Number"];
$address[$i] = $row["Registered_Address"];
$group[$i] = $row["Applicable_Limb_of_Related_Party_Group"];
$selectradio[$i] = 'selectradio'.$i;
$text[$i] = 'text'.$i;
$i++;
}
if(#$name != NULL) //Positive Result
{
echo "<input type='button' name=uncheck' value='Uncheck All'
class='uncheck' onClick='window.location.reload()'>"; //uncheck all
function where it clears all changes
echo "<h2><div align='center'>Results found for:
$entityfromform</div></h2><br />";
//table to display the data
echo "<div align='center'>
<table>
<tr>
<th>Name</th>
<th>Business Registration Number</th>
<th>Registered Address</th>
<th>Applicable Limb of Related Party Group</th>
<th>True Hit</th>
<th>False Hit</th>
<th>Unable To Ascertain</th>
<th>Remarks, for false hit</th>
</tr>
</div>";
echo "<strong><div class='wording'>Positive Hit: </div></strong>";
echo "<br /><br />";
$x=0;
?>
<!--The form data is sent for processing to action_handler.php by HTTP POST method-->
<form method="post" id="form" action="action_handler.php" enctype="multipart/form-data">
<?php
//data displayed in tables along with checkboxes for true hit, false hit, unable to ascertain and text box for remarks where applicable
for($x=0;$x<$i;$x++)
{
echo "<tr>
<td>" . $name[$x] . "</td>
<td>". $brn[$x] . "</td>
<td>". $address[$x] . "</td>
<td>". $group[$x] . "</td>
<td>
<label class='container'>
<input type='radio' id='truehit' name='".$selectradio[$x]."' value='true hit' class='btn' required>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='falsehit' name='".$selectradio[$x]."' value='false hit' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label class='container'>
<input type='radio' id='unabletoascertain' name='".$selectradio[$x]."' value='unabletoascertain' class='btn'>
<span class='checkmark'></span>
</label>
</td>
<td>
<label><input type='text' name='".$text[$x]."'>
</label>
</td>
</tr>" ;
}
echo "</table>"; //table closed
echo "<br /><br /><br />";
echo "<input type='button' value='Submit' class='submit' onClick='empty()'>"; //submit button to confirm
?>
</form>
<?php
//sessions to be used in others
$_SESSION['num'] = $x;
$_SESSION['entityfromform'] = $entityfromform;
}
else
{
echo "<div align='center'><h2>Results found for: $entityfromform</h2>
<br />";
echo "<div class='wording' align='center'>$negative</div><br><br>
<br>";
}
?>
</table>
</body>
your empty() function does not return anything if the textbox has a value and hence for that condition it is undefined; you can create a function for your requirement like:
function doSubmit()
{
if(document.getElementById('falsehit').checked)
{
if(document.getElementById("roll-input").value == '')
{
alert("Please enter remarks for false hits selected.");
return false;
}
}
return true;
}
and call this method to validate, so if falsehit is checked and remarks has a value it'll return true or else false.
Hope this helps; let me know if I'm missing to understand your problem here..
Happy coding...
You can use a set of if statements like below. This basically checks if the falsehit radio button is checked. If it is, then it checks if the text is empty. If the text is empty, it alerts what you wanted it to. If the text isn't empty, it submit's the form.
Also, if falsehit is not checked, it automatically submit's the form.
As per request in the comments: Now I get every radio button, and loop through them to check if they're selected. If they aren't, you get an alert message saying Please select all accordingly. Otherwise, it just works the same as before.
function empty() {
var text;
var groups = document.querySelectorAll("[id^=group]");
var selected = {};
var radioButtons;
var submitForm = true;
groups.forEach(e1 => {
radioButtons = e1.querySelectorAll("input[type=radio]");
radioButtons.forEach(e2 => {
if (e2.checked) {
selected[e1.id] = true;
}
});
if (selected[e1.id] == undefined) {
selected[e1.id] = false;
}
});
groups.forEach(e => {
text = e.children[0].value;
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].id == "falsehit") {
if (e.children[i].checked) {
if (text.length == 0) {
alert("Please enter remarks for false hits selected.");
submitForm = false;
}
} else if (selected[e.id]) {
//Don't need to do anything. Just need to prevent the next else from accessing these values
} else {
alert("Please select all accordingly.");
submitForm = false;
}
}
}
});
if (submitForm) {
document.getElementById("form").submit();
}
}
<form id="form">
<fieldset id="group1">
<input type="text" id="roll-input" />
<input type="radio" name="group1" id="truehit" value="true" />
<input type="radio" name="group1" id="falsehit" value="false" />
</fieldset>
<fieldset id="group2">
<input type="text" id="roll-input" />
<input type="radio" name="group2" id="truehit" value="true" />
<input type="radio" name="group2" id="falsehit" value="false" />
</fieldset>
<input type="button" value="Submit" onclick="empty()" />
</form>

How do I save data from a checkbox array into database

function check_uncheck(truefalse) {
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form.chkboxarray[i].checked = true;
} else {
form.chkboxarray[i].checked = false;
}
}
}
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
The snippet shows how it works without connection to a database
I am trying to save the data that is sent from the checklist to a database but i'm stuck. I was thinking of using a foreach but I don't know what to put in it.
I though of putting it as:
foreach($_POST['id'] as $add){
insert into database...
}
How do I do this?
If I do this as Fred-ii and xjstratedgebx suggested where I just change name="chkboxarray" to name="chkboxarray[]" then the javascript code would stop working.
<?php
include '../conec.php';
mysql_select_db("test",$conec)or die('Database does not exist.') or die(mysql_error());
$sql = mysql_query("SELECT * FROM user WHERE state='Not Signed Up'");
?>
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<?php
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$name = $row['name'];
$lName= $row['lName'];
$concate = $name.' '.$lName;
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
}
?>
<!--<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />-->
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
<script type="application/javascript">
function check_uncheck(truefalse){
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for(var i=0;i < boxes;i++){
if (truefalse) {
form.chkboxarray[i].checked=true;
} else {
form.chkboxarray[i].checked=false;
}
}
}
</script>
If you change the name of your checkbox from "chkboxarray" to "chkboxarray[]", then any boxes that are checked when the form is submitted will pass their values as an array to the server under the key of "chkboxarray".
Basically, change this line:
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
To:
echo '<input type="checkbox" name="chkboxarray[]" value="'.$id.'" />'.$concate.'<br />';
As a result, if you var_dump the $_POST super global, you should see something like:
array(1) {
[chkboxarray]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
In the example above, the checkboxes for id's 3 and 4 were checked, so they were sent to the server.
Once you have that array, inserting it into your database depends heavily on what you're trying to accomplish and your database's schema.
Hope that helps.
Also, in fairness, this is exactly what #Fred meant in his comment.
Edit 1
To make the javascript work with the change of the input name, you'll need to update all the places in your javascript where you were referencing the name of the input to the new name (chkboxarray[]).
The resulting code should look like this:
<script type="application/javascript">
function check_uncheck(truefalse) {
var boxes = document.forms[0]["chkboxarray[]"].length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form["chkboxarray[]"][i].checked = true;
} else {
form["chkboxarray[]"][i].checked = false;
}
}
}
</script>
I've created a fiddle to show this works for checking/unchecking all the boxes: https://jsfiddle.net/solvomedia/3Ln468u3/

php increase and decrease quantity of product?

im noob at php but my question is this:
im having a while loop which presents to me all the products from the db
im trying to add a + and - quantity buttons next to the buy now button that will increase and decrease by pressing them (just display the number not affect the db)
but the problem is that the quantity number won't pass the number 2. Can anyone lend me some brains with this one?
$value = 1; //to be displayed
if(isset($_POST['incqty'])){
$value= $value +1;
echo $value;
}
if(isset($_POST['decqty'])){
$value = $value -1;
echo $value;
}
<form method='post'>
<input type='hidden' name='item'/>
<td><button name='incqty'>+</button><input type='text' size='1' name='item' value='$value'/><button name='decqty'>-</button></td>
</form>
I already tried to do it with js
<form name="f1"> <input type='text' name='qty' id='qty' />
<input type='button' name='add' onclick='javascript:document.getElementById("qty").value++;' value='+'/>
<input type='button' name='subtract' onclick='javascript: document.getElementById("qty").value--;' value='-'/>
</form>
but the buttons were unclickable...
I'm guessing you're learning PHP and because of that not doing this with javascript. Below code should work for you:
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
if(isset($_POST['incqty'])){
$value += 1;
}
if(isset($_POST['decqty'])){
$value -= 1;
}
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<button name='incqty'>+</button>
<input type='text' size='1' name='item' value='<?= $value; ?>'/>
<button name='decqty'>-</button>
</td>
</form>
If I understood the question, you need to show the values of the items in the cart and modify it by pressing + and - button.
I think you shoud use javascript for this (as you are saying that no affects database)
I'm writing some code in jQuery to show an example of the plus button
$('button[name="incqty"]').bind('click', funcion(){
var actual = $('input[name="intem"]').val();
if (actual <= 1) {
actual = actual +1;
}
$('input[name="intem"]').val(actual);
});
Of course is better not to hardcode values in the code and use constants or variables (for the 1 limit) but I hope this example help you.
I tried your javascript snippet and it worked perfectly.
That being said, is there a reason you are not using the HTML number input?
<input type="number" name="quantity" min="1" max="99">
Edit: I used the code from Daan's answer as the template but...
<?php
$value = isset($_POST['item']) ? $_POST['item'] : 1; //to be displayed
?>
<form method='post' action='<?= $_SERVER['PHP_SELF']; ?>'>
<!--<input type='hidden' name='item'/> Why do you need this?-->
<td>
<input type="number" name="item" min="1" max="99" value="<?= $value; ?>">
</td>
</form>
<input type="button" value = "-" onclick="minusbot()" />
<input type="number" name="kgcount" id = "kilohere" value = "1" >
<input type="button" value = "+" onclick="plusbot()" />
<script>
function minusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) - 1;
var checknumifzero = parseInt(document.getElementById('kilohere').value);
if(checknumifzero < 1) //preventing to get negative value
{
document.getElementById('kilohere').value = 1;
}
}
function plusbot()
{
document.getElementById('kilohere').value = parseInt(document.getElementById('kilohere').value) + 1;
var checknumiffifty = parseInt(document.getElementById('kilohere').value);
if(checknumiffifty > 50) //just a limit
{
document.getElementById('kilohere').value = 50;
}
}
</script>

How to change style of Clicked particuler button?

i have two files
in xml.php i am displaying data from a xml file
also displaying button with xml data by this code
<input type="button" id="class" value="Select this Agent" onClick="Selected(this.id);">
so buttons displayed on page is equal to elements in xml. and i want to change background color of clicked button.
here is my javascript code for changing style of button
function Selected(ClickedId){
alert(ClickedId);
ClickedId.css('background-color', 'Green');
}
and whole code is
<?php
$xml = simplexml_load_file("agent.xml") or die("Error: Cannot create object");
function processXML($node){
foreach($node->children() as $agent => $data){
$agent= trim($agent);
if($agent!="" && $agent=='image'){
?><div class="inline"><?php
echo "<br>";
echo "</br>";
echo "</br>";
echo '<img src='.$data.' >';?></div>
<!--<input type="button" value="Select this Agent">--><?php
}
elseif($agent == 'phone'){
?><div class="btqn"><input type="button" id="class" value="Select this Agent" onClick="Selected(this.id);"></div> <?php
}
elseif($agent!=""){
?> <div class="Table"><?php echo $data;?></div>
<?php
//echo "</br>";
}
else{
echo "<hr>";
}
processXML($data);
}
}
processXML($xml);
?>
So please anyone can tell me where i am wrong.
any suggestion should be appreciable
Please Help
Try out
change this line
<input type="button" id="class" value="Select this Agent" onClick="Selected(this.id);">
to
<input type="button" id="class" value="Select this Agent" onclick="Selected(this);">
Note here instead of passing id pass this reference.
So you can use
function Selected(ClickedId){
alert(ClickedId);
ClickedId.style.backgroundColor = 'green';
}
JQuery
$("#class").click(function(){
$(this).css("background-color","green");
})
See Fiddle Demo
Try
document.getElementById(ClickedId).style.backgroundColor = "green";
[Updated part as user requested]
First change from id to class selector as ids are not supposed to be duplicated and pass this instead of this.id. Also if you want to clear all the other buttons backgrounds you can make use of getElementsByClassName() function.
HTML
<input type="button" class="class" value="Select this Agent" onClick="Selected(this);">
<input type="button" class="class" value="Select this Agent" onClick="Selected(this);">
<input type="button" class="class" value="Select this Agent" onClick="Selected(this);">
Javascript code
function Selected(elem) {
var buttons = document.getElementsByClassName('class');
for (var i = 0; i < buttons.length; i++) {
buttons[i].style.backgroundColor = '';
}
elem.style.backgroundColor = "green";
}
Jsfiddle here

Checking multiple files

I currently have a file element, and a button that allows a user to add more file elements so that if they wanted to, they could select multiple at once. I want to be able to loop through them and need some assistance as to what direction I should take or if there is a correct syntax to do this. Form, php, and JS code below.
Form:
<form action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" method="post" enctype="multipart/form-data" name="upload_form" id="upload_form">
<br />
<input type="file" name="file[]" id="file"/>
<input id="addbutton" type="button" onclick = 'javascript: add()' value="ADD ANOTHER FILE" />
<br />
<input type="submit" id="submit" name="submit" value="SUBMIT" />
</form>
PHP:
if($_POST['submit'] == "SUBMIT")
{
$count = count($_FILES[ "file" ][ "tmp_name" ]);
echo $count;
for($i = 0; $i < $count; ++$i)
{
if($_FILES && $_FILES['file']['name'])
{
//code that does some stuff here
}
}
}
JS:
<script>
function add()
{
var form = document.getElementById("upload_form");
var addButton = document.getElementById('addbutton');
var br = document.createElement("br");
form.insertBefore(br, addButton);
form = document.getElementById("upload_form");
input = document.createElement("input");
input.type="file";
input.name="file[]";
form.insertBefore(input, addButton);
}
every thing is looks ok, u just need to add index to access particully uploaded file like
<?php
// ...
for($i = 0; $i < $count; ++$i)
{
echo $_FILES['file']['tmp_name'][$i];
// ...
Looks perfect, but you can just use this for multiple selection:
<input type="file" name="file[]" id="file" multiple="multiple" />
You won't need that javascript...

Categories

Resources