Delete a div on a button click (changing id) - javascript

I'm generating div with class and id changing. They are all the same and each one has a delete button.
I want to delete the div in which the clicked button is. Each button as the id "delete_index" in a "past_experience_index" div. In fact, when i click on delete_2, i want past_experience_2 to be deleted.
I tried several things but it does not work...
Here is the PHP :
<div class="experiences_container">
<?php
if (!empty($experiences)) {
$index = 0;
foreach ($experiences as $key) {
?>
<div id="past_experience_<?=$index?>" class="past_experience">
<div class="experience_header">
<div>
<label for="team">Nom de l'équipe</label>
<input class="team" name="team_<?= $index ?>" value="<?= $key['team-name'];?>"/>
</div>
<div>
<label for="role">Rôle dans l'équipe</label>
<input class="role" name="role_<?= $index ?>" value="<?= $key['team-role'];?>"/>
</div>
</div>
<div class="experience_textarea">
<label for="description">Description du rôle</label>
<textarea class="description" name="description_<?= $index ?>"><?= $key['team-description']; ?></textarea>
<label for="palmares">Palmarés avec l'équipe</label>
<textarea class="palmares" name="palmares_<?= $index ?>"><?= $key['team-palmares']; ?></textarea>
</div>
<p id="delete_<?=$index?>" class="delete_button">supprimer</p>
</div>
<?php
$index++;
}
} else {
?>
<div><p>Vous n'avez encore rentré aucune expérience</p></div>
<?php
}?>
</div>
So as a JavaScript beginner, i tried a for() with the php index value limit but it doesn't work. The $("div").remove(past_experience_index) works, but i can't have the actual index.
Thanks a lot

