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.
Related
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
Okay so i have done alot of rewriting to eliminate loops that adds eventlisteners..
This link explains -> Handling Events for Many Elements
But this way will give me some problems... basically how do i add an eventListener to every edit label generated? (see php code)
I can do this by making a loop that adds an event listener to every label but aparently this is bad practice?
Right now my "parent" element is <div id="popUp"> this makes the popup appear when the whole code inside <div class="col100 pad10 flex editUsers"></div> is clicked not just the "edit label"...
And how could i dynamically add the correct form information if i want to loadup a form in the popup?
PHP LOOP
<div id="popUp">
<?php
$stmt = $dbCon->prepare(" SELECT id, username, level "
. " FROM bilbixen_login ");
$stmt->execute();
$stmt->bind_result($id, $username, $level);
while ($stmt->fetch()) {
?>
<div class="col100 pad10 flex editUsers">
<div class="col80">
<p>User : <?php echo $username; ?></p>
<p>Level : <?php echo $level; ?></p>
</div>
<form class="" action="#" method="POST">
<input class="" id="submitDelete<?php echo $id; ?>" type="radio" name="status" value="0">
<input class="" id="submitAccept<?php echo $id; ?>" type="radio" name="status" value="1">
<input type="hidden" value="<?php echo $id; ?>" name="userId">
<input id="submit<?php echo $id; ?>" type="submit" name="submit">
</form>
<div class="flex col20 space-b">
<label for="submitDelete<?php echo $id; ?>" class="pad10 bgcr pointer">Delete</label>
<label for="submitAccept<?php echo $id; ?>" class="pad10 bgcg pointer">Edit</label>
<label for="submit<?php echo $id; ?>" class="pad10 bgcb pointer">Submit</label>
</div>
</div>
<?php
}
$stmt->close();
?>
</div>
Javascript/Popup
<script>
var popUp = document.querySelector('#popUp');
var btn = document.getElementById('btn');
var close = document.getElementById('close');
popUp.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
overlay.style.display = 'block';
}
e.stopPropagation();
}
close.addEventListener('click', function () {
overlay.style.display = 'none';
});
window.addEventListener('click', function (event) {
if (event.target === overlay) {
overlay.style.display = "none";
}
;
});
</script>
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/
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
}
Jquery :
$('.question_title').click(function () {
var value = $('#question_id').val();
alert(value);
});
Friends in this code question_id will be carrying different values for the looping . Here I have writtern code to get the value according to the LOOPING on click of ahref class I would like to fetch the value of hidden value for example in the first iteration title is cow on click ahref it should alert 0 (question_id value). on click on 2nd title cat it should get alert 1 like on clicking 5 different title it should display 0-4 respectively but now onclick on different title it alerts only 0 not the other values . could any one suggest me how to achieve it .
Get the parent h2 and then next .question_id like following.
$('.question_title').click(function() {
var value = $(this).parent().next('.question_id').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Title 0</h2>
<input type="hidden" name="question_id" value="0" id="question_id" class="question_id">
<h2>Title 1</h2>
<input type="hidden" name="question_id" value="1" id="question_id" class="question_id">
BTW you are using same id question_id for multiple elements.
As 'id' is unique value, it will get only the first element.
Try this:
for($i=0;$i<5;i++)
{
<h2><?php echo $value['asked_title'];?> </h2>
}
Jquery :
$('.question_title').click(function()
{
alert(event.target.id);
});
For
<?php
for($i=0;$i<5;i++)
{
?>
<h2><?php echo $value['asked_title'];?> </h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
<?php } ?>
And in script use
$('.question_title').click(function() {
alert($(this).attr("data-tell"));
});
You are having the same id question_id in all five hidden fields.
you can have it like this..
for($i=0;$i<5;i++)
{
echo '<h2>'.$value['asked_title'].'</h2>';
}
jquery
$('.question_title').click(function()
{
var value = $(this).data('value');
alert(value);
});
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"