manipulate dynamic input with php mysql and js - javascript

I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.

Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>

hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>

add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>

I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced

Related

How to sent id from one page to another when click on submit?

I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.
$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);
<html>
<head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="row">
<div class="col-md-6">
<?
while( $row2 = mysqli_fetch_array($fetch2))
{
?>
<form method="post" class="poll_form">
<h3><?echo $row2['question']?>?</h3>
<br />
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?></h4></label>
</div>
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?></h4></label>
</div>
<br />
<?php
if( $count >0)
{ ?>
<button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<h>You selected : <? echo $row1['vote_option']; ?></h>
<br>
<p id="demo"></p>
<?php
}
else
{ ?>
<button alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<?
}
?>
</form>
<? }
} ?>
<br />
</div>
</div>
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(".poll_form").submit(function(event){
event.preventDefault(); //prevents the form from submitting normally
var poll_option = '';
$('button.poll_option').each(function(){
if($(this).prop("checked"))
{
poll_option = $(this).val();
var option=poll_option;
}
var url = '<?php echo SITE_URL; ?>';
});
$.post("poll_vote.php",$('.poll_form').serialize(),
function(data)
{
if(data=="User Created Success"){
window.setTimeout(function () {
location.href ="<?php echo SITE_URL; ?>poll.php";
}, 100);
}
else{
$("#result").html(data);
}
}
);
//to reset form data
});
});
<? } ?>
</script>
</html>
Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also
Create a hidden input filed in your form
<input type="hidden" name="question_id" value="<?php echo $row2['question_id']; ?>">
Create a hidden input field in your form.
<input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">
PHP solution:
In this case your question_id will be included in the POST.
You can then access it by calling $_POST['question_id'].
Jquery solution:
In Jquery you can also access it by:
$("#question_id").val();

JavaScript show a input type file on anchor click

My code is as follows:
<div class="fifty">
<label>Credit report</label>
<input type="hidden" id="credtireport-link" name="credtireport-link" value="<?php echo $creditreport; ?>">
<input type="file" name="creditreport" id="creditreport" <?php if($creditreport!=""){?> style="display:none" <?php } ?> >
<?php if($creditreport!="") { ?>
Edit File
<?php } ?>
</div>
<div class="fifty">
<label>Employer’s ref</label>
<input type="hidden" id="employerref-link" name="employerref-link" value="<?php echo $employeer_ref_url; ?>">
<input type="file" name="employerref" id="employerref" <?php if($employeer_ref_url!=""){?> style="display:none" <?php } ?>>
<?php if($employeer_ref_url=="") { ?>
Edit File
<?php } ?>
</div>
I want to write a function in JavaScript which is called on edit file anchor click and will show the respective input type file.
Explanation: if some one clicked on anchor of credit report then it should show only <input type="file" name="creditreport" id="creditreport">.
My JavaScript code:
function showfile()
{
var id=$(this).parent().find('input[type="file"]').toggle();
return false;
}
html
Edit File
javascript
function showfile(el) {
var id = $(el).prev(":file").toggle();
return false;
}
plnkr http://plnkr.co/edit/MjZkZvFjlqj4a8HffYaF?p=preview

Enabled and disabled checkbox using javascript

This is my checkbox and text box:
<td> <input type ="checkbox" id="haha" onclick="enable('<?php echo $agenda->id; ?>')" value=<?php echo $agenda->id; ?>>
<td> <input type="text" name="dnama" id="nama_<?php echo $agenda->id; ?>" value="<?php echo $agenda->nama; ?>" disabled /> </td>
<td> <input type="text" name="dketer" id="ket_<?php echo $agenda->id; ?>" value="<?php echo $agenda->keterangan; ?>" disabled> </td>
and here's my javascript:
function enable(id) {
var disabled = !document.getElementById('haha').checked;
document.getElementById("nama_"+id).disabled = disabled;
document.getElementById("ket_"+id).disabled = disabled; }
my question is why this is only works on first row, i checked first checkbox the textbox will be enabled and then i unchecked first checkbox and checked 2nd and others that textbox still disabled.. how can i fix this?
You could use just one function:
function toggle(someId) {
document.getElementById(someId).disabled = !document.getElementById(someId).disabled;
}
You want the following:
function testEna() {
var dis = this.checked;
document.getElementById("nama"+this.id).disabled=dis;
document.getElementById("ket"+this.id).disabled=dis;
}
window.onload=function() {
var ena = document.querySelectorAll(".enabler");
for (var i=0;i<ena.length;i++) {
ena[i].onclick=testEna;
ena[i].onclick(); // run now too
}
}
using
<input type="checkbox" class="enabler" id="<?php echo $agenda->id; ?>" />
<input type="text" name="dnama" id="nama_<?php echo $agenda->id; ?>" value="<?php echo $agenda->nama; ?>"/>
<input type="text" name="dketer" id="ket_<?php echo $agenda->id; ?>" value="<?php echo $agenda->keterangan; ?>"/>
I don't know your ID's but the disable and enable checkbox code is like this :
function enable() {
document.getElementById("some_id").disabled= false;
}
function disable() {
document.getElementById("some_id").disabled= true;
}
try this..
function EnableDisable(id) {
document.getElementById("nama_"+id).disabled =false;
document.getElementById("ket_"+id).disabled = false;
var disabled = !document.getElementById('haha').checked;
document.getElementById("nama_"+id).disabled = disabled;
document.getElementById("ket_"+id).disabled = disabled; }
I don't know you question exactly, But it's good to use jQuery for this. I have try something with this. See below jsfiddel link
jsfiddle.net/ravipateldhg/5c7rdt0a
As you said you are using same id twice .With out changing id u can use this. But u should update the parament i.e Rather than passing id you should pass this object
function enable(pobj) {
var id = pobj.value;
var disabled = !pobj.checked;
document.getElementById("nama_"+id).disabled = disabled;
document.getElementById("ket_"+id).disabled = disabled;
}
Preferably usage of same id is not recommended.
For reference you can check https://jsfiddle.net/uw5f001q/3/

How to check if a radio button is clicked?

My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.

Pass form variables to php. Prevent page refresh

I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"

Categories