Append forms dynamically based on PHP-Array - javascript

I'm developing a module for my clan, where the user can automatically generate a BBCode formatted text.
As there are multiple groups in our team, i want them also seperated by <h1> Tags
For each Group from $groups there should be an individual amount of clones.
Here's my HTML + JS. Instead of the <h1> there sould be the name of the group from the PHP array $groups=array("Group 1", "Group 2",...)
http://jsfiddle.net/yq2jjn9z/1/ (form.js)
My index.php looks at the moment like this:
<?php
[...] //some DB stuff
<script>js/form.js</script>
<form name="groups" action="" method="post">
<?php foreach($groups as $key): ?>
<div class="field_wrapper">
<div>
<h2><?php echo($key)?></h2>
<input type="text" name="field_rank[]" placeholder="Rank" value=""/>
<input type="text" name="field_name[]" placeholder="Name" value=""/>
+
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
?>
Sadly, it clones everything, not only within the selected group.
But the remove button works exactly as intended. Did I miss something?
Also, can I do this without PHP and HTML mixed?
Any ideas, how i can improve this?
Edit: http://techtreedev.de/muster.php this it what it's looks like at the moment (But with German words)
PS: Before downvoting, please consider writing what's wrong with my question. Thanks in advance

var wrapper = $('.field_wrapper');
...
$(wrapper).append(fieldHTML);
wrapper contains all elements with class "field_wrapper". If you add an element to it, it is added to all elements with this class.
You need to find the correct wrapper div for the + button that was clicked
$(addButton).click(function(){
$(this).parents(".field_wrapper").append(fieldHTML);
});

the question is a bit confusing, but a few things to note,
at the moment, you are using an array to parse the data the the server, but not grouping the arrays together at all, try the below code as a starting point.
<?php $groups = array("group 1","group 2"); ?>
<form name="groups" action="" method="post">
<?php foreach($groups as $key=>$text): ?>
<div class="field_wrapper">
<div>
<h2><?php echo($text)?></h2>
<div class="rowDiv_<?= $key ?>">
<input type="text" name="field_rank[<?= $key ?>][0][Rank]" placeholder="Rank" value=""/>
<input type="text" name="field_name[<?= $key ?>][0][Name]" placeholder="Name" value=""/>
+
</div>
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
<script>
$("body").on("click",".add_button",function(){
myKey = $(this).attr("data-group-key");
rowCount = $(".rowDiv_"+myKey+":last a").attr("data-rowCount");
rowCount = parseInt(rowCount) + 1;
html = '<div class="rowDiv_'+myKey+'">';
html += '<input type="text" name="field_rank['+myKey+']['+rowCount+'][Rank]" placeholder="Rank" value=""/> ';
html += '<input type="text" name="field_name['+myKey+']['+rowCount+'][Name]" placeholder="Name" value=""/> ';
html += '-';
html += '</div>';
$(this).parent().parent().append(html);
})
$("body").on("click",".remove_button",function(){
$(this).parent().remove();
})
</script>

You need to make a unique wrap for each group like this
<script>js/form.js</script>
<form name="groups" action="" method="post">
<?php foreach($groups as $key): ?>
<div class="field_wrapper_<?php echo $key;?>">
<div>
<h2><?php echo($key)?></h2>
<input type="text" name="field_rank[]" placeholder="Rank" value=""/>
<input type="text" name="field_name[]" placeholder="Name" value=""/>
+
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
And put this code in your JS file
<script>
function append_more(key)
{
var wrapper = $('.field_wrapper_'+key);
var fieldHTML = '<div><input type="text" name="field_rank[]" placeholder="Rang" value=""/> <input type="text" name="field_name[]" placeholder="Name" value=""/> -</div>';
$(wrapper).append(fieldHTML);
}
</script>

Related

PHP form open new window [duplicate]

