I have an HTML form in my website/application.
The form has lots of fields of input text, select, and PHP code, as well, to fill drop down values.
Is there any way I can clone/create the same form when the user clicks on the Add button? Let's say, if the user clicks 5 times, it would have five forms on the UI.
HTML
<form id = "buyerForm" role="form" method="POST" enctype="multipart/form-data" style="margin-top:30px;">
<span class="customerno" style="font-size: 22px;">Buyer 1 (Form 2)</span>
<div class="form-group">
<label>APPLICANT DETAILS</label>
</div>
<div class="form-group">
<label>Mr. / Mrs</label>
<select class="form-control" name="jnameTitle" id="jnameTitle">
<option>Please Select One</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="MS">MS</option>
</select>
</div>
// similar fields are omitted to reduce the complexity
<div class="form-group">
<label>Address</label>
<textarea name="jaddress" id="jaddress" class="form-control" cols="80" rows="5" ></textarea>
</div>
<button type="submit" name="jointCustomers" id="jointCustomers" class="btn btn-success btn-lg btn-flat">Save</button>
<button type="reset" class="btn btn-default btn-lg">Reset</button>
</form>
if you're using jQuery (or dont mind using it) you could just use clone to add the form again to the parent container
$("#youButton").click(function(){
$("#buyerForm").clone().appendTo("#yourParentWrapper");
});
see this fiddle
Yes, there is a way.
Lets say you have the main page -> mainPage.php, where you can have a list and the button (addForm).
Then you will have your myform.php page that will generate a form it self.
The process is very simple.
You press the btn AddForm
You make a request using AJAX against your function that generate the form in the myform.php page.
Inside your AJAX code, you will add your form inside the list object.
Note: This is only a basic idea. You must adapt the code to your needs.
//Your main page, will contain a list.mainPage.php
<ul id="myFORMS">
<li><button id="idBtnElement" type="button">AddForm</button></li>
</ul>
//Your php code to create the form. You can create a function if you want
$arrToJSON = array(
"myFormHtml"=>"You will put your HTML form code here"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idBtnElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_ADDFORM"
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "myFormGenerator.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
formStrHtml=dataset[index].myFormHtml;
}
//JavaScript
//Here you can grab formStrHtml in apped at the end of the list in your main page.
$("#myFORMS ul").append('<li>'+formStrHtml+'</li>');
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
Related
I have an html page which has around six different forms with different somewhat unrelated fields in each form. What I'm trying to do is create a single jquery or javascript function to handle all the Fetch() on form submit without knowing the form ID (which is most of what I found in tutorials online). Right now I'm just trying to get the form data to display in an alert, but the alert is always blank (no form data being passed?).
My code for what I think should capture any form submit and display the form data:
<script>
$(document).ready(function() {
$("form").on("submit", function(e) {
console.log("CCCCCCC in script CCCCCCCCCc")
e.preventDefault();
var dataString = $(this).serialize();
alert(dataString);
return false;
});
});
</script>
I have a couple of these type of forms (took out bootstrap class info for ease of reading:
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="thing2">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
How can I get any of the form data into the alert box? Ideally later I will use fetch() after I massage the input string.
The form doesn't have any serializable data.
A form control's data comes from a combination of its name and value but none of your form controls have name attributes.
As #Quentin suggested, you need to give a name to select and input elements, in order to get their values.
For instance:
$('form').submit(function(e) {
e.preventDefault();
var el_1 = this.thing1;
var el_2 = this.inputtext;
alert(el_1.value + ', ' + el_2.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form>
<div>
<div>
<label for="thing1">Choose:</label>
<select id="thing1" name="thing1">
<option value="XXX">XXX</option>
<option value="YYY">YYY</option>
</select>
</div>
<div>
<label for="inputtext">Command</label>
<input type="text" id="inputtext" name="inputtext">
</div>
<div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:
I have the following code:
For the Submit button
<form method='POST'>
<div class="form-group">
<input type="text" name="s_amount" style='width:20%;' required>
<input type="submit" class="btn btn-primary" name="submit" value="Submit" />
</div>
</form>
<?php
$s_amount = $_POST['s_amount'];
echo $s_amount;
?>
AND for the Submit Code button
<button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
<pre><code id="output">.../...</code></pre>
When the Submit code is pressed, this executes the following script
<script>
$(document).ready(function(){
$("#submitcode").on("click", function(){
ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
//arguments
var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
//perform the request
var req = ocpu.call("identity", {
"x" : mysnippet
}, function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
});
});
})
});
</script>
What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.
Many thanks !
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.
<form method='POST'>
function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
// using form id call the form
$("#formdata").submit(); // it will simply submit the form.
});
});
<form method="post" id="formdata"> <!--assign id to form tag-->
</form>
Could finally do it very easily using js.
<input type="text" id="VTP" value="0">
and get the value in the javascript form
document.getElementById("VTP").value
# nikhil borikar: Thanks but it did not work
With a play view template I know I can convert a Scala List into a javascript Array e.g. for example.scala.html:
#(list: List[Any])
#import play.api.libs.json.Json
<script type="text/javascript">
$(document).ready(function () {
var jsArr = #Json.toJson(list);
console.log(jsArr);
});
</script>
but how does one go back the other way, converting a javascript array into a scala list to pass on to a controller?
I have template code (test.scala.html) like this:
#(selected: List[String])
#main("Test Scripts Page") {
<div class="page-header page-heading">
<h1 class="pull-left">Test Scripts Page</h1>
#helper.form(action = helper.CSRF(routes.DoSomething.create(selected))) {
<input type="submit" class="btn btn-primary pull-right" value="Done >"> }
<div class="clearfix"></div>
<p class="lead text-left">Choose Buttons</p>
</div>
#for(index <- 0 to 3) {
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary"><input type="checkbox" name="options" id="option-#index" aria-pressed="false" autocomplete="off" checked>option #index</label>
</div> <!-- buttons --> }
<input type="text" id="buttonvalue"/>
<script>
$(window).unload(function() {
var jsArray = []
$('.btn-group checkbox:selected').each(function() {
jsArray.push($(this).attr("id"));
});
selected = Json.fromJson(jsArray, String);
$("#buttonvalue").val(selected.text());
});
</script>
}
Which doesn't seem to be working... only returns an empty list [] to my DoSomething(List) controller... basically I'm trying to let the user set the state of some widgets (in my case a bootstrap button-grp, with the ids of the buttons being object ids of static reference data in my database) and then read that selection back into my DoSomething controller as a List of ids when they hit a "done" button. Can anyone offer some advice on what I've missed here or a better way to handle this situation?
When you load a page, this happens:
Your browser asks the server for a HTML page.
Your scala code is run on the server and generates a HTML page with some javascript on it.
The server sends the HTML page to the browser. The javascript code then runs in the browser and therefore can't talk to the server code (Scala).
To send data back to the server you can make an HTTP call e.g. to a REST endpoint that your server offers.
Ok. I have a solution for this.
My view template looks like this, with the Bootstrap button-grp tagged with "myButtons" (note: if you insert anything between the btn-group div and the label class buttons, JQuery doesn't seem to pick up the checked options), and an script with ajax call bound to the submitButton.
Test Scripts Page
">
Choose Buttons
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="checkbox" name="options" id="option1" autocomplete="off" checked> Box 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="checkbox" name="options" id="option2" autocomplete="off"> Box 2
</label>
<label class="btn btn-primary">
<input type="checkbox" name="options" id="option3" autocomplete="off"> Box 3
</label>
</div>
<script>
$('#submitButton').click(function(e) {
var selected = $( "#myButtons :checked" ).map(function() {
return this.id;
}).get().join();
var selections = JSON.stringify({ 'selected' : selected });
$.ajax({
type : "POST",
dataType: 'json',
data: selections,
contentType: "application/json; charset=utf-8",
url : "#routes.Application.getSelection()",
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
my controller then picks up the selection via the AJAX post thus:
public static Result getSelection()
{
JsonNode json = request().body().asJson();
if( json == null)
{
Logger.info("Expecting JSON!");
return badRequest("Expecting Json data!");
}
else
{
String selection = json.findPath("selected").textValue();
if (selection == null)
{
Logger.info("Missing Parameter: selected");
return badRequest("Missing Parameter: selected");
}
else
{
Logger.info("selection = " + selection);
String[] ids = selection.split(",");
}
}
return ok(modaltest.render());
}
in my application code, those selections map to object ids in a model stored in my database, and then can be re-used in a subsequent request.
The only issue now is that the final return Request of my getSelection() controller (i.e. another GET to render a new page with a form) doesn't get invoked. No idea why yet. Probably something to do with the Ajax POST.
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I am searching a table for specific values based on the user input which queries the database for the LIKE condition. This works perfectly but I have to manually scroll to the buttom of the page to see my filtered table. I really want to redirect the user to the div of the table underneath the page. This is the form with the search box:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" type="submit" value="Submit">Go!</button>
</span>
</div>
</div>
</form>
This code below then checks to see if the button is clicked and then sets the variable that populates the table to equals the current search result from the database.
var searchIP = "";
if (Request.Form["searchnow"] != null & IsPost)
{
searchIP = Request.Form["search"];
alertForTheDay = dbConnection.searchDashboardTable(searchIP);
// Response.Redirect("Dashboard.cshtml#search");
}
Using Response.Redirect refreshes the table back to its original state. Commenting out the Response redirect as shown above allows the filter to be possible but I have to manually scroll down the page. I want this to redirect to the id of the div in that redirect. Please what can I do?
I guess you are doing a complete server round trip. From my point of view this is unnecessary.
I would suggest to do this via AJAX.
Change the HTML like this to call an AJAX operation on your button click:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" id="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" id="theButton">Go!</button>
</span>
</div>
</div>
</form>
Handle the button click and link to your anchor on success. (Assuming that the anchor to your table is present. In your case something like Dashboard.cshtml#contact)
$.fn.gotoAnchor = function(anchor) {
location.href = this.selector;
}
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#theButton").click(function() {
$.ajax({
type: "POST",
url: "<YOUR URL>",
data: { search: $('#search').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// If everything is successful link to your anchor tag
$('#search').gotoAnchor();
}
});
});
});