Serialized Radio Button | Do not submit, if radio button is not selected - javascript

Below is my code, which serializes the list of radio button, these radio buttons are generated by PHP, and then it is printed on the client side using javascript.
What I need is,
after I choose all the radio buttons, and when i click on Submit button, I want it to "check if all the radio buttons are selected in the form", if even a single/multiple radio buttons are not selected in the form, then i need a RED colour Star (mandatory symbol) next to each Not selected radio button
Then pass to another PHP which will save to DB. (this is working)
PHP:
$mysqli=mysqli_connect('localhost','Uid','Pass','DB');
$standard1 = mysqli_real_escape_string($mysqli,trim($_POST["tclass"]));
$section1 = mysqli_real_escape_string($mysqli,trim($_POST["tsection"]));
$SchoolID1 = mysqli_real_escape_string($mysqli,trim($_POST["tschoolid"]));
$query3="SELECT * FROM euser_student WHERE StudCourse='$standard1' and SchoolID='$SchoolID1'and StudentSection='$section1' order by StudentFirstName ASC";
$res3=mysqli_query($mysqli, $query3);
echo '<table border="1">';
for($i=0; $row=mysqli_fetch_assoc($res3); $i++) {
$dat3 = $row['StudentFirstName'];
$dat4 = $row['StudentRegID'];
// data to ajax to display data in a div
// we put the student's name in a hidden input
echo "<tr>
<td>" . $dat3 . " <input type='hidden' name='student[" . $i . "]' value='" . $dat3 . "'><input type='hidden' name='Reg[" . $i . "]' value='" . $dat4 . "'><input type='hidden' name='schoolid[" . $i . "]' value='" . $SchoolID1 . "'></td>
<td><input name='present[" . $i . "]' type='radio' value='Present'>Present</td>
<td><input name='present[" . $i . "]' type='radio' value='Absent'>Absent</td>
<td><input name='present[" . $i . "]' type='radio' value='Leave'>Leave</td>
</tr>";
}
echo '</table>';
Javascript:
$(document).ready(function() {
// radio buttons and input type Hidden data
$('#myForm').submit(function(e) {
e.preventDefault();
$.ajax({
url: 'save.php',
data: $(this).serialize(), // reads the data ...
success: function(data) {
alert("data Updated Successfully");
window.location = 'login.html';
});
});
});

You want something like jQuery validation plugin.
http://jqueryvalidation.org/
Checkout demo here
http://jqueryvalidation.org/files/demo/

Related

Checking radios in pagination

I have some radio buttons generated dynamically and are already paginated. Am checking to see if all are checked but this works only for the first page of pagination but fails to work for the next pages.
When i disable the pagination this works so it only checks for the radio buttons in the first page of the pagination but not all checkboxes how do i imlplement to check for all checkboxes regardless of which page they are in pagination
This is my code which works for first page of pagination
$("input:radio").change(function() {
var all_answered = true;
$("input:radio").each(function(){
var name = $(this).attr("name");
if($("input:radio[name="+name+"]:checked").length == 0)
{
all_answered = false;
}
});
if(all_answered==true ){
alert("all checked");
}else {
alert("not all checked");
}
});
This is my php code that generates the radios:
<?php
$n=1;
foreach ($checks as $m => $check) {
$radioyes ="";
$radiono ="";
$item ="";
$radioyes .= '<input type="radio" name="'. $m.'" class="selected one" value="'.$m.'" >';
$radiono .= '<input type="radio" name="'. $m .'" class="not_selected one" value="'.$m.'">';
echo "<tr id='" . $m . "'>";
echo "<td>" . $n . "</td>";
echo "<td>" . $item . "</td>";
echo "<td>".$radioyes."</td>";
echo "<td>".$radiono."</td>";
echo "<td>".$textinbox."</td>";
echo "</tr>";
$n++;
}
?>
I hve checked on This link but doesnt work.
You have to use '.on('change'...) for dynamically generated inputs
E.g :
$(document).on('change', 'input:radio', function() {
// Does some stuff
});

Is there a 'cleaner' way I can assign a MySQL value to a jQuery variable?

I am creating a basic auction site and having a slight issue where when a bid is placed, it sometimes says it's too low, despite it being higher than the current bid. I think this is to do with the way I am getting the current bid, as it's not a very tidy approach in my opinion.
So my HTML/PHP which retrieves and lists the auctions on the page:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction" . $row['ID'] . "'>
<input type='hidden' name='id' value='" . $row['ID'] . "' />
<div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £<div class='nospace' id='" . $row['ID'] . "'>" . $row['CurrentBid'] . "</div></div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname' autocomplete='off'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid' autocomplete='off'/></div>";
echo "<div class='auction-bid'><input type='submit' name='submit' value='Place Bid!' /></div>";
echo "<div class='bid-success' id='bid" . $row['ID'] . "'>Bid placed!</div>";
echo "</div></form>";
As you can see, I wrap the column/value "CurrentBid" in a div with the ID of the ID in MySQL.
Then when someone places a bid, the following jQuery/AJAX code is called:
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).find('input[name="bid"]').val();
var currentbid = $('#'+id).text();
var itemdesc = $(this).find('.auction-name').text();
if (bidname == '')
{
alert("No name!")
return false;
}
if (bid > currentbid)
{
alert("Bid is greater than current bid");
}
else
{
alert("Bid is too low!");
return false;
}
$.ajax({
type: "POST",
url: "auction-handler.php",
data: {bidname: bidname, bid: bid, id: id, itemdesc: itemdesc},
success: function(data){
$('#bid'+id).fadeIn('slow', function () {
$(this).delay(1500).fadeOut('slow');
});
}
});
return false;
});
});
As you can see from this code, I assign the variable 'currentbid' by selecting the ID of the div container, and then pulling through the text within it.
I am not sure if this is what is causing me the problem, but it seems likely, I cannot figure out why sometimes it says "Bid too low" despite me putting in a higher price then what is currently in the Current Bid div.
Ideally, I'd like to assign the jQuery variable 'currentbid' with the value directly from MySQL, but I am not too sure if this is possible.
Does anyone know of a way that I can do this? Or is there a better way I can assign a value to the variable?
Thank you
You are comparing strings now instead of numeric values. You should cast your values to floats before comparing.
bid = parseFloat(bid)
currentbid = parseFloat(currentbid);
Also on the server side when processing to bid you should first check the currentBid from the database because it could have changed already.

