Loop through inputs and get checked value - javascript

I'm trying to get a list of radio inputs from a form that are grouped by their names, and they all have different names. I'm trying to create an array with them, if they are checked then append a 1 to the array, otherwise append a 0. None of the alert boxes pop up, so I assume that the function processDataForFinalization doesn't get called.
I didn't know if something was wrong with how I'm appending to the array. Or if it's a bigger error than that.
Thanks in advance.
EDIT4 Here is the updateBallot.php code
TwoResults.txt looks like:
0 0 0 0 0 0 0 0
3 4 1
<?php
$name = $_POST['name'];
$points = $_POST['points']; //array of user vote
echo $points;
$txt_file = file_get_contents($name.'Results.txt');
$rows = explode("\n", $txt_file); // rows-array separated by new line
foreach($rows as $row => $data)
{
$row_datas = explode(' ',$data);
}
$goods = $row_datas[0];
$goodies = $row_datas[1];
$newArr = [];
for($j=0;$j<count($points);$j++) {
$newArr[$j] = $goods[$j] + $points[$j];
}
$newText = "";
foreach($newArr as $nArr => $nData) {
$newText .= $nData." ";
}
$newText .= "\n";
$secondNewArr = [];
$sizeOfBottom = count($goodies);
for($k=0;$k<$sizeOfBottom;$k++) {
$secondNewArr[$k] = $goodies[$k];
}
foreach($secondNewArr as $neArr => $neData) {
$newText .= $neData." ";
}
$myFile = fopen($txt_file,"w+");
fwrite($myFile, $newText);
fclose($myFile);
?>
EDIT3 Here is the output HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="20">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="Array">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
<input type="radio" name="input0" value="1">
a <br>
</div>
<script>
var numQs = 1;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
<input type="radio" name="input1" value="1">
a <br>
</div>
<script>
var numQs = 2;
</script>
<div id='ballotElement'><h4><u>q</u></h4>
<input type="radio" name="input2" value="1">
a <br>
</div>
<script>
var numQs = 3;
</script>
<br><br><br>
<div class="submit">
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</div>
</form>
EDIT2 Here is the HTML from the page.
<form action="submitElection.php" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>">
<input type="hidden" name="numQs" id="numQs">
<input type="hidden" name="arr" value="<?php echo $arr;?>">
<script>
var a = document.getElementById("numQs");
a.value = numQs;
</script>
<?php
if (file_exists($name.'.txt')) {
if($type==1) {
$inputType = "checkbox";
} else {
$inputType = "radio";
}
$txt_file = file_get_contents($name.'.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
$vals = 0;
foreach($rows as $row => $data)
{
$arrCount = 0; // number of elements in array
echo "<div id='ballotElement'>";
$row_data = explode('^',$data);
$info[$row]['questions'] = $row_data[0];
$info[$row]['answers'] = $row_data[1];
echo "<h4><u>".$info[$row]['questions'] . "</u></h4>";
//echo $info[$row]['answers'] . "<br>";
$lines = explode("~",$info[$row]['answers']);
foreach($lines as $line => $lData) {
$answers[$row][$line] = $lData;
if($answers[$row][$line] !== "") {
$arrCount++;
?>
<input type="<?php echo $inputType; ?>" name="input<?php echo $row; ?>" value="1">
<?php echo $answers[$row][$line]; ?>
<br>
<?php }
$vals++;
}
if($writeIn == "y") {
$arrCount++; ?>
<input type="text" name="writeIn<?php echo $row; ?>" placeholder="Write in">
<?php
}
echo "</div>";
array_push($arr, $arrCount);
?>
<script>
var numQs = <?php echo count($arr); ?>;
</script>
<?php
}
} else {
header('Location: error.php');
}
echo "<br><br><br>";
<input type="submit" value="Submit ballot" class="btn btn-primary btn-large" onclick="return confirmSubmit()">
</form>
EDIT getActualData() is called from getData()
Here is getData(), this function works, so I'm not sure why the getActualData() doesn't work since they are basically the same thing.
function getData() {
var parts = 0;
for(var i=0; i<numQs; i++){
var checked = false;
var inp = document.getElementsByName('input'+i);
for(var j=0; j<inp.length && checked == false; j++){
if(inp[j].checked) {
checked = true;
parts++;
}
}
}
if(parts != numQs){
window.alert('Please vote for at least one candidate per race.');
return false;
} else {
window.alert('Okay');
getActualData();
//return true;
}
}
function processDataForFinalization() {
$.ajax({
url: 'updateBallot.php',
type: 'post',
data: {"points" : val, "name":name},
success: function(data) {
// Do something with data that came back.
window.alert(data);
//return true;
}
});
}
var val = [];
function getActualData() {
for(var k=0;k<numQs;k++) {
var inpu = document.getElementsByName('input'+k);
for(var jk=0;jk<inpu.length;jk++) {
window.alert('almost there');
if(inpu[jk].checked) {
window.alert('hello');
val.array_push(1);
window.alert(val.length);
} else {
val.array_push(0);
}
}
}
processDataForFinalization();
}

Related

How can I prevent the second forms submit button from removing data from the first form while using the the window.history.pushState function?

I was advised to use the windows.history.pushState function in order to be able to sustain the information the user enters into the text boxes and be able to use the browser's reload this page button if they elected to do so, this function works just fine with just one form, but I've added a second form and the submit button on the second form removes the data from the first form once the user presses it.
<?php
function getDistance($addressFrom, $addressTo, $unit){
//Change address format
$formattedAddrFrom = str_replace(' ','+',$addressFrom);
$formattedAddrTo = str_replace(' ','+',$addressTo);
//Send request and receive json data
$geocodeFrom = file_get_contents('http://maps.google.com/maps/api/geocode/json?
address='.$formattedAddrFrom.'&sensor=false');
$outputFrom = json_decode($geocodeFrom);
$geocodeTo = file_get_contents('http://maps.google.com/maps/api/geocode/json?
address='.$formattedAddrTo.'&sensor=false');
$outputTo = json_decode($geocodeTo);
//Get latitude and longitude from geo data
$latitudeFrom = $outputFrom->results[0]->geometry->location->lat;
$longitudeFrom = $outputFrom->results[0]->geometry->location->lng;
$latitudeTo = $outputTo->results[0]->geometry->location->lat;
$longitudeTo = $outputTo->results[0]->geometry->location->lng;
//Calculate distance from latitude and longitude
$theta = $longitudeFrom - $longitudeTo;
$dist = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +
cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) *
cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.8515;
$unit = strtoupper($unit);
if ($unit == "K") {
return round($miles * 1.609344, PHP_ROUND_HALF_UP).' km';
}
else if ($unit == "N") {
return round($miles * 0.8677, PHP_ROUND_HALF_UP).'';
}
else {
return round ($miles).'';
}
}
$distanceTotal = null;
$addressFrom = null;
$addressTo = null;
if(!empty($_GET['addrFrom'])) {
$addressFrom = $_GET['addrFrom'];
}
if(!empty($_GET['addrTo'])) {
$addressTo = $_GET['addrTo'];
}
if(!empty($_GET['distanceTotal'])) {
$distanceTotal = $_GET['distanceTotal'];
}
if (!empty($_GET['addrFrom']) && !empty($_GET['addrTo'])) {
$distanceTotal = getDistance($addressFrom, $addressTo, "N");
$distanceTotal = sprintf('%0.2f',round($distanceTotal,2));
}
$success = false;
?>
<?php
$selected='';
function get_options($select){
$rate=array('Economic Rate'=>3.00,'Standard Rate'=>4.00,'Express
Rate'=>5.00,'Quantumtheory'=>6.00);
$option='3.00';
foreach ($rate as $key_rate => $value_rate){
if($select==$value_rate){
$option.='<option value="'.$value_rate.'"selected>'.$key_rate.'</option>';
}
else{
$option.='<option value="'.$value_rate.'">'.$key_rate.'</option>';
}
}
return $option;
}
if(isset($_POST['rate'])){
$selected=number_format((float)$_POST ['rate'], 2,'.','');
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<div align="center">
<script>
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", "<?php echo
$_SERVER['PHP_SELF']; ?>");
}
</script>
<form method="get" name"lion" id"blue" >
<p class="distanceTotal">
<div id="d">
<p><b>Adress From<b>
<input type="text" name="addrFrom" id"fred" value="<?php echo $addressFrom;
?>" />
</p>
<p><label>Adress To</label><b>
<input type="text" name="addrTo" id="chris" value="<?php echo $addressTo; ?
>" />
</p>
<label>Total Miles<label><b>
<input type="text" id="distanceTotal" name="distanceTotal" value="<?php echo
$distanceTotal; ?>" >
<p>
<input type="submit" name="calc_1" value="Calculate Distance" />
</p>
</div>
</p>
</form>
<form method="POST" name"tiger" id="black" />
<p>
<div>
<select name="rate">
<option value="<?php echo get_options($selected); ?>" /></option>
</select>
<input type='submit' id='submit_2' name="calc_2" value='Submit' />
<input type="text" id="rateTotal" name="rat" width="110px" value="<?php echo
$selected; ?>" /><b><b><label>Per Mile</label>
</div>
</p>
</form>
</div>
</body>
</html>

Show second Submit button after clicking first Submit with form submit - Javascript

I've build a function in javascript to show me a second submit but only after the first submit was clicked.
Edited - this is ex.php:
<form method="post" action = "ex.php">
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
inputSubmit = document.getElementById("submit");
function myFunction(){
inputSubmit.style.display = "block"; };
</script>
Updated:
I've edited in order to conclude the main problem.
So what I want is this:
a) The user has pressed the first submit button "search" then it will echo on the page "first search" and then show the second submit button "search_close" .
b)Then, if the user has pressed the second submit button it will show "second search".
When first Refreshing:
======
search (button)
======
if clicking the "search" button:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
if clicking the "find close results:
======
search (button)
======
first search (text)
==================
Find close results (button)
==================
second search (text)
This code doesn't do what I want. Why?
Updated - why the button find close results disappers after one second?
<?php
session_start();
$db=mysqli_connect("localhost","root","","travelersdb");
if(#$_SESSION["username"]){
?>
<?php
// function to connect and execute the query
function filterTable($query)
{
$connect=mysqli_connect("localhost","root","","travelersdb");
$filter_Result = mysqli_query($connect, $query) or die(mysqli_error($connect));
return $filter_Result;
}
$submit_value = 0;
if(isset($_POST['search']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$Age= $_POST['Age'];
$email = $_POST['email'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($Age)) {
$query.="AND age='$Age'";
}
if(!empty($email)) {
$query.=" AND email='$email'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 1;
}
///Make The search more wider, only for the fields that were in the post
else if(isset($_POST['search_close']))
{
$Destination = $_POST['Destination'];
$TypeOfTravel = $_POST['TypeOfTravel'];
$topic_name = $_POST['topic_name'];
$StartingPoint = $_POST['StartingPoint'];
// search in all table columns
$query = "SELECT * FROM `topics`
left join `users` on users.username = topics.topic_creator
WHERE 1=1 ";
if(!empty($Destination)) {
$query.="AND destination='$Destination'";
}
if(!empty($TypeOfTravel)) {
$query.=" AND typeTravel='$TypeOfTravel'";
}
if(!empty($topic_name)) {
$query.=" AND topic_name='$topic_name'";
}
if(!empty($StartingPoint)) {
$query.=" AND StartingPoint='$StartingPoint'";
}
$search_result = filterTable($query);
$submit_value = 2;
}
else {
$query = "SELECT * FROM `topics`";
$search_result = filterTable($query);
}
?>
<html>
<head>
<?php header('Content-Type: text/html; charset=utf-8'); ?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Home Page</title>
<style>
.hidden {
display: none;
}
</style>
<script type="text/javascript">
function showHide()
{
var checkbox = document.getElementById("chk");
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i=0; i != hiddeninputs.length; i++) {
if(checkbox.checked){
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
myFunction();
inputSubmit = document.getElementById("submit");
function myFunction(){
document.getElementById('submit').style.display = "block";
};
<?php } ?>
</script>
<body>
</body>
</head>
<?php include("header.php");?>
<center>
</br>
<button>Post</button>
</br>
<br/>
<h4>Simple Serach</h4>
<form action="" method="post">
<input type="text" name="Destination" placeholder="Destination" value=
"<?php if(isset($_POST['Destination']))
{echo htmlentities($_POST['Destination']);}?>" ></br>
<input type="text" name="TypeOfTravel" placeholder="Type Of Travel"
value=
"<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['TypeOfTravel']);}?>"
></br>
<input type="text" name="Age" placeholder="Age" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['Age']);}?>">
</br>
</br>
<!-- Advanced Search-->
<input type="checkbox" name="chkbox" id="chk" onclick="showHide()" />
<label for="chk"><b>Advanced search</b></label>
</br>
<input type ="text" name="email" placeholder="Email" class="hidden" value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['email']);}?>">
<input type ="text" name="topic_name" placeholder="topic name" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['topic_name']);}?>">
<input type="text" name="StartingPoint" placeholder="Starting Point" class="hidden"value="<?php if(isset($_POST['TypeOfTravel']))
{echo htmlentities($_POST['StartingPoint']);}?>">
</br><br/>
<input type="submit" id="button" name="search" value="Search"
onclick="myFunction();" >
<br><br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<br/>
<?php echo '<table border="1px">';?>
<td width="400px;" style="text-align:center;">
Name
</td>
<td width="400px;" style="text-align:center;">
Destination
</td>
<td width="400px;" style="text-align:center;">
Type Of Travel:
</td>
<td width="80px;" style="text-align: center;">
First Name
</td>
<td width="80px;" style="text-align: center;">
Age
</td>
<td width="400px;" style="text-align:center;">
profile picture
</td>
<td width="80px;" style="text-align: center;">
Creator
</td>
<td width="80px;" style="text-align: center;">
Date
</td>
</tr>
</center>
<?php
$sql = "Select * from `topics`";
$check = mysqli_query($db,$sql);
$rows = mysqli_num_rows($search_result);
if($rows != 0){
while ($row = mysqli_fetch_assoc($search_result)){
$id = $row['topic_id'];
echo "<tr>";
//echo "<td>".$row['topic_id']."</td>";
echo "<td style='text-align:center;'><a href='topic.php?id=$id'>".$row['topic_name']."</a></td>";
echo "<td>".$row['Destination']."</td>";
echo "<td>".$row['typeTravel']."</td>";
$sql_u = "Select * from users where username='".$row['topic_creator']."'";
$check_u = mysqli_query($db,$sql_u);
while ($row_u = mysqli_fetch_assoc($check_u))
{
$user_id = $row_u['id'];
$profile_pic = $row_u['profile_pic'];
$firstname = $row_u['firstname'];
$age = $row_u['age'];
echo "<td>".$firstname."</td>";
echo "<td>".$age."</td>";
echo "<td><img src='".$profile_pic."' width='10%' height='10%' alt='me'></td>";
echo "<td><a href='profile.php?id=$user_id'>".$row['topic_creator']."</a></td>";
}
$get_date = $row['date'];
echo "<td>".$row['date']."</td>";
echo "</tr>";
}
}else {
echo "No topics found";
}
echo "</table>";
if (#$_GET['action']=="logout")
{
session_destroy();
header('location:login.php');
}
}else
{
echo "You must be logged in.";
echo "<a href ='login.php'>Click here to login</a>";
}
?>
</br>
</br>
<body>
</body>
</html>
you need to set type button cause when you set type submit then form automatically submit so show second not show but it work.
<form method="post" action = "">
<input type="submit" id="button" name="search" value="Search" >
<br>
<input type="submit" name="search_close" id="submit" style="display:
none;" value="Find close results">
</form>
<?php
$submit_value = 0;
if(isset($_POST['search']))
{
echo "first search";
$submit_value = 1;
}
else if(isset($_POST['search_close']))
{
echo "first search";
echo '<br>';
echo "second search";
$submit_value = 2;
}
else {
echo "nothing";
}
?>
<script type="text/javascript">
<?php
if($submit_value == 1 || $submit_value == 2){ ?>
document.getElementById('submit').style.display = "block";
<?php } ?>
</script>
check this code
I have cleaned up your code, but the issue of having two submit buttons still persists. Even if the clicking of the first button causes the second to show, the first button will cause the page to reload with the results from the form's action resource. In this example, I have cancelled the form's submit event to show that the display of the second button works.
In the end, I think you are going about this all wrong. I think you should be making AJAX calls to your server-side resource and injecting the results of that call into your page - - no forms and no submits.
// Don't forget to add "var" to your variable declarations, otherwise the variables
// become global!
var sub1 = document.getElementById("btnSub1");
var sub2 = document.getElementById("btnSub2");
// Set up the event handler for the first button
sub1.addEventListener("click", myFunction);
function myFunction(e){
// Adjust classes, not individual styles
sub2.classList.remove("hidden");
// Cancel the native event and stop bubbling
e.preventDefault();
e.stopPropagation();
};
.hidden { display:none; }
<form>
<!-- Submit buttons don't get a name attriute unless you expect their value to be submitted
along with all the other form data. Inline styles should be avoided and internal style
sheets used instead. And, inline JavaScript event attributes (onclick, etc.) should not
be used. -->
<input type="submit" id="btnSub1" name="search" value="Search" >
<br>
<input type="submit" id="btnSub2" class="hidden" value="Find close results">
</form>
<?php
if(isset($_POST['search']))
{
echo "first search";
}
else if(isset($_POST['search_close']))
{
echo "second search";
}
else {
echo "nothing";
}
?>