Define an onclick function on button click pass $index as a function argument.
<p id="delete_<?=$index?>" class="delete_button" onclick="del_div_fun('<?php echo $index ?>')">supprimer</p>
Now you have to define this function in javascript like.
function del_div_fun(index_val){
var div_id = 'past_experience_'+index_val;
$('#'+div_id).remove();
}//end of function del_div_fun
Please use jquery library
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If your using jquery you don't really need to worry about ids. You can use jQuery to find the parent and remove it that way.
Something like this:
$(".delete-btn").click(function(){
$(this).parent().remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="padding:10%;background-color:lightgrey;text-align:center;">
<p style="cursor:pointer;" class="delete-btn">Delete</p>
</div>

Probably you don't need to duplicate indexes everywhere.
And you can avoid adding jquery into your page.
<script>
function deletePastExperience() {
var experiencesContainer = document.querySelector('.experiences_container');
var elementToRemove = document.getElementById(event.target.parentElement.id);
experiencesContainer.removeChild(elementToRemove);
}
</script>
<p onclick="deletePastExperience()" class="delete_button">supprimer</p>

Related

Getting input value that has its own iterated button upon click

I've successfully added an iterator to my php foreach loop so that I can create a unique button for each row in my table.
<?php $i = 1;?>
#foreach($getPromoCodes as $codes)
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
<?php $i++;?>
#endforeach
However, I can't figure out, once the button is pressed, how to get the value of the input from the clicked button. This being due to the uniqueness of each button with the iterator.
var promo_codet_id = document.getElementsByClassName("promo_code_id");
This returns undefined when I console log it.
How do I need to change my JS for this?
You can do this way:
<div class="elements">
<?php $i = 1;?>
<?php foreach($getPromoCodes as $codes): ?>
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}">
Link
<?php $i++;?>
<?php endforeach; ?>
</div>
jquery:
$('.elements').on('click', '.btn', function(e){
e.preventDefault();
console.log($(this).data('id'));
});
You can use this.value in a call to a javascript function:
<input type="hidden" name="promo_code_id" id="promo_code_id[{{$i}}]" class="promo_code_id" value="{{ $codes->promo_codet_id }}" onclick="doSomething(this.value); return false;">

Set the display of my table with radio button using radio buttons mvc

well I searched on every web site but I didn't find what I want so :
I will be easier for you, to see what I have :
my page ;)
So for each radio buttons, I want to set the display of my table.
Ex : if I pick "Alphabétique", the values sorted in alphabetical order.
I knew I needed to use Ajax, but I'm absolutely not comfortable with that. In addition to that, I am programming my project in MVC.
I made some research on Google, Stack, OpenClassroom, etc..
And I don't understand exactly what I need to do in Ajax or where I need to add the instructions.
So here is my code :
controllerBoutique.php (Controller):
<?php
require('../Views/codes/boutique.php');
require('../Models/vehicule.php');
$query = getVehiculesByAlpha();
require('../Views/codes/tabAffich.php');
?>
boutique.php : (View)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rentcar - Boutique</title>
<link rel="stylesheet" href="../Views/styles/style2.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
</head>
<body>
<?php require("menu.php");?>
<section id="section" class="main-section cleanbg">
<div class="container">
<label>Trier par :</label>
<div class="single-col">
<div class="styled-input-container">
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioAlpha" value="Alpha" checked="checked"/>
<label for="radioAlpha">Alphabétique</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioModel" value ="Model"/>
<label for="radioModel">Modèle</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioKm" value ="Km"/>
<label for="radioKm">Kilométrage</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioDispo" value ="Dispo"/>
<label for ="radioDispo"> Disponible </label>
</div>
</div>
</div>
</div>
<div class="search">
<label class="lblSearch"> Rechercher :</label>
<input type="text" id="search-box" class="search-box">
<button class="btnSearch">Chercher</button>
</div>
</section>
<section id="section" class="main-section cleanbg">
<div class="container">
<hr>
tabAffich.php : (view table)
<div class="wrapper">
<div class="table">
<div class="row header">
<div class = "cell">Marque</div>
<div class = "cell">Modèle</div>
<div class= "cell">Kilométrage</div>
</div>
<?php
while($res = $query->fetch()){
?>
<div class="row">
<div class ="cell">
<?php echo $res['nom'];?>
</div>
<div class="cell">
<?php echo $res['modele'];?>
</div>
<div class="cell">
<?php echo $res['km'];?>
</div>
</div>
<?php
}
$query->closeCursor();
?>
</div>
</div>
</div>
</section>
</body>
</html>
vehicule.php (Model):
<?php
function getVehiculesByAlpha(){
try{
$db = new PDO('mysql:host=localhost;dbname=ProjectRentcar;charset=utf8','root','root');
}catch(Exception $e){
die('Erreur : '.$e->getMessage());
}
$query = $db->query('
SELECT nom, modele, km
FROM Vehicule V, Marque Ma
WHERE V.numMarque = Ma.numMarque
ORDER BY nom, modele');
return $query;
}
function getVehiculesByModel(){
//Same code with order differently
}
function getVehiculesByKm(){
//Same here
}
So I would know how can I change the display of table when I click on a specific radio button, and some help in Ajax 😉
Thanks you in advance ❤️
you can achive this using only PHP but sure it would be better for UX to achive this with Ajax (for you too, you will learn more).
1) So first you need a javascript function that will trigger when you click on input[type=radio] and for example if you click on radio button with id == radioAlpha it will run a function using Ajax request to your vehicule.php?sort=alphabetique. If you click on radio button with id == radioModel it should run a function using Ajax request to your vehicule.php?sort=model - you can send data using POST or GET request with Ajax, how do you like.
2) You should then change your vehicule.php file, it should also contain something like this:
if ($_GET['sort'] == 'alphabetique') {
// run function with sort for alphabetique
// echo data with json format for example or even with html
}
if ($_GET['sort'] == 'models') {
// run function with sort for model
// echo data with json format for example or even with html
}
...
...
3) Yor file tabAffich.php
<?php
while($res = $query->fetch()){
?>
<div id="sorttable"> // Add this line
<div class="row">
<div class ="cell">
<?php echo $res['nom'];?>
</div>
<div class="cell">
<?php echo $res['modele'];?>
</div>
<div class="cell">
<?php echo $res['km'];?>
</div>
</div>
<?php
}
$query->closeCursor();
?>
</div>
Back to Ajax request, when it would be a successfull call with response you can generate new data in <div id="sorttable"> container. You need some knowledge of javascript how to clear data and generate a new from ajax response but its not very hard to learn.
I hope that will help you a little bit in understanding how you can use ajax in this situation.
There are really many ways to get the effect you want to achieve, and the one I've presented is quite simple, I think.

how to go to another page when clicking on each dynamically added submit button using jquery or javascript?