This question already has answers here:
Submit form to popup window?
(3 answers)
Closed 2 years ago.
I have a PHP website that i am building where i am adding a basic product order form. I have created the form elements and once a user selects an option, i would like to open a new window (not tab), have that new window present as the focus and have variables delivered to the newly opened window through the GET method.
Currently when i submit the form, the target form opens per js, however the url variables are not passed to the new window. My code somehow concurrently also opens a new tab and transfers the GET url to the new tab and not the new window resulting in a new tab with the correct url and a new window without the correct url.
I appreciate there are many similar questions like this and i have spent hours trying to fix to no avail.
Thanks in advance for your time
Source form HTML:
<div class="prdContainer">
<form method="GET" target="_blank" action="members_order.php" onsubmit="openMemberOrder()" id='bcpot002' class="prdInput">
<div class="prodDiv">
<button type="submit" id="catOrder" class="catOrder"><img id="prdImgThumb" name="bcpot002" src="../../../Images/Product_Catalogue/bcpot002/bcpot002_thumb.jpg" ></button>
</div>
<div class="formDiv">
<label for="cat_ID" value="">Product Name:</label>
<input type="text" id="catID" name="cat_ID" value="bcpot002" readonly><br>
<label for="cat_Desc">Product Description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="Red_Pot" readonly><br>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="" readonly>
<input type="hidden" id="divHeight" name="DivHeight" value="1036" readonly>
<input type="hidden" id="divWidth" name="DivWidth" value="1543" readonly>
</div>
</form>
</div>
Source form JS:
function openMemberOrder(url) {
newwindow = window.open('members_order.php', 'members_order', 'width=1600px,height=2000px,toolbar=no,scrollbars=no,resizable=no');
if (window.focus) {newwindow.focus()}
if (!newwindow.closed) {newwindow.focus()}
return false;
}
Receiving page HTML:
<?php require_once('xxxxx/initialize.php');
$catID = $_GET['cat_ID'];
$catDesc = $_GET['cat_Desc'];
$DivHeight = $_GET['DivHeight'];
$DivWidth = $_GET['DivWidth'];
echo "ID: " . $catID . "<b>";
echo "Desc: " . $catDesc . "<b>";
echo "Val: " . $catVal . "<b>";
echo "H: " . $DivHeight . "<b>";
echo "W: " . $DivWidth . "<b>";
?>
<body>
<header id="memOrderHead" ></header>
<div class="gridContainer" id="gridContainer" ></div>
<article class="article" >
<div class="orderDiv">
<h3>Order Item</h3>
<form class="orderInput">
<label for="cat_ID">Product name:</label>
<input type="text" id="catID" name="cat_ID" value="<?php echo $catID; ?>" readonly>
<label for="cat_Desc">Product description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="<?php echo $catDesc; ?>" readonly>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="<?php echo $catVal; ?>" readonly>
<label for="cat_quant">Quantity ordered:</label>
<input type="number" id="orderQuant" name="cat_quant" min="0" placeholder="0">
<label for="cat_Total">Total Price $:</label>
<input type="number" id="orderTotal" name="cat_Total" min="0" placeholder="0" readonly>
<button type="button" class="orderButton" onclick="clearForm()">Clear</button>
<button type="button" class="orderButton" onclick="total()">Calculate Total</button>
<button type="button" class="orderButton" onclick="orderConfirm()" id="confirmReset">Submit</button>
</form>
</div>
</article>
You can pass data from the webpage to a new window using HTML 5 local storage. Some other alternatives are given in the post below
JavaScript - How do I open a new page and pass JSON data to it?

jquery get specific input value from clicked button on form when multiple forms on page