Alerting only 1st Product Code from table?

So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle

PHP - retrieving all the data corresponding to a radio button

I am using php and have less experience in it. I am displaying data in a table, which has a radio button at the start of each row. I want to retrieve all the data that is present in the row corresponding to the radio button I check.
Here is something what I have done till now:
<form name="test" method="POST">
<table>
<tr>
<th></th>
<th>book_id</th>
<th>card no</th>
<th>fname</th>
<th>lname</th>
</tr>
<?php
$conn = mysql_connect("localhost", "root", "");
if ($conn) {
mysql_select_db("library");
} else {
echo 'no such database';
}
$query_test = "select book_id2,a.card_no,fname,lname from book_loans a, borrower b where a.card_no = b.card_no ";
$result = mysql_query($query_test);
if ($result === FALSE) {
mysql_error();
} else {
while ($rows = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='test'></td>";
echo "<td>" .$rows['book_id2']. "</td>";
echo "<td>" .$rows['card_no']. "</td>";
echo "<td>" .$rows['fname']. "</td>";
echo "<td>" .$rows['lname']. "</td>";
echo "</tr>";
}
}
?>
<input type="submit" name="test_val" value="submit"/>
</table>
</form>
Here I want to print the data i.e. book_id, card_no, fname, lname as the submit button is clicked:
<?php
if($_POST)
{
if(isset($_POST['test_val']))
{
// TO PRINT THE DATA CORRESPONDING TO THE RADIO BUTTON
}
}
?>
Add hidden input fields in each of the <td> rows. For example:
echo "<td>".$rows['book_id2']."</td><input type='hidden' name ='book_id2' value='".$rows['book_id2']."' />";
I've tried writing the JavaScript but this is much easier in JQuery. Add these scripts before the end of the closing </body> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var toggleInput = function(){
$('input[type=hidden]').prop('disabled', true);
var selection = $('input:checked').eq(0);
selection.parent().parent().find('input[type=hidden]').each(function(){
$(this).prop('disabled',false);
});
}
$(form).on('submit',toggleInput);
</script>
JQuery is used a lot in manipulating the DOM like this. It cuts out a lot of the repetition that can be seen in JavaScript. Although if it is easier to do something with just JavaScript, then do it!
On form submission, we're disabling all hidden elements. Then we find the active radio box, and activate the hidden elements corresponding to the radio box.
This is one solution and might need to be tweaked. JavaScript and JQuery are your friends for this problem.
You could add the data as the value attribute of your radio button
echo "<input type='radio' name='test' value='".$rows['book_id2']." ".$rows['card_no']." ".$rows['fname']." ".$rows['lname']."'>";
Then the name of the post variable will be the name of the radio button
if(isset($_POST['test']))
{
echo $_POST['test'];
}
Another example, to access individual values:
echo "<input type='radio' name='test' value='".addslashes( json_encode($rows) )."'>";
if(isset($_POST['test']))
{
$result = json_decode( stripslashes($_POST['test']) ) ;
echo $result->book_id2;
echo $result->card_no;
echo $result->fname;
echo $result->lname;
}
Try implementing this:
Create a hidden textarea (which will be holding data corresponding to the radio button)
Assign a dynamic id (unique) to the <tr> and <td> and once the respective radio button is clicked, create JS function which will capture all the data w.r.t the row and if a new radio is clicked, it will clear out the old data and replaces it with new.
Submit the data and you can capture that required data.
Functions you wil require (Inbuilt and User Defined):
1 $( "#tr_unique td_unique" )[.text()][1]; // text() Since you are storing data in td else it would be val()
2 insertData(number){
// Here number is the row # through which you'll track corresponding data
}
3 $( "#hidden_textarea" )[.val][1]('data')
See, if that helps.

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Categories