Dynamically created form elements value not getting in $_POST in php - php

I have created some dynamic text boxes and values according to the no. of cart items selected by a user. The no. of cart items are stored in a cookie and I am trying to do the following:
1) Get the no. of cart items from the cookie named cartcounter
2) Create 'cartcounter' no of text boxes with name itemkey_skey where itemkey is the hash key of each items in user cart.
3) Submit the form
4) Get the keys of the selected items in php
Now I can create cartcounter, the number of text boxes with different values.
But the problem is that I can get only the first text box value in $_POST in PHP. I would like to get all the values of the dynamically created form elements.
Code:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
$("#frm").submit();
}
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​

I have solved it. The problem was that I was calling the submit function inside the loop. I have solved it by doing:
$(document).ready(function() {
if (getCookie("cartcounter") != 0) {
$("#counter").val(getCookie("cartcounter"));
for (var i = 1; i <= cartcounter; i++) {
var ckey = getCookie(i + "_skey");
var element = document.createElement("input");
alert("Element=" + element);
element.setAttribute("type", "text");
element.setAttribute("value", ckey);
element.setAttribute("name", "skey_" + ckey);
var foo = document.getElementById("itmbox");
foo.appendChild(element);
}
$("#frm").submit();
}
else {
alert('Your cart is empty , please choose your product');
window.location = "http://synergiadigital.com/restaurant2/orderFood.php/"
}
});​

Related

How to remove an input value before submitting it in Wordpress with the Ultimate member plugin

I want to know how to remove an input value before submitting a profile form in Wordpress with Ultimate Member plugin. I've been stuck with this for a whole week.
The thing is that I have conditional fields in the profile form that if the user does not select, they still save their values ​​when the form is submitted. The plugin does not remove the values ​​from the hidden fields conditionally, which is a problem if you want to send these fields elsewhere with REST API.
I couldn't do it with PHP so I added a script inside the principal function to try and clear the values. This work when user refresh the form, but not when user submit the form with the hook um_after_user_updated
function remove_before_send () {
?>
<script>
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
</script>
<?php
}
add_action('um_profile_content_main', 'remove_before_send');
EDIT:
Thanks to the comment of #JB_DELR. You really gave me all the clues.
This is my final code (im not proud, because i wanted to use php, but this is the best i could do)
function remove_before_send () {
?>
<script>
var boton = document.querySelector("div.um-left.um-half > input");
boton.addEventListener("click", function(){
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
if (elements[i].style.display == "none") {
elements[i].childNodes[1].childNodes[0].value = "";
}
}
});
</script>
<?php
}
add_filter( 'um_profile_content_main', 'remove_before_send');
Your js script need to handle the form submit event, prevent default submiting, remove unnecessary fields an submit the form itself.
Something like this:
<script>
var form = document.querySelector(<select the form>);
form.onsubmit = function(e) {
e.preventDefault(); // don't submit the form right now;
var elements = document.querySelectorAll('.um-is-conditional');
for (var i = 0; i < elements.length; i++) {
elements[i].childNodes[1].childNodes[0].value = "";
}
// to remove element, this remove the input field, so field is no more in the request
// elements[i].childNodes[1].removeChild(elements[i].childNodes[1].childNodes[0]);
}
form.submit();
</script>

How to add extra space to div using Jquery?

I am working on the sticky menu and highlight menu based on div id in WordPress. I have completed code well but I got a problem.
I have a sticky header when I click menu item in side sticky menu title going back to header title not visible.
I want result like this.'
How can I solve this?
My Jquery Code
jQuery(function($) {
/**
* This part causes smooth scrolling using scrollto.js
* We target all a tags inside the nav, and apply the scrollto.js to it.
*/
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
var aChildren = jQuery("#nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = jQuery(aChild).attr('href');
console.log(ahref);
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+70; // get the offset of the window from the top of page
console.log('Window Position:'+windowPos);
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
//console.log(theID);
var divPos = $(theID).offset().top-150; // get the offset of the div from the top of page
console.log('Div Position:'+divPos);
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("#nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("#nav li:last-child a").addClass("nav-active");
}
}
});
});
You need to offset the height of the heading when you jump to an anchored section.
Are you using the jQuery scrollTo plugin? If you can do something like:
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, 800, {offset: {top:-80, left:0} });
});
Options for scrollTo found here: http://demos.flesler.com/jquery/scrollTo/

Get index value from dropdown form

I have a dropdown that is filled by a database and everything works well. However I want to pass a parameter to php based on the value of the dropdown which I can do. If I force the var to have a particular number it gets the corresponding item in the database. I'm having a problem to get the value of a dropdown. I've tried all the suggestions here in the forum and nothing works in this particular area of my code. I have it working on another piece of my code but not on this particular one and I don't know why. Here is my code:
<select id="servicos" onChange="return selectServ();">
<option value="item" class="itemoption">Serviço</option>
This is the code that is not working:
function selectServ() {
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
$.getJSON("http://ib.esy.es/gestao/_php/servicos_threadingpreco.php", { serv: idserv }, null).then(function(data) {
console.log(data);
var tr = data
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
// Indexing into data.report for each td element
$(tr).append("<td>" + data[i].preco + "</td>");
$('.table1').append(tr);
}
});
}
If I put
var idserv = "1"
It is working, however this:
var e = document.getElementById("servicos");
var idserv = e.options[e.selectedIndex].value;
Is not getting a value. The console log gives:
selectdynamicpreco.html:76 Uncaught TypeError: $(...).value is not a function
You should consider using jQuery to get the value of the dropdown:
$('#dropdown').val() will give you the selected value of the drop down element. Use this to get the selected options text.
$("#dropdown option:selected").text();
Should get you the text value of the dropdown.
This is working on another piece of the code
<script>
function selectCat(){
$('#servicos').change(function() {
$('#demo').text($(this).find(":selected").text());
});
//for textbox use $('#txtEntry2').val($(this).find(":selected").text());
var e = document.getElementById("categoria");
var servSelected = e.options[e.selectedIndex].value;
var url = "";
var items="";
if(servSelected === "1"){
url = "http://ib.esy.es/gestao/_php/servicos_threading.php";
}
if(servSelected === "2"){
url = "http://ib.esy.es/gestao/_php/servicos_sobrancelhas.php";
}
if(servSelected === "3"){
url = "http://ib.esy.es/gestao/_php/servicos_manicure.php";
}
$.getJSON(url,function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.ID+"'>"+item.servico+"</option>";
});
$("#servicos").html(items);
});
};
</script>