I have multiple forms on the same page but need to get the values of the input element when a particular form is clicked i.e
However the jquery returns undefined query i
MY SCRIPT to get the values
jQuery(function($) {
$('.theform').submit(function(e) {
e.preventDefault();
var user = $(this).find(".product").val();
alert(user);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$product='productOne';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ??>" style="display: none">
<input type="hidden" class="userName" name="userName" value="john759">
<button class="action">Click</button>
</form>
$product='productTwo';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ?>" style="display: none">
<input type="hidden" class="userName" name="userName" value="dDuck">
<button class="action">Click</button>
</form>
instead of this:
var user = $(this).find(".product").val();
use:
var user = $(this).parent().find(".product").val();
Use jquery closest function to get closset form value;
$(this).closest('form').find(".product").val();
Try to change type of button
<button class="action" type="submit">Click</button>

Automatically add a certain class, whenever <Form> code contains a certain value?

I want to add a special class to each form that contains the word special as part of its action URL.
But I have many forms, and I can't think of an automated way to do this.
The only way I came up with was to create the following code, but I will have to create such code for each and every form, using a different index number:
<?php
$case1 = "special";
$case2 = "none";
if($case1 == "none") {
$class1 = ""; // don't add any class
}
else {
$class1 = "effect"; // add `effect` class
}
if($case2 == "none") {
$class2 = ""; // same goes here
}
else {
$class2 = "effect"; // and here
}
?>
HTML:
<form action="/go/<?= $case1 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class1 ?> general-class" value="submit">
</form>
<form action="/go/<?= $case2 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class2 ?> general-class" value="submit">
</form>
OUTPUT:
<form action="/go/special" method="POST" target="_blank">
<input type="submit" class="effect general-class" value="submit">
</form>
<form action="/go/none" method="POST" target="_blank">
<input type="submit" class="general-class" value="submit">
</form>
Is there any automated way to do this?
Basically I have two types of forms, one should be opened using a jquery plugin (henace the special class), and the other should open in a normal way.
My way to differentiate between them is to insert the $case[i] variable into the action url, as this is something that I have to do either way.
Perhaps there's a complete different way to achieve this, I don't know.
EDIT:
Real Form is generated mostly manually, with this code:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= $class1 ?> general-class" value="Click Me"></form>
(all variables are being given values at the start of the PHP block you see above)
There's two ways - PHP and jQuery. Based on your code, we don't have enough info to know if we can use the PHP way or not, so here's the jQuery way:
// wait until the document is ready
jQuery(function($) {
// find all forms that have "special" in the action
$('form[action*="special"]').each(
function() {
// within the form, find the submit button, and add the "effect" class
$(this).find('input[type="submit"]').addClass('effect');
}
);
});
And, the shorter / less verbose way:
jQuery(function($) {
// find all forms that have "special" in the action, find their input, and add the class
$('form[action*="special"] input[type="submit"]').addClass('effect');
});
The PHP Way
So, to do this in PHP, I would recommend writing a simple function, then calling it.
function get_class( $slug ) {
$class_map = array(
'special' => 'effect',
'none' => '',
// .. you could add others here if appropriate
return ( isset( $class_map[ $slug ] ) ) ? $class_map[ $slug ] : '';
);
Then you could use it in your php like so:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= get_class( $case1 ); ?> general-class" value="Click Me"></form>
While that may not seem like a big value, if you started applying those concepts to your code, you would quickly see the value start adding up.

Multiple Forms on Same page AJAX

I'm having troubles on making this work.
I need to have multiple forms on the same page... I've tried countless things, but nothing seem to work.
What I'm trying to do here is identify every form (in some way) in order to submit that one instead of the FIRST form on the page. Code below, works but submits always the same form, the first one!
Here's my current code
JS:
$(document).ready(function(){
$('.submit').on("click", function() {
var artworkId = $("#inquirebox").data("artworkid");
$.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
HTML:
<div id="inquirebox" data-artworkid="<?php echo 456;?>">
<form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="hidden" name="id" value="<?php echo 456;?>">
<input type="hidden" name="artist" value="<?php echo $title1; ?>">
<input type="hidden" name="url" value="<?php echo $uri1; ?>">
<input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">
<input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
<div id="success"></div>
</form>
</div>
You're using the same ID on all the DIV wrappers around the forms.
ID's must be unique, so you could use a class instead, but you really don't need any identifiers at all, nor do you need data attributes, the .submit button is inside the form, so all you need is this.form, or more jQuery'ish $(this).closest('form') to get the parent form
$(document).ready(function(){
$('.submit').on("click", function() {
var form = $(this).closest('form');
$.post("send.php", form.serialize(), function(response) {
form.find('.success').html(response);
});
return false;
});
});
You should however use a class on the #success element to find it based on the form.

Using javascript to prevent duplicate values of dynamically generated input text boxes

I have a 3 step (3 page) form. The first page that asks the user to check up to 5 of there favorite music genres. The second page dynamically displays the checked genres and then asks to rank them and the third page displays their music genre preference in order.
My question is how can I use javascript to prevent duplicate values of dynamically generated input text boxes on the second page?
I found this code (http://jsfiddle.net/zHJSF/) that would work if my text box fields were set but the text box fields are being generated dynamically. It might be easier to tweak that code or do something different that involves a loop. I'm not sure.
below is the code for the three pages:
Page 1
<form id="genre" name="genre" method="post" action="musicsell.php">
<input type="checkbox" name="genre[]" id="Rap" value="Rap"/>Rap<br />
<input type="checkbox" name="genre[]" id="HipHop" value="HipHop"/>HipHop<br />
<input type="checkbox" name="genre[]" id="RnB" value="RnB"/>RnB<br />
<input type="checkbox" name="genre[]" id="Rock" value="Rock"/>Rock<br />
<input type="checkbox" name="genre[]" id="Jazz"value="Jazz"/>Jazz<br />
<p>
<input type="submit" value="Next">
<br />
</p>
</form>
Page 2
<form id="form1" name="form1" method="post" action="musicresults.php">
<?php
$name = $_POST['genre'];
if(isset($_POST['genre'])) {
foreach ($name as $genre){
?>
<input type="number" required="required" id="<?php echo $genre ?>" name="music[<?php echo $genre ?>]" max="3" min="1" /><?php echo $genre ?><br />
<?php
}
}
?>
<input type="submit" name="button" id="button" value="Submit" /></form>
page 3
<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];
//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );
/*
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
echo "$music is your $rank choice";
echo "<br>";
}*/
foreach($musicgenres as $music => $rank)
{
array_push($musicstring, $music);
echo "$music is your $rank choice";
echo "<br>";
}
$musicstring = implode(", ", $musicgenres);
echo $musicstring;
?>
add a class to the inputs i will use the class test
and i'm using jquery so add the jquery library before add the code
$(document).ready(function(){
$('.test').change(function(){
var theinput=$(this);
var value=theinput.val();
$('.test').each(function(){
if($(this).val()==value){
theinput.val('');//to remove the value
alert('you choose a duplicate');//notify the user why the value removed
}
});
});
});

Categories

Resources