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>
Related
I've looked at previous questions like this and cannot find the answer to my problem. I am working in javascript creating a checkout screen and I have two onclicks for two different html files but when I go to the html file for both it says that the other onclick is null. I have tried window.load and moving the script to the bottom of the
var cart = [];
var search = document.getElementById("addItem");
let placement = 0;
var cartElement = document.getElementById("showCart");
var cartTotal = document.getElementById("totalCart");
search.onclick = function(e) {
var userInput = document.getElementById("query").value;
var cartHTML = "";
e.preventDefault();
placement = 0;
for (i = 0; i < menu.length; i++) {
if (menu[i][0].includes(userInput)) {
cart.push(menu[i]);
placement++;
}
}
if (placement == 0) {
alert("Menu option not included. Please try again.");
}
cart.forEach((item, Order) => {
var cartItem = document.createElement("span");
cartItem.textContent = item[0] + " (" + item[1] + ")";
cartHTML += cartItem.outerHTML;
});
cartElement.innerHTML = cartHTML;
}
window.onload = function() {
var checkout = document.getElementById("addCartButton");
checkout.onclick = function(event) {
cart.forEach()
var cartTotalHTML = "";
event.preventDefault();
cart.forEach(Item, Order => {
var totalInCart = 0;
var writeCart = document.createElement("span");
totalInCart += Order[1];
});
writeCart.textContent = cartTotal += item[1];
cartTotalHTML = writeCart.outerHTML;
cartTotal.innerHTML = cartTotalHTML;
console.log(cartTotal);
}
}
<h3>Search for items in the menu below to add to cart</h3>
<form id="searchMenu">
<input type="search" id="query" name="q" placeholder="Search Menu..."></inpuut>
<input type = "Submit" name= "search" id="addItem" ></input>
</form>
<h4>Your cart: </h4>
<div class="Cart">
<div id="showCart"></div>
</div>
<script src="Script.js"></script>
<h4>Cart</h4>
<button id='addCartButton' class="Cart">Add Cart</button>
<div class="ShowCart">
<div id="totalCart"></div>
</div>
<script src="Script.js"></script>
I'm newbie in jquery And Data table,
I have problem when to set value for element input from another page using function.
this my 1st page code
{
data: "action_user",
targets: "action_user",
mRender: function (data_app, type_app, row_app) {
if (row_app["id_user"] !== null) {
var va_id_user = row_app["id_user"];
var va_user_name = row_app["user_name"];
var va_gender = row_app["gender"];
var va_address = row_app["address"];
var va_imei = row_app["imei"];
var va_phone = row_app["phone"];
var va_role_name = row_app["role_name"];
var va_email = row_app["email"]; //,supplier_name,supplier_code,address,contact_name,contact_num,status_supp
var va_status_user = row_app["status_user"]; // <a href='#'id='updateDataUser' onclick='javascript:myFunc(" + supplier_id + ")'><i class='fa fa-edit'title='Edit'></i></a>\n\
var data_users = {
id_user: va_id_user,
user_name: va_user_name,
gender: va_gender,
imei: va_imei,
phone:va_phone,
address:va_address,
role_name: va_role_name,
email: va_email,
status_user: va_status_user
};
return"<a id='updateDataUser' href='#' onclick='javascript:editUserFunc(" + JSON.stringify(data_users) + ")'><i class='fa fa-edit activeRecord' rel='13' title='Edit'></i></a>";
// return "<a href='" + data_pict_1 + " 'target='_blank' class='btn btn-info'>" + "<font color='#f2f2f2' size='2em'>" + "Display" + "</font>" + "</a>";
}
}
}
this my html code
<div id="div_add_pic" class="panel panel-default">
<form id="form_add_pic" name="form_add_pic" method="POST" action="">
<div id="form_add_user_response" class="resp"></div>
<div class="box-body">
<div class="form-group">
<label for="username" class="req">User Name :</label>
<input type="text" name="userName" id="userName" placeholder="User Name" class="form-control uppercase" />
</div>
</div>
</form>
</div>
this my function to set input value element .
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
$("#userName").val(userName);}
my function I change to
function editUserFunc(data_users) {
var userName = data_users.user_name;
alert(userName);
var oForm = document.getElementById("form_add_pic");
var set_userName = oForm.userName;
window.location.href = "index.jsp?url=user_layout& pages=add_user_form"
}
but I've got error
validation.js:1422 Uncaught TypeError: Cannot read property 'userName' of null
at editUserFunc (validation.js:1422)
at HTMLAnchorElement.onclick (index.jsp?url=user_layout&pages=list_users:1)
my console.log printscreen
how to call the element form on another page
I have tried it many times but I've been unsuccessful. Please help!
I think, you have to move all these functions inside
$(document).ready(function(){
//Replace with your code
})
Because your script may be there in top of html tags and while running these scripts, those html inputs are not loaded.
finally I use this code, to get parameter on url address bar
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
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>  <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>  <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
I need to create text box using JavaScript. I coded as below:
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
<script>
HTML file:
<input type="text" style="width:200px;" id="no_room" onChange="popuptxt()" required>
<div id="my_div"></div>
It displays number of textbox when I type a number, but I need to clear them when I type another number.
Just reset the content of you block each time :
<script>
function _(x) {
return document.getElementById(x);
}
function popuptxt() {
my_div.innerHTML = "";
var i = _("no_room").value;
for(a = 1; a <= i; a++) {
my_div.innerHTML = my_div.innerHTML + "Room number for " + a + "<br><input type='text' name='mytext'+ i><br>"
}
}
</script>
Just add my_div.innerHTML = ""; before the for loop in popuptxt(). That way it will be cleared each time its called.
I have these functions:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).find('.comments-form-' + guid).hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
$(this).find('.comments-form-' + showGuid).show();
var showGuid = $(this).attr('rel');
loadShowingsComments(showGuid);
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});
function loadShowingsComments(guid) {
var commentTextArea = "#comments-form-" + guid;
var commentDisplay = ".spanComments" + guid;
var curComment = $(commentDisplay).text();
var element = "#comments-form-" + guid;
$(element).slideDown();
}
<script>
function showComments() {
var comments = document.querySelectorAll(".spanComments");
for (var i = 0; i < comments.length; i++) {
comments[i].innerHTML = "This is comment #" + i;
}
}
</script>
View Comments
Those functions should grab the information from my controller (it's hooked up correctly. I've stepped through that and it has populated the right information) and place them in my span:
<tr class="p_la" id="comments-form-#currentShowing.ShowingGUID" style="display:none;">
<td colspan="4" style="border-right:5px solid #DDDDDD;">
<form action="" method="post">
<span class="spanComments" cols="100" rows="5">#string.Format("{0} / {1}", #currentShowing.Comments.DateAdded, #currentShowing.Comments.CommentsValue)</span>
<br />
Close
</form>
</td>
</tr>
Unfortunately, when I click on my hyperlink, it only populates the first span with the first span's information. Works great for the first span but when you click on the hyperlink in the second, third, fourth, etc item, they will only open up the first span with the first span's information.
The code should populate each successive span with its own information.
My JQuery was off. It needed this to be changed:
$(".Read-Showing-Comment-Cancel").live('click', function (e) {
var guid = $(this).data("guid");
e.preventDefault();
var f = $('#comments-form-' + guid).slideUp();
$('comments-text-' + guid).empty();
$('comments-text-' + guid).value = "";
$(this).parent("form").parent("td").parent("tr").hide();
$('comments-sendlink-' + guid).show();
});
$('.showComments').unbind('click').click(function (event) {
$('.ListingDisplayOptions').hide();
var showGuid = $(this).attr('rel');
$(this).parent("td").parent("tr").next('#comments-form-' + showGuid).show();
$(this).attr('id', 'comments-sendlink-' + showGuid);
event.preventDefault();
});