how to make a update in MySQL using checkbox

I would like to know how a multiple update in MySQL with checkbox because I'm not getting the id attribute checkbox someone could help me?
HTML code
<form method="post" action="../sys/fav.php">
<input type="hidden" id="id_photo" name="id" value="">
<div class="col-md-12">
<p align="right"><button class="btn btn-primary" id="final" name="final">Send</button></p>
</div>
<?php
require "../sys/connect.php";
$email = $_GET['email'];
$sql = mysqli_query($mysqli, "SELECT * FROM gallery WHERE email ='$email'");
while($row = mysqli_fetch_array($sql)){
$id = $row['id'];
$name = $row['nome_galeria'];
$emailcontact = $row['email_contact'];
$pass = $row['pass'];
$email = $row['email'];
$img = $row['img'];
print"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12\">
<input type=\"hidden\" name=\"contact\" value=\"$emailcontact\">
<input type=\"hidden\" name=\"login\" value=\"$email\">
<input type=\"hidden\" name=\"pass\" value=\"$pass\">
<input type=\"hidden\" name=\"name\" value=\"$name\">
<div class=\"hovereffect\">
<img id=\"he\" class=\"img-responsive\" src=\"../images/images/gallery/big/$img\" alt=\"$name\">
<div class=\"overlay\">
<div class=\"btn-group\" data-toggle=\"buttons\">
<label class=\"btn btn-primary cke\">
<input type=\"checkbox\" name=\"ck[]\" class=\"ck\" value=\"not\" id=\"ck_$id\"><i class=\"fa fa-heart\"></i>
</label>
</div>
</div>
</div>
</div>";
}
mysqli_close($mysqli)
?>
</form>
PHP Code
require "conexao.php";
if(isset($_POST['final'])){
$id = $_POST['id'];
foreach($_POST['ck'] as $ck){
$check = $ck;
$sql = mysqli_query($mysqli,"UPDATE gallery SET fav = '$check' WHERE id = '$id'")or die(mysqli_error($mysqli));
}
if($sql)
echo "Success!";
else
echo "Fail!";
}
Code Js to get the id of the checkbox
$("#final").click(function(){
var str = "";
var boxes = $(".ck");
for(var i = 0; i< boxes.length; i++){
if(boxes[i].checked == true){
var tmp = boxes[i].id.split("_");
str+=(i ? "," : "")+tmp[1];
}
}
document.getElementById('id_fotos').value=str;
});
You can get values of checkbox using below code and pass through ajax
var ckArray = new Array();
$.each($('input[name="ck[]"]:checked'),
function(index, ele){
ckArray.push($(ele).val());
});

