javascript - Remove form element dynamically - javascript

I have a form in my PHP with JavaScript code to add select elements dynamically, which is working nicely :
<tr><th>Requester</th><td><input type="hidden" name="requester" value="<?php echo $_SESSION['user_id']; ?>"><?php echo $_SESSION['user_descr']; ?></td></tr>
<tr>
<th>User(s) for whom you are requesting the access</th>
<td>
<div id="dynamicUsers">
<?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
echo '<select name="firecallUsers[]">';
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
echo '</select>';
?>
</div>
<input type="button" value="Add user" onClick="add_FC_User('dynamicUsers');">
</td>
</tr>
The JavaScript is :
var counter = 1;
var limit = 5;
function add_FC_User(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " users");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select name="firecallUsers[]"><?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
?></select>';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
But I would like to add a little "remove" button next to each added element, for example something like this in the javascript :
?></select> remove ';
How can I script this javascript function in order to remove the dynamically-added elements ?
I suppose I have to say something like (remove the child div created in parent div called dynamicUsers, but my child div doesn't have a name/id it seems)
any idea ?
thanks!
PS : I tried this solution 1 (doesn't work) :
I tried to do something like :
1.adding a name to the div in the javascript, e.g :
var newdiv = document.createElement('div'); newdiv.id = "userDiv";
2.creating a function like :
function remove_FC_User(divName){
var child = document.getElementById(userDiv);
var parent = document.getElementById(divName);
parent.removeChild(child);
}
3.creating the remove link in the JS with :
?></select> remove';
but it won't work :(

it's working nicely now with :
function randId() {
return Math.random().toString(36).substr(2, 10);
}
var counter = 1;
var limit = 15;
function add_FC_User(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " users");
}
else {
var newdiv = document.createElement('div');
var randstring = randId();
newdiv.setAttribute("id", randstring);
newdiv.innerHTML = '<select name="firecallUsers[]"><?php
$q_users = 'SELECT id,descr,tnumber FROM users ORDER BY descr;';
$prep = $dbh->prepare($q_users);
$prep->execute();
$arrAll = $prep->fetchAll();
foreach($arrAll as $data)
{
echo '<option value="'.$data['id'].'">'.$data['descr'].'</option>';
}
?></select> remove';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
thanks a lot for your hints/help !

mmh I managed to make it half-work with :
var newdiv = document.createElement('div');
newdiv.setAttribute("id", "one");
and
?></select> remove';
and
function remove_FC_User(parentDiv, userDiv){
var child = document.getElementById(userDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
the elements get removed successfully, but it changes the remaining elements contents :(
maybe I need to generate a random "id" and avoid using "one" for each ?
how can I do that ? with a random function ? or a count ?

You could set an id of your newly added element and then use it with your onclick:
newdiv.setAttribute("id", "SOME_GENERATED_ID");
and then
remove;
Or you could use a class or name or data-* attribute. Or you could just remove the sibling of your "a" attribute etc.

Related

JavaScript function to generate dropdowns / remove dropdown menus

I am trying to add and remove dropdown <select>s to a form on a button click. This is the code I have currently. I could have sworn I had this working last night, but when I went to work some more on my project this morning, the dropdowns wouldn't add / remove correctly.
function DropDowns(){
this.counter = 0;
this.addDropdown = function (divname) {
var newDiv = document.createElement('div');
var html = '<select name="cookie' + this.counter + '">', i;
for (i = 0; i < cookies_drop.length; i++) {
html += "<option value='" + cookies_drop[i] + "'>" + cookies_drop[i] + "</option>"
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
this.counter++;
}
this.remDropdown = function() {
$('#dropdowns-container').find('div:last').remove();
this.counter--;
}
}
var dropsTest = new DropDowns();
HTML:
<form action='' method=post id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>
I can only figure out the main problem may be on the server side when you create the cookies_drop variable using json_encode.
Other problems may reside in:
A test on the parameter of addDropdown function is suggested to check if it's valid
In the function remDropdown the decrement of the counter variable must be done only if the element is actually removed
You mixed jQuery and javaScript
Instead of using directly the createElement, making the code more simple and readable, you used the innerHTML property.
So, my snippet is:
// I assume you used something like:
// var cookies_drop = JSON.parse( '<?php echo json_encode($data) ?>' );
var cookies_drop = [{text: "Text1", val: "Value1"},
{text: "Text2", val: "Value2"},
{text: "Text3", val: "Value3"}];
function DropDowns() {
this.counter = 0;
this.addDropdown = function (divname) {
var divEle = document.querySelectorAll('form[id=' + divname + ']');
if (divEle.length != 1) {
return; // error
}
var newDiv = document.createElement('div');
var newSelect = document.createElement('select');
newSelect.name = 'cookie' + this.counter;
newDiv.appendChild(newSelect);
for (var i = 0; i < cookies_drop.length; i++) {
var newOption = document.createElement('option');
newOption.value = cookies_drop[i].val;
newOption.text = cookies_drop[i].text;
newSelect.appendChild(newOption);
}
divEle[0].appendChild(newDiv);
this.counter++;
}
this.remDropdown = function () {
var lastDiv = document.querySelectorAll('#dropdowns-container div:last-child');
if (lastDiv.length == 1) {
lastDiv[0].parentNode.removeChild(lastDiv[0]);
this.counter--;
}
}
}
var dropsTest = new DropDowns();
<form action="" method="post" id="dropdowns-container">
<button id="add_cookie" type="button" onclick="dropsTest.addDropdown('dropdowns-container');">add cookie</button>
<button id="rem_cookie" type="button" onclick="dropsTest.remDropdown();">remove cookie</button>
<input name="cookies" type=submit value="submit">
</form>

multiple textbox values storing in same column in php

I an using Javascript when click add button to show multiple text box. but i don't how to store these text box values in database table single column. here i attached my form input coding and javascript for add number of textbox. after submit my form it stores somthing like Array into my table.
<?php
if(isset($_POST['submit']))
{
Include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
$count = $_POST['count'];
for($i = 0 ; $i < $count ; $i++)
{
//$count++;
$routesmore = $_POST['routes_more'];
$routesmore2 = explode('.', $routesmore[0]);
}
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$routesmore2', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
my input box:
<div class="col-lg-8" id="img_upload">
<!-- <input type="text" id="file0" name="routes" style="background:none;width:185px;"> -->
<div id="divTxt"></div>
<p><a onClick="addproductimageFormField(); return false;" style="cursor:pointer;width:100px;" id="add_img_btn" class="btn btn-primary">Add Route</a></p>
<input type="hidden" id="aid" value="1">
<input type="hidden" id="count" name="count" value="0">
My Javascript:
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more"+count_id+"' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change In JS - Append routes_more[] in jQuery("#divTxt").append in place of routes_more'+count+'.
<script type="text/javascript">
function addproductimageFormField()
{
var id = document.getElementById("aid").value;
var count_id = document.getElementById("count").value;
if(count_id < 2)
{
document.getElementById('count').value = parseInt(count_id)+1;
var count_id_new = document.getElementById("count").value;
jQuery.noConflict()
jQuery("#divTxt").append("<div id='row" + count_id + "' style='width:100%'><fieldset class='gllpLatlonPicker'><label for='text- input'>Stop</label><span style='color:red;'> *</span><input type='text' class='gllpSearchField' name='routes_more[]' id='file"+count_id_new+"' /></fieldset> &nbsp<a href='#' onClick='removeFormField(\"#row" + count_id + "\"); return false;' style='color:#F60;' >Remove</a></div>");
jQuery('#row' + id).highlightFade({speed:1000 });
id = (id - 1) + 2;
document.getElementById("aid").value = id;
}
}
function removeFormField(id)
{
//alert(id);
var count_id = document.getElementById("count").value;
document.getElementById('count').value = parseInt(count_id)-1;
jQuery(id).remove();
}
</script>
Change in PHP Code - Find total count of routes_more textbox. And do accordingly. (No Need of checking how much count was there in your html code.)
<?php
if(isset($_POST['submit']))
{
include 'db.php';
//$digits = 5;
//$staff_id=STAF.rand(pow(10, $digits-1), pow(10, $digits)-1);
$fromlocation = $_POST['fromlocation'];
$fromlatitude = $_POST['fromlatitude'];
$fromlongitude = $_POST['fromlongitude'];
$tolocation = $_POST['tolocation'];
$tolatitude = $_POST['tolatitude'];
$tolongitude = $_POST['tolongitude'];
// $routes = $_POST['routes'];
//$routesmore = $_POST['routes_more'];
$date=date('Y-m-d H:i:s');
$status=1;
//$usertype=1;
//For Routes More
$totalRoutesCount = sizeof($_POST['routes_more']);
$totalRoutes="";
for($i=0;$i<$totalRoutesCount;$i++)
{
$totalRoutes = $totalRoutes.$routesmore[$i].",";
}
$totalRoutes = rtrim($totalRoutes, ',');
$query = mysqli_query($connect,"INSERT INTO `motorpark-db`.`tbl_route` (`from_location`, `from_latitude`, `from_longitude`, `to_location`, `to_latitude`, `to_longitude`, `route1`, `status`, `created_date`) VALUES ('$fromlocation', '$fromlatitude', '$fromlongitude', '$tolocation', '$tolatitude', '$tolongitude', '$totalRoutes', '$status', '$date');");
if($query)
{
header('location:create_route.php#managepart');
}
else
{
header('location:create_staff.php');
}
}
?>
HTML :
<input type="text"
id="file0" name="routes[]"
style="background:none;width:185px;">
PHP:
INSERT Query:
'routes'(BD column) = serialize( $post['routes'] );
Display Time:
unserialize the column routes and print with foreach loop

How do I add and remove content within a div using JavaScript?

I already have a function that adds content to a div once an image is clicked; however, I want the content to be removed once the same image is clicked a second time. Is there a simple way to do this?
Is there also a way for the function that adds content to also appear with a number field next to it?
Here is the function that I used to add content.
function frenchBread(){
var div = document.getElementById("orderBox");
div.innerHTML = div.innerHTML + "French Bread" + "<br>";
}
Assign a variable to determine if the image was clicked or not.
Edit
Forgot to assign is_clicked :)
Edit Again
Added the input field next to the "Frech Bread" text.
var is_clicked = false;
function frenchBread(){
var div = document.getElementById("orderBox");
var curr = div.innerHTML, frenchy = 'French Bread <input type="number" name="amount"><br>';
if ( is_clicked ) {
var tmp = div.innerHTML;
curr = tmp.replace(frenchy, "");
div.innerHTML = curr;
is_clicked = false;
} else {
div.innerHTML = curr + frenchy
is_clicked = true;
}
}
<img src="" style="width: 30px; height: 30px; background: black;" onclick="frenchBread()" />
<div id="orderBox">
An item here <br />
</div>
You could just check for the content in innerHTML:
function frenchBread() {
var div = document.getElementById("orderBox");
if(var.innerHTML == "") {
div.innerHTML += "French Bread" + "<input type='number' /><br />";
} else {
div.innerHTML = "";
}
}
Edit: even shorter with the ternary operator, although less readable:
function frenchBread() {
var div = document.getElementById("orderBox");
div.innerHTML = if(var.innerHTML == "") ? "French Bread" + "<input type='number' /><br />" : "";
}
Edit: added the number field in both versions.

Trying to load cities based on state value using select options tag and javascript

I was using the information from this site http://jsfiddle.net/Q6h5s/ to create a drop down menu of Cities and States. When the State is selected the Cities belonging to that state should be selected. However all cities are being loaded. I am not too familiar with Javascript so I can't figure out where I am making this mistake.
Here is my code
<script>
$("#state").change( function(){
if($(this).data('options') == undefined){
$(this).data('options',$('#city-name option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[state=' + id + ']');
$('#city-name').html(options);
});
</script>
State:
<select id="state">
<?php
$fs = new fsCreator();
$cityState = $fs->loadCityState();
$dbh = new DatabaseHandler();
echo '<option value="0">State</option>';
$temp = null;
$sep = ',';
$index = 0;
$max = sizeof($cityState);
for($i = 0; $i< $max; $i++){
if(!($temp == substr($cityState[$i], 0, strpos($cityState[$i], $sep)))){
$index++;
$temp = substr($cityState[$i], 0, (strpos($cityState[$i], $sep)));
echo '<option value="'.($index).'">'.(substr($cityState[$i], 0, strpos($cityState[$i], $sep))).'</option>';
}
}
?>
</select>
City:
<select id="city-name">
<?php
$index = 0;
$cityIndex = 0;
$temp = null;
for($i = 0; $i < $max; $i++){
if(!($temp == substr($cityState[$i], 0, strpos($cityState[$i], $sep)))){
$index++;
$temp = substr($cityState[$i], 0, strpos($cityState[$i], $sep));
}
$cityIndex++;
echo '<option state="'.($index).'value="'.($cityIndex).'">'.(substr($cityState[$i], (strpos($cityState[$i], $sep)) + 1)).'</option>';
}
?>
</select>
The state attribute isn't set properly, which is what you're using to filter by.
you're missing a " at the end of it.
echo '<option state="'.($index).'" value="'.($cityIndex).'">'.(substr($cityState[$i], (strpos($cityState[$i], $sep)) + 1)).'</option>';
^^
Also you are attempting to bind an event handler to an object before it is created.
There are different ways to solve this
Event delegation, bind the handler to the document
$(document).on("change","#state", function(){
if($(this).data('options') == undefined){
$(this).data('options',$('#city-name option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[state=' + id + ']');
$('#city-name').html(options);
});
Using the document load event
$(document).ready(function(){
$("#state").change( function(){
if($(this).data('options') == undefined){
$(this).data('options',$('#city-name option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[state=' + id + ']');
$('#city-name').html(options);
});
});
Putting the code after the element in the markup
State:
<select id="state">
...
</select>
<script>
$("#state").change( function(){
if($(this).data('options') == undefined){
$(this).data('options',$('#city-name option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[state=' + id + ']');
$('#city-name').html(options);
});
</script>

How to show and hide an element, pass values from JavaScript to html element using JavaScript (not jQuery)?

I am new to programming so this question of mine might seems irrelevant. I want to know how to hide and show a html element using the original JavaScript not jQuery. Since I'm a total beginner I think I have to learn the primitive JavaScript before jumping into some libraries like jQuery.
First of all I'll paste the code:
index.php
<html>
<head>
<script type="text/javascript" src="myscripts.js"></script>
<style type='text/css'>
#show_description {
min-height: 100px;
min-width: 500px;
max-height: 100px;
max-width: 500px;
background-color: #000;
color: #fff;
}
</style>
</head>
<body>
<div>
<form name="myform" action="index.php" method="get" >
Select Year: <?php echo hspacer(1); ?>
<select id="year_list" name="year_list" onchange="check_year_event();" >
<?php
for($year = (date('Y') - 100); $year <= (date('Y') + 100); $year++ ) {
if ($year == date('Y')) echo "<option value='$year' name='$year' selected='' >" . $year . "</option>";
else echo "<option value='$year' name='$year' >" . $year . "</option>";
}
?>
</select>
<?php echo hspacer(5); ?>
Select Event: <?php echo hspacer(1); ?>
<select id="event_list" name="event_list" onchange="check_year_event();" >
<?php
$events = array("Karate Tournament", "Beauty Pageant", "Film Festival", "Singing Contest", "Wedding");
foreach($events as $event) echo "<option value='$event' name='$event' >" . $event . "</option>";
?>
</select>
<?php echo vspacer(2); echo hspacer(22); ?>
<input type="submit" id="add_description" value="Add Description" onclick="show(); "/>
</form>
</div>
<div id="show_description">
</div>
</body>
</html>
functions.php
<?php
function hspacer($num_of_spaces) {
$spaces = "";
if ($num_of_spaces > 0) for($i=0; $i<$num_of_spaces; $i++ ) $spaces .= " ";
return $spaces;
}
function vspacer($num_of_linefeeds) {
$linefeeds = "";
if ($num_of_linefeeds > 0) for($i=0; $i<$num_of_linefeeds; $i++ ) $linefeeds .= "<br />";
return $linefeeds;
}
?>
myscripts.js
function create2DArray(row, col){
var array2D = new Array(row);
for (var i = 0; i < row; i++) {
array2D[i] = new Array(col);
}
return array2D;
}
function check_year_event() {
var years_and_events = create2DArray(10, 3);
years_and_events[0][0] = 2001;
years_and_events[0][1] = "Karate Tournament";
years_and_events[0][2] = "Annual karate tournament held globally";
years_and_events[1][0] = 2002;
years_and_events[1][1] = "Beauty Pageant";
years_and_events[1][2] = "Beauty pageant held globally";
years_and_events[2][0] = 2003;
years_and_events[2][1] = "Film Festival";
years_and_events[2][2] = "Film festival held globally";
years_and_events[3][0] = 2004;
years_and_events[3][1] = "Singing Contest";
years_and_events[3][2] = "Singing contest tournament held globally";
years_and_events[4][0] = 2005;
years_and_events[4][1] = "Wedding";
years_and_events[4][2] = "Wedding tournament held globally";
years_and_events[5][0] = 2007;
years_and_events[5][1] = "Karate Tournament";
years_and_events[5][2] = "Annual karate tournament held globally";
years_and_events[6][0] = 2008;
years_and_events[6][1] = "Beaty Pageant";
years_and_events[6][2] = "Beauty pageant held globally";
years_and_events[7][0] = 2009;
years_and_events[7][1] = "Film Festival";
years_and_events[7][2] = "Film festival held globally";
years_and_events[8][0] = 2010;
years_and_events[8][1] = "Singing Contest";
years_and_events[8][2] = "Singing contest tournament held globally";
years_and_events[9][0] = 2011;
years_and_events[9][1] = "Wedding";
years_and_events[9][2] = "Wedding tournament held globally";
var year = document.getElementById('year_list').value;
var event = document.getElementById('event_list').value;
for (var i = 0; i < years_and_events.length; i++) {
if ((year == years_and_events[i][0]) && (event == years_and_events[i][1])) {
// This is where I want to put the command to show and hide the div with id = "show_description"
}
}
}
What I want to happen is that when the user changes the value of any of the select element it will automatically check if the combination exists. If there is, it will send the content of the array to the div and that's the only time the div will show.
I'm not pretty sure to what you looking for, some question aren't clear to me. If you say hide or show a div, you can change the style of the div.
//Using visibility
if(show){
document.getElementById('show_description').style.visibility = "visible";
} else {
document.getElementById('show_description').style.visibility = "hidden";
}
//Using display
.style.display = "block"; //To show
.style.display = "none"; //To hide
First, I'd be worried about using the var event, while not a reserve word future developers may get slightly off-balanced to see it in a non DOM-event usage.
Then to start your page off, set that div to visibility:hidden
<div id="show_description" style="visibility:hidden;"></div>
For the code:
var targetNode = document.getElementById('show_description');
var children = targetNode.childNodes;
for(var i=0,len=children.length;i<len;i++){
targetNode.removeChild(children[i]);
}
var newNode = document.createTextNode(year+" "+event);
targetNode.appendChild(newNode);
targetNode.style.visibility = 'visible';
Basically the above selects the div where you want the content to go. Then removes anything inside of it, lastly it creates a new text node of your selected year and event and appends that into the div.
I've found apples DOM script intro to be very helpful for pure js dom manipulating.

Categories