Adding 3rd Dynamic drop down menu

I already have this code working for 2 selection menus, now I am trying to add a third but the third is just showing all of the sub-sub categories, rather than being based on the previous selections..
Here is the menu code, I'll just show 1 selection example so it's easier to read.
<select name="category" id="category">
<option value="Sport">Sport</option>
</select>
<select name="sub_category" id="sub_category">
<option value="Golf" class="Sport">Golf</option>
</select>
<select name="subsub_category" id="subsub_category">
<option value="Mens" class="Golf">Mens</option>
<option value="Ladies" class="Golf">Ladies</option>
</select>
JS CODE
<script src="js/menu.js"></script>
<script type="text/javascript">
window.onload = function() {
dynamicSelect("category", "sub_category", "subsub_category");
}
</script>
MENU.JS
function dynamicSelect(id1, id2, id3) {
// Browser and feature tests to see if there is enough W3C DOM support
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_mac = (agt.indexOf("mac") != -1);
if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) {
// Obtain references to both select boxes
var sel1 = document.getElementById(id1);
var sel2 = document.getElementById(id2);
var sel3 = document.getElementById(id3);
// Clone the dynamic select box
var clone = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions = clone.getElementsByTagName("option");
// Onload init: call a generic function to display the related options in the dynamic select box
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
sel1.onchange = function() {
refreshDynamicSelectOptions(sel1, sel2, sel3, clonedOptions);
};
}
}
function refreshDynamicSelectOptions(sel1, sel2, sel3 clonedOptions) {
// Delete all options of the dynamic select box
while (sel2.options.length) {
sel2.remove(0);
}
// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
var pattern1 = /( |^)(select)( |$)/;
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
var pattern3 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
// Iterate through all cloned options
for (var i = 0; i < clonedOptions.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2) || clonedOptions[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions[i].cloneNode(true));
sel3.appendChild(clonedOptions[i].cloneNode(true));
}
}
}
Edit: Had to change a lot to get it working, but it is working now, here: http://jsfiddle.net/kvAWf/11/
Here's the resulting Javascript:
var sel1 = document.getElementById('category');
var sel2 = document.getElementById('sub_category');
var sel3 = document.getElementById('subsub_category');
// Clone the dynamic select box
var clone2 = sel2.cloneNode(true);
var clone3 = sel3.cloneNode(true);
// Obtain references to all cloned options
var clonedOptions2 = clone2.getElementsByTagName("option");
var clonedOptions3 = clone3.getElementsByTagName("option");
sel1.onchange = function(){
refreshSelect2();
}
sel2.onchange = function(){
refreshSelect3();
}
function refreshSelect2() {
while (sel2.options.length) {
sel2.remove(0);
}
var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions2.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions2[i].className.match(pattern2)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel2.appendChild(clonedOptions2[i].cloneNode(true));
}
}
refreshSelect3();
}
function refreshSelect3() {
while (sel3.options.length) {
sel3.remove(0);
}
var pattern3 = new RegExp("( |^)(" + sel2.options[sel2.selectedIndex].value + ")( |$)");
for (var i = 0; i < clonedOptions3.length; i++) {
// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
if (clonedOptions3[i].className.match(pattern3)) {
// Clone the option from the hidden option pool and append it to the dynamic select box
sel3.appendChild(clonedOptions3[i].cloneNode(true));
}
}
}

how to assign unique id to elements that are created dynamically - Javascript

Hello im trying to generate dynamic divs with a textbox and delete button in it. On form submit i want all dynamically generated textboxes values, how can i assign unique id to the textbox element. The ID's / Name of textbox should be unique.. to get all values properly.
Pls suggest..
My Code:
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic elements</TITLE>
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
eleText.setAttribute("id", "textbox");
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(eleText);
eleDiv.appendChild(eleBtn);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px"><INPUT type="text" name="txtData" /></div>
<input type="submit" value="Submit"/>
</form>
You can keep a global count variable (outside of function divId).
Each time you create a new div, you add 1 to the counter and use it as a unique ID for your textbox.
<script language="javascript">
var globalcount=0;
function addRow()
{
globalcount++;
//the rest
}
</script>
And the rest is much like you already do for the name.
To answer your question directly you could try:
var textboxCount = 0;
/* In your function */
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
eleText.setAttribute("id", "textbox" + textboxCount);
textboxCount += 1; //Increment the count
That will create textbox's with id's textbox0, textbox1, textbox2 etc.
Or, for a more efficient option you may store all textboxs you create in an array, like so:
var textboxes = new Array();
/* In your function */
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
textboxes.push(eleText);
Now instead of calling e = document.getElementById('textbox4'); you may call e = textboxes[4];
This function will generate a unique ID:
function uniqueId() {
var uid;
do {
uid = 'uid-' + Math.random();
} while (document.getElementById(uid));
return uid;
}

Categories