Somehow my XMLHttpRequest not calling saveChat.php but just refresing the form onSubmit

The XMLHttpRequest function part that isn't working:
function save() {
//the data from the form
chat_message = document.getElementById("chat_message").value;
var from_id = document.getElementById("from_id").value;
var to_id = document.getElementById("to_id").value;
//the data string
var postdata = 'chat_message='+ chat_message + '&from_id=' + from_id +'&to_id=' + to_id;
xmlhttp.open("POST","saveChat.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", postdata.length);
xmlhttp.send(postdata);
}
The saveChat.php file that should receive the data and insert to database:
<?php
#session_start(); //start a session for to_id
include 'dbconnect.php';
$chat = strip_tags($_POST['chat']); //messages
$from_id = $_POST['from_id'];
$to_id = $_POST['to_id'];
$timei = $_SESSION['time']; //time postes
$datei = date("Y-m-d"); //date posted
$nowId = 0; //now id
$chatId = ''; //chat id
//insert into ocmment box
$chat_user = $db_con->prepare("insert into chat_message(chat_id,message,from_id,to_id,now_id,date,time)
values(:chatId,:chat,:from_id,:to_id,:now_id,:datei,:timei)");
$chat_user->execute(array('chatId' => $chatId, 'chat' => $chat,'from_id' => $from_id, 'to_id' => $to_id, 'now_id' => $nowId,
'datei' => $datei, 'timei' => $timei));
//execute the comment
?>
The HTML form that suppose to get it message inserted:
<form name="inclusion" method="post" onSubmit="javascript: save();document.inclusion.action.focus();return false;">
<div class="input-group">
<input type="hidden" name="from_id" id="from_id" value="<?php echo $_SESSION['user']; ?>" />
<input type="hidden" name="to_id" id="to_id" value="<?php if(isset($_REQUEST['ChatId']))
echo $_REQUEST['ChatId']; else { $to_id = $db_con->prepare("select from_id from chat_message where to_id =".$_SESSION['user']); $to_id->execute(); $rowTOID = $to_id->fetch(); echo $rowTOID['from_id']; } ?>" />
<input type="text" name="chat_message" id="chat_message" placeholder="Type Message ..." class="form-control" size="50"/>
<span class="input-group-btn">
<input type="submit" value="Send" name="submit" class="btn btn-warning btn-flat"/>
</span>
</div>
</form>

Concatenate variable into radio button selector

I am trying to find the value of a checked radio button. I am concatenating the variable 'flagName' into the input selector, and it keeps returning undefined. Here is my JQuery:
function filterProjects (searchInput) {
var filter = $(searchInput).val(), count = 0;
var $projects = $(".ProjectDisplay");
$projects.show();
$projects.each(function () {
var $currentProject = $(this);
var projectFlags = $(this).data();
for (var flagName in projectFlags) {
var flagValue = projectFlags[flagName];
var checkedInputValue = $("input[name='" + flagName + "']:checked", "#flagSearchForm").val();
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
}
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
});
}
I am trying to find the value of checkedInputValue. flagName and flagValue both return what they are supposed to. In the HTML, I have a form that loops through a PHP array to create multiple fieldsets that have three radio buttons each. Here is part of my HTML where the form is:
<form id="flagSearchForm" name="flagForm">
<div class="grid-unit grid-unit-9-14">
<h4>Search by Flag Value</h4>
<div class="flagSearch">
<div class="wrapper grids">
<?php
$flag_names = array("hasBib", "hasChoice", "hasEbooks", "hasFrbr", "hasLcd","hasLtp", "hasNlm", "hasPeers", "includeDewey", "includeGovtDocs", "includeNonBooks", "includeOpacUrl", "includeProtection", "includeScores"); ?>
<?php foreach ($flag_names as $i=>$flag_name):
?>
<div class="flagfields">
<div class="grid-unit grid-unit-3-14">
<fieldset>
<span class="flagName"><?php echo $flag_name; ?></span>
<input type="button" value="N/A" class="tri-state ignore" id="<?php echo $flag_name; ?>"/>
<input type="radio" name="<?php echo $flag_name; ?>" value="ignore" id="<?php echo $flag_name; ?>-ignore" class="radio-button" checked><label for="<?php echo $flag_name; ?>-ignore">Ignore</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="yes" id="<?php echo $flag_name; ?>-yes" class="radio-button"><label for="<?php echo $flag_name; ?>-yes">Yes</label>
<input type="radio" name="<?php echo $flag_name; ?>" value="no" id="<?php echo $flag_name; ?>-no" class="radio-button"><label for="<?php echo $flag_name; ?>-no">No</label>
</fieldset>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<input type="submit" value="submit" class="flagSearchSubmit">
</div>
Is my syntax for checkedInputValue wrong?
I'm not sure what your filter/regex was so that will need to be completed. This logs all the selected inputs.
Here is a fiddle: https://jsfiddle.net/c4qbywrt/7/
function filterProjects(searchInput) {
$('input:radio').each(function () {
if ($(this).is(':checked')) {
var $currentProject = $(this);
var checkedInputValue = $(this).val();
var flagValue = '0'; // Not sure what is setting this
if ((checkedInputValue == "yes" && flagValue == "0") || (checkedInputValue == "no" && flagValue == "1")) {
$currentProject.hide();
}
var filter = '';
if ($(this).find(".projectName").text().search(new RegExp(filter, "i")) < 0) {
$(this).hide();
}
}
});
}
$("#searchProjects").keyup(function () {
filterProjects($(this));
});
$("#flagSearchForm").submit(function (event) {
event.preventDefault();
filterProjects($("#searchProjects"));
});

Categories