I have a form in which by using javascript and in a while I add content to it.
Denpending on the number of data in database different number of forms are added to the page.
<?php
while($row = mysql_fetch_array ($result)){
?>
<form method="post" accept-charset="UTF-8" >
//add some content to the form by reading from database
<div class="form-group ">
<input type="submit" name="print" id="button" value="print"/>
</div>
</form>
<?php
}//end while
?>
and below I want to redirect to another page when clicked on each "print" button.
But not only it doesn't redirect to another page but also alert just works for the first button.
Below is the code:
<script>
$("#button").click(function(){
alert('hi');
window.location.href = "design_card.php";
});
</script>
how to solve?
jquery, php or javascript solutions are acceptable. other workable solutions, if work, are good.
Thanks for your response in advance.
Check your HTML
<?php
while($row = mysql_fetch_array ($result)){
?>
<form method="post" accept-charset="UTF-8" >
//add some content to the form by reading from database
<div class="form-group ">
<input type="submit" name="print" id="button" value="print"/>
</div>
</form>
<?php
}//end while
?>
You have created multiple <input> element dynamically with duplicate id so the better way is to assign a class to them like
<?php
while($row = mysql_fetch_array ($result)){
?>
<form method="post" accept-charset="UTF-8" >
//add some content to the form by reading from database
<div class="form-group ">
<input type="submit" name="print" class="buttonClass" value="print"/>
</div>
</form>
<?php
}//end while
?>
And then use this buttonClass class as a jquery selector like this
$(".buttonClass").click(function(){
alert('hi');
window.location.href = "design_card.php";
});

how to write HTML tags with jQuery n json dynamically?

