Hello guys I just want to ask how can i create a jquery that can detect the user input and assign an attribute or remove an attribute based on the user input.
My scenario is I have a table with 4 columns. First is a dropdown. And the rest are textboxes which are readonly.
The default option for dropdown is NULL or empty. If the user choose from the dropdown, the 2 texboxes should not be readonly. On that process I don't have an error but if the user set back again to NULL. The 2 textboxes won't go back to readonly again. I don't know where's my error.
Here's my jquery code:
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate != ''){
$("#qty"+index).removeAttr('readonly');
$("#price"+index).removeAttr('readonly');
}
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate == ''){
$("#qty"+index).attr('readonly');
$("#price"+index).attr('readonly');
}
});
And this is my table
for($i = 1; $i < 16; $i++){
echo "<!-- ITEM {$i} -->";
echo "<tr>";
echo "<td>";
echo "<select name='code[]' id='code{$i}' style='width:100'>";
echo "<option value=''><label>--CHOOSE ITEMS--</label></option>";
foreach($resultGetCode->result_array() as $list){
echo "<option value='".$list['itemid']."'>".$list['itemcode']." --- ".$list['itemname']."</option>";
}
echo "</select>";
echo "</td>";
//echo "<td><input type='text' name='item[]' class='k-textbox' id='item{$i}' value='' /></td>";
echo "<td><input type='text' name='qty[]' id='qty{$i}' style='text-align: center' readonly='readonly' /></td>";
echo "<td><input type='text' name='price[]' id='price{$i}' style='text-align: right;' onblur='' readonly='readonly' /></td>";
echo "<td><input type='text' name='total[]' id='total{$i}' style='font-family: courier; text-align: right; background-color: lightgray; color: red' readonly='readonly' value='' /></td>";
echo "<tr>";
}
Here's the fiddle: http://jsfiddle.net/rochellecanale/jnkc3/5/
Would be easier to help you if you create a fiddle, but try this
if(validate == ''){
$("#qty"+index).prop('readonly', true);
$("#price"+index).prop('readonly', true);
}
Update. FIDDLE
Related
I'm trying to make a shopping page. I've kept checkboxes for selection and a number type field for quantity. As checkboxes are array I took the quantity field also an array... I know that we can check the checkbox state with checked method, now what I'm trying to achieve is to fetch corresponding quantity value and store it in a session varaible.
<?php
session_start();
if(isset($_POST['sub'])){
$_SESSION['cbb']=$_POST['cb'];
if(isset($_POST['qnty'])){
$_SESSION['qtty']=$_POST['qnty'];
header("location:userlogin.php");
}
}
?>
<html>
<head>
</head>
<body topmargin="20">
<font color='#7FFF00'>
<h1 align='center'>ONLINE SHOPPING</h1>
</font>
<form name="onshop" align="right" action="<?=$_SERVER["PHP_SELF"]?>"
method="post" onsubmit="return validate()">
<input type="submit" value="Add to cart" name="sub" style="background-
color:#7FFF00" />
<input type="reset" value="Reset" style="background-color:#7FFF00"/>
<?php
$db=mysqli_connect("localhost","root","","onlineshop");
if(!$db){
echo "Connection failure.";
}
$sql="SELECT * FROM stock";
$result=mysqli_query($db,$sql)or die("Invalid query ".mysqli_error($db));
echo "<TABLE width=50% height=70% align='center'>";
echo "<TR><TH>ITEM NAME</TH><TH>PRICE</TH><TH>IMAGE</TH><TH>Do you like?
</TH><TH>QUANTITY</TH></TR>";
while($myrow=mysqli_fetch_array($result))
{
echo "<TR><TD align='center'>";
echo $myrow["item"];
echo "</TD>";
echo "<TD align='center'>";
echo $myrow["price"];
echo "</TD>";
echo "<TD align='center'>";
$image=$myrow["image"];
echo '<img height="100" width="100" src="data:image/jpeg;base64,'.base64_encode( $image ).'"/>';
echo "</TD>";
echo "<TD align='center'>";
$itm_id=$myrow["id"];
echo "<input type='checkbox' name='cb[]' value='$itm_id'>";
echo "</TD>";
echo "<TD align='center'>";
echo "<input type='number' name='qnty[]' value='1' max='50'
min='1'>";
echo "</TD>";
echo "</TR>";
}
echo "</TABLE>";
mysqli_close($db);
?>
</form>
<script type="text/JavaScript">
function validate(){
var count=0;
var i;
var cbelements = document.getElementsByName("cb[]");
if(count==0){
for(i=0;i<cbelements.length;i++){
if(cbelements[i].checked){
count++;
}
}
if(count<1){
alert("Select atleast 1 item.");
return false;
}
}
}
</script>
</body>
</html>
Can the onchange event be useful in anyway? or the associative array ?
This is my first post here so I apologize in advance if the formatting is wrong.
I am working on a form that pulls data from MySQL using a loop and outputs it to HTML page. The user then has the option to approve or deny the entries, and based on user selection validation should be required or optional. My current code will validate correctly, but only for the first row being outputted from the loop. I am trying to validate all rows. I have tried using a while loop and foreach statement with no success. Any help would be greatly appreciated!
My Loop & Form:
//connect to the database
$db=mysqli_connect('localhost','root','') or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysqli_select_db($db,"my_db") or die(mysql_error());
//-query the database table
$sql="SELECT id, date, client_name, client_number, date_completed, status FROM clients WHERE client_name LIKE '%" . $search ."%' OR status LIKE '%" . $search ."%' ";
//-run the query against the mysql query function
$result=mysqli_query($db, $sql);
//-count results
$rows=mysqli_num_rows($result);
if($rows=mysqli_num_rows($result)) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>" . $rows . " result(s) found for " . $search . "</h2><br />";
}elseif($rows=mysqli_num_rows($result) == 0) {
echo "<h2 style='margin-left: 10em;margin-bottom: -0.4em;'><br><br><br>0 result(s) found for " . $search . "</h2><br />";
}
//-create while loop and loop through result set
while($row=mysqli_fetch_assoc($result)){
$id=$row['id'];
$date=$row['date'];
$client_name=$row['client_name'];
$client_number=$row['client_number'];
$date_completed=$row['date_completed'];
$status=$row['status'];
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed_returned' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
}
My jQuery code:
I am trying to make date_completed and upload fields required if user selects "Approved" under status field, and optional if he selects "Denied".
<script>
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#date_completed").prop('required',true)
}).trigger("change"); // notice this line
$('#status').on('change', function() {
if ( this.value == 'Approved')
$("#upload").prop('required',true)
}).trigger("change"); // notice this line
</script>
Thanks to KevinB I was able to find a solution to my problem.
I added class names for the input fields (status, date_completed, upload) I was trying to validate:
Updated code below:
echo "<form method='post' enctype='multipart/form-data' action=''>";
echo "<table border='0'>";
echo "<tr>\n";
echo "<td>Timestamp</td><td>Client Name</td><td>Client Number</td>Status</td><td>Date Completed & Returned</td><td>Upload Zip Files</td>\n";
echo "</tr>";
echo "<tr>\n";
echo "<td readonly class='date'>$date</td>\n";
echo "<td><input readonly type='text' id='client_name' name='client_name' value='$client_name'></td>\n";
echo "<td><input readonly type='text' id='client_number' name='client_number' value='$client_number'></td>\n";
echo "<td><select id='status' name='status' class='status' aria-invalid='false'>
<option value=''>Select an option</option>
<option value='Denied'>Denied</option>
<option value='Approved'>Approved</option>
</select></td>\n";
echo "<td><input type='date' id='date_completed' name='date_completed' class='date_completed' value='$date_completed'></td>\n";
echo "<td><input type='file' id='upload' name='upload' class='upload'></td>";
echo "<td class='submit'><input type='hidden' id='hidden' name='hidden' value='$client_name'><input type='submit' id='save' name='save' value='Save'></td>\n";
echo "</tr>";
echo "</table>";
echo "</form>";
<script>
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.date_completed').prop('required',true)
}).trigger("change"); // notice this line
$('.status').on('change', function() {
if ( this.value == 'Approved')
$('.upload').prop('required',true)
}).trigger("change"); // notice this line
</script>
I just want to do something when an option is clicked on/set before submitting its containing form.
Here is my code
echo " <form method='post' action='employees.php?go' id='searchform' >";
echo "<tr>","<td>","<select name='inpuQuery' style ='width:200px;border-radius: 25px;'>",
"<option value='-1'>Filter:</option>",
"<option value='Name'>Name</option>",
"<option value='Surname'>Surname</option>",
"<option value='ID_No'>ID_No</option>",
"</select >",
"<td>", "<tr>";
echo "<tr>","<td>"," <input style='border-radius: 25px;color:blue;width:200px;' type='submit' name='filter' value='Search'> ","<td>", "</tr>";
//the if statement for if isset the search submit query
if(isset($_POST['filter'])){
$criteria=$_POST['inpuQuery'];
switch ( $criteria) {
case "Name":
echo "<input type='text' style ='border-radius: 25px;width:200px;height:40px;' placeholder ='enter first name to search by' name='name_query' > ";
break;
case "Surname":
echo "<input type='text' style ='border-radius: 25px;width:200px;height:40px;' placeholder='enter surname to search by' name='surname_query' > ";
break;
case "ID_No":
echo "<input type='text' style ='border-radius: 25px;width:200px;height:40px;' placeholder ='enter ID Num to search by' name='id_query' > ";
break;
}
}
I am trying to build a web app in php something like stock maintenance, in my earlier page the user is allowed to insert the values of the bill which he gets from the dealer, as in from whom he buys the items which he sells from his shop, hence there he inserts details about the products bought, quantity, price per pc and the rest, i mean total price and the grand total is calculated using JS.
now there is another page where the user sets his profit percent on the grand total(Grand total= total price of the products + Transportation price) and i want the selling price of each item to calculated on its own, using a button.
the rest details are being fetched from the database.
the user sets the profit% on the grand total and now i have used the JS to calculate for each item.
<script type="text/javascript">
function poffy()
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice").value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant").value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice").value=h;
}
}
</script>
Now The problem is that the calculated value is being displayed only once and only for the first item ,not for the other rows.
My php code:
<?php
include("connect.php");
$wer='ccat';
$i=0;
$dater=date("D/M/Y");
$sq="SELECT D_id FROM dealerdetail where Dealer='$wer'";
$res=mysql_query($sq);
while($row=mysql_fetch_array($res))
{
$did=$row["D_id"];
}
$io="Select pdate,tranprice,grandtotal from dateprice where D_id='$did'";
$qw=mysql_query($io);
while($row=mysql_fetch_array($qw))
{
$pd=$row["pdate"];
$as=$row["tranprice"];
$as=0 + $as;
$tr=$row["grandtotal"];
$tr=0 + $tr;
$sql="Select * from additem where Ditem_id='$did'";
$result = mysql_query($sql);
while($pop=mysql_fetch_array($result))
{
$b= $pop["Product"];
$c= $pop["Brand"];
$d= $pop["Model"];
$e= $pop["Dprice"];
$f= $pop["Quantity"];
$t=$e*$f;
$g= $pop["Quality"];
echo "<tr>";
echo "<td> $wer</td>";
echo "<td> $b </td>";
echo "<td> $c </td>";
echo "<td> $d </td>";
echo "<td><input type=text name=costprice id=costprice onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice /></td>" ;
echo "<td> <div align=center ><p>$g<p></div> </td>";
/*echo "<td><input type=text name=purchasedt value=$pd /></td> "; */
echo "<td><input type=text name=current value=$dater /></td>
</tr>";
$i++;
/* if(isset($_POST['S.P']))
{
$po=$_POST['grandy'];
$ap=$po-$tr;
$ao=$ap/$i;
$ai=$ao/$f;
$ul=$_POST['costprice'];
$re=$ai + $ul;
echo $re;
}
*/
}
}
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
?>
</table>
<?php
echo "<br><br><label> Transport Price :</label><input type = text name=transport value=$as > <br>";
echo " <br><label> Grand Total : </label> <input type = text name=grandy id=grt value=$tr > ";
?>
<br >
<br >
<input type="button" name="proft" onclick="calcu();" value="Profit" />
<input type ="text" name="grandy" id="ui" />
I see you already have a variable $i that you're incrementing on every row, you can use that to make the IDs unique:
echo "<td><input type=text name=costprice id=costprice$i onkeyup=sell(); class=price value=$e /></td>";
echo "<td><input type=text name=quantity[] class=quantity id=quant$i value=$f /></td> ";
echo "<td><input name=txt type=text class=txt value=$t readonly /></td> ";
echo "<td><input type=text name=sellprice id=sellprice$i /></td>" ;
Then change your Javascript to take a parameter that specifies the row:
function poffy(i)
{
var d=document.getElementById("ui").value;
var e=document.getElementById("grt").value;
var p=parseFloat(d-e);
var t=document.getElementById("noit").value;
var e=p/parseFloat(t);
for(var b=0;b<parseFloat(t);b++)
{
var c=document.getElementById("costprice"+i).value;
var y=new Array();
y[b]=c;
var f=document.getElementById("quant"+i).value;
var mk=new Array();
mk[b]=f;
var g=e/parseFloat(mk[b]);
var h=g + parseFloat(y[b]);
document.getElementById("sellprice"+i).value=h;
}
}
I don't see where in your HTML you call the poffy() function. You need to change that code to pass the row number as a parameter.
I noticed another problem in your code. You have the following at the bottom of the table:
echo "<label>Number Of Items : </label> <input type=text name=no size=6 id=noit value= $i> ";
echo " <label>Dealer Name :</label> <input type=text name=fetch id=fetc readonly />";
echo " <label>Purchase Date :</label> <input name=prdt type=text size=10 class=pur value=$pd readonly /> <br><br> ";
Everything in a <table> has to be inside <tr> and <td> or <th> elements. You either need to put those wrappers around this line, or move them out of the table.
I'm new to javascript that why i don't know how to get value using javascript.
Here is my PHP script
while($row = mysql_fetch_array($sql)){
echo "<div class='loop'>";
if($row['choice'] == 0){
echo "<p>First Choice</p>";
echo "<input type='hidden' id='hidden' value='0' />";
}
elseif($row['choice'] == 1){
echo "<p>Second Choice</p>";
echo "<input type='hidden' id='hidden' value='1' />";
}
else{
echo "<p><input type='radio' name='content_type' value='1' />This is A</p>
<p><input type='radio' name='content_type' value='2' />This is B</p>
<p><input type='radio' name='content_type' value='3' />This is C</p>";
//content_a
echo "<div id='content_a'>";
echo "<p>First Choice</p>";
echo "<input type='hidden' id='hidden' value='0' />";
echo "</div>";
//content_b
echo "<div id='content_b'>";
echo "<p>Second Choice</p>";
echo "<input type='hidden' id='hidden' value='1' />";
echo "</div>";
//content_c
echo "<div id='content_c'>";
echo "<p>Third Choice</p>";
echo "<input type='hidden' id='hidden' value='2' />";
echo "</div>";
}
echo "<a style='text-decoration: none; color: #000000;' class='alert'
href='#' onclick='return false;'>Alert</a>";
echo "</div>";
}
Javascript
//when click on alert button
$(".alert").bind('click', function(){
var type = $(this).parents('.loop').find("#hidden").val();
alert(type);
});
//when radio button change
$('input[name=content_type]').bind('change', function(){
var n = $(this).val();
switch(n)
{
case '1':
$(this).parents('.loop').find('#content_a').show(1000);
$(this).parents('.loop').find('#content_b').hide(1000);
$(this).parents('.loop').find('#content_c').hide(1000);
break;
case '2':
$(this).parents('.loop').find('#content_b').show(1000);
$(this).parents('.loop').find('#content_a').hide(1000);
$(this).parents('.loop').find('#content_c').hide(1000);
break;
case '3':
$(this).parents('.loop').find('#content_c').show(1000);
$(this).parents('.loop').find('#content_a').hide(1000);
$(this).parents('.loop').find('#content_b').hide(1000);
break;
}
});
My javascript script above work only when choice == 0 and choice == 1 (when I click alert button with choice == 0, it will alert 0, and click alert button with choice == 1, it will alert 1). But if choice == 2, it didn't work at all, it alerts undefined. I want when choice == 3 and user choose the radio button, it will do like below:
- if user choose **This is A** and click Alert button, it will alert 0
- if user choose **This is B** and click Alert button, it will alert 1
- if user choose **This is C** and click Alert button, it will alert 2
Can you help me to solve this problem?
Thank in advance
You have logic for
if($row['choice'] == 0){
and
elseif($row['choice'] == 1){
but not in the same manner if the choice is 2.
You also have three inputs with id='hidden.' Is it possible that the following line is finding the wrong hidden element?
var type = $(this).parents('.loop').find("#hidden").val();
A live example in a site like jsfiddle.net would help us tinker more easily.
you are given same id's in the below code. id's need to given unique name.
echo "<div id='content_a'>";
echo "<p>First Choice</p>";
echo "<input type='hidden' id='hidden' value='0' />";
echo "</div>";
//content_b
echo "<div id='content_b'>";
echo "<p>Second Choice</p>";
echo "<input type='hidden' id='hidden' value='1' />";
echo "</div>";
//content_c
echo "<div id='content_c'>";
echo "<p>Third Choice</p>";
echo "<input type='hidden' id='hidden' value='2' />";
echo "</div>";