Selecting a checkbox in html table containing handlebar, expressjs - javascript

I have a html table in a form in which the rows of table are populated using handebars. I want to select some rows of the table using checkbox. The form makes a post request. I am using express.js framework for the same. The requiremment is that when the form is submitted the json should have a field named 'checked' which should have value true or 1 if the row was selected. Please help me in solving the issue.
Following is the snippet of the html
<form id='form1'>
<table border="1">
{{#each ElectrnicsResults}}
<tr>
<td>{{Product}}</td>
<td>{{Description}}</td>
<td>{{price}}</td>
<td>{{quantity}}</td>
<td>
<input type='checkbox' id="check">
</td>
<td style="display:none">
<input type="hidden" name="electronicsId" value="{{electronicsId}}" />
<input type="hidden" name="Product" value="{{Product}}" />
<input type="hidden" name="Description" value="{{Description}}" />
<input type="hidden" name="price" value="{{price}}" />
<input type="hidden" name="quantity" value="{{quantity}}" />
</td>
</tr>
{{/each}}
</table>
<input type="submit" value="submit" >
</form>
Following is the javascript code using JQuery
$(document).ready(function () {
$('#form1').submit(function() {
$.ajax({
url: '/submitValues',
type: 'post',
dataType: 'json',
data: $('#form1').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
return false;
});
});

Since the form is created dynamically, you'll have to parse the results dynamically as well.
First, you'll want to attach a name field to each input type=checkbox element. This name needs to be unique to each ElectrnicsResults (perhaps something like the ID field).
Then, in your backend code when parsing the form details, you'll can again loop through each relevant ElectrnicsResults and check the req.body.{UNIQUE_NAME_FIELD_VALUE} for each checkbox, and act accordingly.

Related

Unable to submit data from php jquery page posting data to another page

I'm creating a php form using jquery. Trying to dynamically add rows and then submit to another page which inserts the data.
It is a store inventory form to supply multiple products in a single form rather than adding one product and going over the process back again. I have another form to submit same data which inserts single row of data and it works fine.I am trying to improve the same. If I comment out add row & delete row functions, submit works but for only one row. Vice versa, if I comment out submit button & function, I can dynamically add & delete rows. How to post data for multiple rows by connecting ajax to php for posting data is not clear. Also I need to post attached file which will be in pdf format for input id=Annexure.
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<form action="insert_indents.php" method="post" name="indform" id="indform">
<label for="Part_No">Part No.:</label>
<input type="text" id="Part_No" name="Part_No" placeholder="Part No">
<label for="Part_Make">Part Make:</label>
<input type="text" id="Part_Make" name="Part_Make" placeholder="Part Make">
<label for="Annexure">Attach File:
<input type="hidden" id="MAX_FILE_SIZE" value="30000" />
<input id="Annexure" name="Annexure" type="file" class="form-control" style='width:20em'/>
</label>
<input type="button" class="add-row" value="Add Row">
<input type="button" id="Submit" class="ind-row" id ="Submit" value="Submit" onclick="add_indent_details()" />
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>Part No</th>
<th>Part Make</th>
<th>Attached File</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
<script src="js/jquery-1.4.1.min.js"></script>
<script src="js/ajax.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
var Part_No = $("#Part_No").val();
var Part_Make = $("#Part_Make").val();
var Annexure= $("#Annexure").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + Part_No +"</td><td>" + Part_Make +"</td><td>" + Annexure+ "</td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
<script>
$(document).ready(function(){
$("#Submit").click(function(){
var Part_No = $("#Part_No").val();
var Part_Make = $("#Part_Make").val();
var Annexure= $("#Annexure").val();
$.ajax({
url:'insert_indents.php',
type :'post',
data :{Part_No:Part_No,Part_Make:Part_Make,Annexure:Annexure},
datatype :'text',
success:function(data)
{
alert(data);
}
});
}
}
</script>
</body>
</html>
I want to insert the data along with attached file into my database posting this data to a different page which contains insert query.
Thanks for your help.
I'm a newbie to PHP & ajax.

Submitting two different forms with an external Submit button not working properly

I am creating a add to cart program and need to add product with its attribute(colors, size) to the cart and for that I need to submit both the forms together. I am not sure where am I going wrong here I have created the scripts but it submits only the first form selected for submit() using jquery but not the other form.
Given below is my code with Snippet and this is the JSFIDDLE
$(document).ready(function (){
$('#cart').click(function (e1) {
var $form = $('#masterform');
var $formcolor = $('#colorform');
var $checkbox = $('.roomselect');
var $checkboxcolor = $('.colorselect');
if (!$checkbox.is(':checked'))
{
$('#tipdivcontent').css("display", "block");
$("#tipdivcontent").delay(4000).hide(200);
e.preventDefault();
}
else
{
if (!$checkboxcolor.is(':checked')) {
$('#tipdivcontentcolor').css("display", "block");
$("#tipdivcontentcolor").delay(4000).hide(200);
e.preventDefault();
} else {
$form.submit();
$formcolor.submit();
}
}
});
});
#tipdivcontent
{
border:1px solid black;
margin-top:0px;
background-color:white;
height:50px;
width:102px;
display:none;
position:relative;
background-color:red;
color:yellow;
font-weight:bold;
}
#tipdivcontentcolor
{
border:1px solid black;
margin-top:0px;
background-color:white;
height:18px;
width:292px;
display:none;
position:absolute;
background-color:red;
color:yellow;
font-weight:bold;
}
<form action="" method="POST" id="masterform">
<table border="1" cellspacing="0">
<tr>
<th colspan="4">Sizes</th>
</tr>
<tr>
<td>
<label for="2.2">2.2</label>
</td>
<td>
<input class="roomselect" type="radio" id="2.2" name="size" value="twopointtwo">
</td>
<td>
<label for="2.4">2.4</label>
</td>
<td>
<input class="roomselect" type="radio" id="2.4" name="size" value="twopointfour">
</td>
</tr>
<tr>
<td>
<label for="2.6">2.6</label>
</td>
<td>
<input class="roomselect" type="radio" id="2.6" name="size" value="twopointsix">
</td>
<td>
<label for="2.8">2.8</label>
</td>
<td>
<input class="roomselect" type="radio" id="2.8" name="size" value="twopointeight">
</td>
</tr>
<tr>
<td colspan="3" align="center">
<label for="2.10">2.10</label>
</td>
<td>
<input class="roomselect" type="radio" id="2.10" name="size" value="twopointten">
</td>
</tr>
</table>
</form>
<div id="tipdivcontent">Please Select Size.</div>
<input type="submit" value="To Cart" class="cartorcheckoutbutton" id="cart">
<form action="" method="POST" id="masterform">
<table border="1" cellpadding="2">
<tr>
<th colspan="8">COLORS</th>
</tr>
<tr>
<th title='White' style='background-color:white;' height='15' width='20'>
<input type='radio' name='color' class="colorselect" value='white'>
</th>
<th title='Red' style='background-color:red;' height='15' width='20'>
<input type='radio' name='color' class="colorselect" value='red'>
</th>
<th title='Green' style='background-color:green;' height='15' width='20'>
<input type='radio' name='color' class="colorselect" value='green'>
</th>
<th title='Blue' style='background-color:blue;' height='15' width='20'>
<input type='radio' name='color' class="colorselect" value='blue'>
</th>
</tr>
</table>
</form>
<div id="tipdivcontentcolor">Please Select Color.</div>
You could try assigning the color inputs from the secondary form to your 'master' form. Simply using <input form='formID' ...> on any input would assign that input to the other form regardless of where it is on the page.
// When the 'master' form is submitted...
$("#masterForm").on("submit", function(e) {
"use strict";
// Stop the default action
e.preventDefault();
if ($("input[type='radio']:checked").length === 0) {
alert("You must check at least one color option.");
return false;
}
// *for logging*
// write the contents of the submitted data
$("p").html("submitted data: " + $(this).serialize());
console.log("submitted data: " + $(this).serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="masterForm">
<input name="someField" type="text" value="test value">
</form>
<form id="anotherForm">
<label>
<input name="color" type="radio" value="blue" form="masterForm">Blue
</label>
<label>
<input name="color" type="radio" value="red" form="masterForm">Red
</label>
</form>
<!-- Submit button outside of the form -->
<button type="submit" form="masterForm">Submit</button>
<p></p>
If the above option (and attached snippet) wouldn't work for you, try appending your formData with the relevant fields. Something like this (untested):
// When the 'master' form is submitted...
$("#masterForm").on("submit", function(e) {
"use strict";
// Stop the default action
e.preventDefault();
var submissionData = $(this).serialize();
submissionData += "&color=" + $("#slaveForm").find("input[name='color']:checked").val()
// do stuff ...
});
A form is a set of data to be sent via a POST request (or GET). What you are asking for makes no sense. If it is possible then you still shouldn't do it. Whatever HTML and CSS issues are making you split the form then I recommend you put that as your actual problem here.
Submitting a form, unless it has a target attribute pointing to a frame or other window, will cause an HTTP request for a new page to be made.
Submitting two forms at the same time would be like following two links at the same time. It can't be done.
You need to either:
Refactor your code so it uses a single form. This would almost certainly make the most sense.
Add a pair of frames to the page and submit each form to a different one.
Collect the data for the first form with JavaScript, sent it to the server using Ajax, then (after you get the response back) submit the second form.
If you want to send multiple form as a single one i can suggest to use formData object (documentation https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects )
var formData = new FormData();
formData.append("size", $('input[name=size]:checked').val());
formData.append("color", $('input[name=color]:checked').val());
var request = new XMLHttpRequest();
request.open("POST", "yourformtarget");
request.send(formData);
A possible solution with javascript: you can add an attribute to locate all fields, and send the form by ajax:
<div id='masterform'>
<input name='field_1' data-field-of='form1'>
...
</div>
...
<div id='colorform'>
<input name='field_23' data-field-of='form1'>
...
</div>
The code in javascript can be something like this:
$(document).ready(function (){
$('#cart').click(function (e1) {
var data = $('[data-field-of=form1]').serialize();
$.ajax({
url: "post/url",
data: data,
type: "POST",
success: function(response){ /* handle success */ },
error: function(){ /* handle error */ }
});
});
});

How can I pass in this data into a form submit call (similar to data parameter for an ajax post)?

I have the following code that submits data to an asp.net-mvc controller action via jquery ajax
var queryString = "name=Joe&age=22&weight=200";
$.ajax({
url: '/MyController/Generate',
type: 'post',
data: queryString,
dataType: 'json'
});
this works fine and binds to the controller action parameter
public ActionResult Generate(MyParams p)
{
Console.Write(p.name);
Console.Write(p.age);
Console.Write(p.weight);
}
The issue now is that I need to change this from ajax to being a regular form post (I need to use regular form post as I am now returning a file from the controller action). I am trying to figure out how I can get that same querystring variable to get submitted as part of a regular form post (non ajax).
Is this possible?
try with html.beginform
#using (Html.BeginForm("Generate", "MyController","name=Joe&age=22&weight=200", FormMethod.Post, new { id = "frmMyForm" }))
{
// Your form elements
}
If you want that data to be fixed you can make a form like this:
<form action="/MyController/Generate" method="post">
<input type="hidden" name="name" value="Joe" />
<input type="hidden" name="age" value="22" />
<input type="hidden" name="weight" value="200" />
<input type="submit" />
</form>
Otherwise, if you want the data to be editable, it goes like this:
<form action="/MyController/Generate" method="post">
<input type="text" name="name" />
<input type="number" name="age" />
<input type="number" name="weight" />
<input type="submit" />
</form>

Adding a item into a cart automatically using javascript

Hi i have a cart that i want to add a form automatically this code seems to kinda do the trick only the problem is i have to hit F5 for it to add the amount i am quite new to this and cant figure out where i have gone wrong.
<form method="post" action="level3.php" class="jcart" id="foo">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="ABC-8" />
<input type="hidden" name="my-item-name" value="Level 1" />
<input type="hidden" name="my-item-price" value="95.00" />
<input type="hidden" name="my-item-url" value="" />
<table>
<tr>
<td width="65%">
<strong>Level 1 all for £95</strong>
</td>
<td width="15%" align="right">
£95.00
</td>
<td>
<input type="text" hidden ="true" name="my-item-qty" value="1" size="3" hidden="true" />
</td>
<td width="20%" align="center">
<input type="submit" name="my-add-button" id="my-add-button" value="add" class="button" />
</td>
</tr>
</table>
<input type="hidden" name="visited" value="" />
</fieldset>
That is the form that submits the amount into the check out.
<script>
$(document).ready(function(){
//Check if the current URL contains '#'
if(document.URL.indexOf("#")==-1)
{
url = document.URL+"#";
location = "#";
} else {
location.reload(true);
document.getElementById("my-add-button").click();// Simulates button click this has to be in as it links to another piece of java that adds the item to the check out with out this it wont add the item
document.foo.submit(); // Submits the form without the button
}
});
</script>
document.getElementById("my-add-button").click();
The code above links to the code below that adds the items from to my knowledge
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
Thank you in advance for any help or suggestions
If i understand correctly, you increase some value of cart in PHP and than want to update quantity on page without refreshing page.
I made little JSFiddle: http://jsfiddle.net/7SbBA/
Basically use ajax:
$.ajax({
url: 'example.com',
data: /* pass product id here */
success: function(){
/* update quantity you want */
}
});
There is some html change too.
UPDATE
If you want updated total values on page load, just £<span class='amount'><?php echo $product['quantity'] * $product['price'] ?></span> and there is no need to use jquery/js for that. But if you still want dynamically update on window load, i updated my JSFiddle v.2

dataTables search messed up by input from another form

hello i have a form like this
<form id="ricerca" enctype="application/x-www-form-urlencoded" method="post" action=""><table class="inserisci_modifica">
<tr class="visualizza_dati">
<td class="nome_campo"><label for="ragsoc_denominazione">Ragione sociale o denominazione</label></td>
<td class="valore_campo">
<input type="text" name="ragsoc_denominazione" id="ragsoc_denominazione" value="" tabindex="1" /></td>
<td class="nome_campo"><label for="piva">Partita IVA</label></td>
<td class="valore_campo">
<input type="text" name="piva" id="piva" value="" tabindex="9" /></td></tr>
then i have an html table to which i apply dataTables
and then i have this code
$("#ricerca").submit(function(event) {
event.preventDefault();
oTable.fnClearTable();//Empty the entire table of current row information.
oTable.fnDraw();
});
the problem is when i type something in my form, it's as if it gets auto submited as dataTables's search field, and then i can see the same text in dataTables search field, i can't understand why
nevermind i find the bug, i am using a plugin, and in dataTableExt.oApi.fnSetFilteringDelay
i had to change
anControl = $( 'input', _that.fnSettings().aanFeatures.f );
to
anControl = $( 'table.dataTables input', _that.fnSettings().aanFeatures.f );

Categories