I need to write html code into the following div with jquery
<div id="addme"></div>
following is my html with php
<div class="col-md-4 product secondproduct">
<div class="images1">
<a
href=" <?php echo base_url();?>products/details/<?php echo $product->productid?>">
<img
src="<?php echo base_url();?>assets/images/products/<?php echo $product->productimage;?>" />
</a>
</div>
<div class="title1">
<?php echo $product->productname;?>
</div>
<div class="price1">
Rs. <?php echo $product->productprice;?>
</div>
<div class="productadd">
<form method="post" action="<?php echo base_url();?>cart/productadd">
<div class="qtyout">
QTY : <input type="text" class="qty" name="qty" value="1" />
</div>
<input type="hidden" name="item_number"
value="<?php echo $product->productid;?>" /> <input
type="hidden" name="price"
value="<?php echo $product->productprice;?>" /> <input type="hidden"
name="title" value="<?php echo $product->productname;?>" />
<button class="btn btn-primary btn-lg" type="submit">Add To Cart</button>
</form>
</div>
</div>
actually i want to populate these html & php with json & query. And kinda getting lots of error. main problem is, i don't know how to write these about of html tags inside jquery and loop through json data.
Thanks in advance
to add something in the addme div you do
$("#addme").html('insert content here');
or you can append something(keeps whats there and add stuff to the end):
$("#addme").append('insert content here');
for the json. Once you have a json string you do
var yourdata = JSON.parse(jsonstring)
Hope this helps a bit
Do Something like following:
var obj = $.parseJSON({"productid":"2","categoryid":"1","manufacturerid":"2","name":"Abraham Lincoln Printed T-Shirt","price":"1250.00","color":"red","description":"Print Name: Abraham Lincoln\r\n100% Cotton\r\nMade in Nepal\r\nRegular fit\r\nHalf sleeve","quantity":"20","otherdetails":"Available in all sizes.","isadvertised":"1","isnew":"1","image":"hazy-crazy-t-shirt.jpg","manuid"‌​:"2"}');
$(".image1").html(obj.image);
$(".color1").html(obj.color);
If you are getting data in json by ajax than you can simply append in html with the specific div, follow the code below:
Using ajax return :
var myAjaxreturn = "Your code which is to append";
<div id='addme'></div>
$('#addme').html(myAjaxreturn);
Jquery append() inserts content, specified by the parameter, to the end of each element in the set of matched elements.
var response = "your ajax response";
$( "#addme" ).append( response );
OR
$( "#addme" ).html( response );
Hope this helps. not tested

Calling a function when the page is loaded from a posted form

On my index.php page, I have a form which posts into a 3rd party newsletter system.
The page reloads index.php?mail&
Is there anyway I can do a check when the page is loaded AND that the form has been posted? If it has, that it can call another function?
Thanks Chris
The code:
So what I'm hoping for is a sort of onload feature which will detect if the form name="subscribe" has been posted. Then I call a function (which will be a popup div).
I can get there with a little help and can do a bit of php or javascript, maybe not program it but understand some of it. don't have a clue with ajax
mailbar8 (where the actual form is located for the newsletter):
<?php include("globals.php"); ?>
<form action="<?php echo $website.$relative_string;?>" name="subscribe" onsubmit="javascript:return checkEmail(this);" method="post">
<div id="cell8" class="titlecell2"><h3>Email:</h3></div>
<div id="cell9" class="inputcell2">
<input type="text" class="inputfield2" name="email" value="Your Email..." id="email2" maxlength="255" onfocus="this.value='';">
</div>
<div id="cell10" class="textcell3">
<input name="group" type="hidden" id="group[]" value="<?php echo $group; ?>">
<input name="subscribe" id="sub" type="radio" value="true" checked>
</span>Subscribe</p>
</div>
<div id="cell11" class="buttoncell">
<button type="submit" name="Submit2" value="Join" id="submitButton2" button" onClick="javascript:myFunction();"/>
<span>Join</span>
</button>
</div>
<div id="cell8" class="textcell4">
<input type="radio" name="subscribe" id="unsub" value="false">
</span>Un-Subscribe</p>
</div>
</form>
The form name is subscribe, it checks the email entry is legit and then if it is redirects the user back to: http://www.allcoles.com/index.php?page=mail&
The index.php (this bit of code displays the mailbar8.php form):
<div id="guestArea" class="siteAreas">
<div id="guestTitle" class="roundedTitle">Guests</div>
<div id="guestContent" class="roundedContent">
<h4>Get Our Newsletter!</h4>
<?php
$mailbar=8;
$group=1;
include("maillist/mailbar.php");
?>
</div>
</div>
<!-- End of User and Guest Areas -->
index.php (the popup div I want to load when the page is open and the form is posted, it has a js file but that's not important - the popup div currently works by a href link on www.allcoles.com):
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<h2 align="center">All Coles Newsletter System</h2>
<h3 align="center">bringing News, Birthdays, Events and Invites to your mailbox!</h3>
<hr align="center" width="75%">
<p style="text-align:center"> <?php
if(isset ($_GET['page']))
{
if ($_GET['page'] == "mail")
{
include("maillist/mailmain.php");
}
if ($_GET['page'] == "about")
{
include("about.php");
}
}else {
print("THIS PRINT IS WHERE THE NEWSLETTER SAYS THAT THE EMAIL HAS BEEN SUBSCRIBED TO THE DATABASE, THIS POPUP DIV IS A NICE WAY TO SHOW THAT. THIS BIT CHANGES IF THE USER IS ALREADY SUBSCRIBED, OR ADDED OR REMOVED");
}
?> </p2>
<hr align="center" width="75%">
<p style="text-align:center; font-size: 12px;">
<font style="text-decoration:underline; font-weight:bold;">TIP</font>
: Remember to check your Junk Mail, and add 'administrator#allcoles.com' to your
<font style="text-decoration:underline; font-weight:bold;">SafeSenders</font>
list.</p>
</div>
</div>
<div class="loader"></div>
<div id="backgroundPopup"></div>
So ideally - when (http://www.allcoles.com/index.php?page=mail&) loads it recognises the form named subscribe which has been submitted and then calls a function.
for example the function: formPosted();
The solution I came up with was (with the help from everyone):
<?php
if(isset ($_GET['page']))
{
if ($_GET['page'] == "mail")
{
echo "<script>window.alert('Found the reply!');var formPosted = true;</script>";
}
}
?>
<script>
if(formPosted) {
window.alert("popupclick!");
popupClick();
}
</script>
How about something simple like this?
<?php
if( /* check if form has been postet */ ) {
$form_posted = true;
} else {
$form_posted = false;
}
?>
and then...
<?php if($form_posted) : ?>
<script>
formPosted();
</script>
<? endif ?>
Using Ajax:
var mail = ???;
$.post( "index.php", { mail : mail }, function( data ) {
formPosted();
});
It's simple. It posts to the page you want with the parameter mail and then calls the function you want.
<?php
$dispatched = isset($_POST['dispatched']) ? 1 : 0;
if($dispatched) {
// handle data
echo "<script>var formPosted = true;</script>";
}
?>
<script>
if(formPosted) {
// do something
}
</script>

Categories

Resources