I use
$('.test').attr('data-payment', 'value');
to create a custom attribute for
<table class="test" data-payment="value">
further down the table I have
<td class="outlay">100</td>
The table is outputted using a PHP script, it is a sort of calculator that updates when form fields are changed and a button is clicked.
My question is how to insert the contents of .outlay into the data-payment value?
You can do something like this
$('#button').clicked(function(){
var val = $('.outlay').text(); // Store content in val variable
$('.test').attr('data-payment', val); // change data-payment value
})
If you're using data-attributes, you can use things like:
$('.test').data('payment');
In your case, you'll want something like:
var outlay = $('.outlay').text();
$('.test').data('payment', outlay);
Related
assuming that i have an HTML textbox with a name with an array:
<input type="hidden" id="text_array" name="text_array[]" class="test">
and i have a jquery code that gets the data on the textbox:
$('.test').each(function(){
arr = $(this).val();
});
how can i get the array content and transfer it into another laravel view and then print it? i tried to get it by using echo my controller but i have recieved comments about printing outputs in a controller is a bad practice.
Hmm i would recommend to use a Database or Session storage. But one idea is to save the value via JavaScript into a cookie.
Disclaimer: Untested ;)
Save the Value:
$('.test').each(function(){
arr = $(this).val();
document.cookie = 'mycookie=' + arr +'expires=DateHere;path=/'
});
Get it (somewhere):
$value = $request->cookie('mycookie');
I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.
I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.
The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.
If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
I have an admin page where I add and delete table rows on the fly.
The page comes loaded with the existent data in the database (mostly consisting in a sku_code and 5 different prices) but when I add rows on the fly, and fill them with the corresponding skus and prices, I want to save them as well in the database.
The problem is that what I do on the client-side with Javascript (add table rows on the fly) with innerHTML = '<input type="text"> is not accesible via $_POST variables of the main <form>
So basically i add via Javascript 's so i can fill them and save them as well in the database. But the $_POST values are empty.
Javascript code works fine. I have no clue where should i start debugging.
here's some Javascript code i'm using
function insert_record(){
var my_table = document.getElementById('my_table')
var tr = my_table.insertRow(my_table.rows.length-1)
//id-ul curent, numar toate row-urile - 1 (care este butonul OK)
var c_id = my_table.rows.length-2
tr.id = 'row_' + c_id + ''
var tr_td_1 = tr.insertCell(0)
tr_td_1.className = 'text2'
tr_td_1.align = 'center'
tr_td_1.innerHTML = 'SKU'
var tr_td_2 = tr.insertCell(1)
tr_td_2.className = 'text3'
tr_td_2.width = '63'
tr_td_2.innerHTML = '<input name="sku_' + c_id + '" type="text" id="sku_' + c_id + '" size="33" value="">'
....this addes a inside the table just before the last which contains the submit button, after which there's the
You need to assign a label to element. Then you can grab it in next page.
Instead of innerHTML = <input type="text"> try to use
<script>
function addElement(tag_type, target, parameters) {
//Create element
var newElement = document.createElement(tag_type);
//Add parameters
if (typeof parameters != 'undefined') {
for (parameter_name in parameters) {
newElement.setAttribute(parameter_name, parameters[parameter_name]);
}
}
//Append element to target
document.getElementById(target).appendChild(newElement);
}
</script>
You can call this function below either click of even or manually addElement('INPUT','targetTag',{id:'my_input_tag', name:'my_input_tag', type:'text', size:'5'});
you should give the name attribute. if you are worried about the unlimited numbers of fields just go for the array of the input variables,
like this
<input type="text" name="field1[]">
Now you can access them in post like this:
$_POST['field1'] //this is an array of fields
EDIT:
First thing is that you should use some library like jquery which eases the work.
I suggest you make sure your all your fields are inside the form and that you have named all of them instead of trying ajax or functions like #shail suggested.
In my opinion they are not solving the problem, just avoiding it.
Using some code to create a form dynamically which I got here: http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm
This works great. However I have a regular html table I generate with html/php to get data out of a DB. I want to replace that data with a form so when users click the edit button the original entry is replaced with a form (either textbox or pull down menu). The user makes a selection and the new table comes back with the appropriate edit.
So for example one part of the data has this in the table:
<td><?php echo $result[0] ?></td>
Using the link about to create a form dynamically I change this to:
<td id="paraID"><form id="form1" name="form1" method="post" action enctype="text/plain" alt=""><?php echo $result[0] ?></form></td>
Also note the onclick event for the edit button:
This is hard to explain but hoping someone can help me with this interaction. I need some way to say:
if (user clicks edit button)
then
replace html table with form for each entry (for example, the table returns a name called foo and a textbox will appear with foo in it but now they can edit to change the name).
If you can start out with an id for the td then it will make things easier. Then you will need an edit button somewhere. Notice: It might be nice to replace "result_0" with the name for the value/field:
<td id="result_0_parent"><?php echo $result[0] ?><input type="button" onClick="editField('result_0','select')" value="Edit" /></td>
Then in your javascript you will have the editField function defined so that it sets the content of the td to be the dynamic form. Looking at makeForm function in the example javascript, you see this happening with appendChild(myform); The function editField will be like the makeForm function except you will pass in the field_id and field_type as parameters:
function editField(field_id, field_type)
I suggest you change the line that defines mypara to define mytd or better yet, field_parent instead since in your case it will not be a paragraph element, but a td (or possibly some other type of element):
field_parent = document.getElementById(field_id+"_parent");
The example code create a select (dropdown), but I am guessing you want to create other field input types so I recommended having field_type as a second parameter to the function. This means that it would make more sense for your implementation to use myfield instead of myselect and then use the field_type parameter to decide what myfield will be.
Replace the line in the makeForm / editField function:
myselect.setAttribute("id","selectID");
with
myfield.setAttribute("id",field_id);
One more thing: To set the initial value of the input field to be the displayed content, you will need to copy the "innerHTML" of the "parent" element. So place something like this right after defining field_parent:
initial_value = field_parent.innerHTML;
and I think you can figure out the rest. If not, I can elaborate a little more.
This works great. However I have a regular html table I generate with
html/php to get data out of a DB. I want to replace that data with a
form so when users click the edit button the original entry is
replaced with a form (either textbox or pull down menu). The user
makes a selection and the new table comes back with the appropriate
edit.
This is a script that allows with a double click on values to edit them and has a button to send them back. Maybe it would be of some help to use it (or use parts of it).
<?PHP
if(count($_POST)>0)
{
echo 'You gave:<br><per>';
print_r($_POST);
echo '<a href=http://localhost/temp/run.php>Start over</a>';
exit;
}
?>
<html>
<head>
<script type="text/javascript">
/**formEditor Class
*/
function formEditorCls( )
{
/**
Constructor simulator
*/
this.lastFieldEditedId = null;
/** Change span with input box, hide the eddit button and store theses IDS
*/
this.edit=
function (field)
{
//if there was a field edited previously
if(this.lastFieldEditedId != null)
this.save();
//get the inner element of the div, it can be span or input text
var childElem = document.getElementById(field).getElementsByTagName('*')[0];
//then replace the span element with a input element
document.getElementById(field).innerHTML="<input type=text name=n_"+field+
" id=id_"+field+" value="+childElem.innerText+">";
//store what was the last field edited
this.lastFieldEditedId =field;
}//func
this.save=
function ()
{
dbq="\"";sq='\'';
//get the last value
var lastValue = document.getElementById(this.lastFieldEditedId).
getElementsByTagName('*')[0].value;
//store it as span
document.getElementById(this.lastFieldEditedId).innerHTML="<span ondblclick="+dbq+
"formEditor.edit("+sq+this.lastFieldEditedId+sq+");"+dbq+" >"+lastValue+"</span>" ;
//now must reset the class field attribute
this.lastFieldEditedId=null;
}//func
this.submit=
function (path)
{
this.save();//if ay field was edited put new values in span elements
var form = document.createElement("form");//create a new form
form.setAttribute("method", "post");
form.setAttribute("action", path);
var myDiv = document.getElementById( "fieldsDiv" );//get the div that contains the fields
var inputArr = myDiv.getElementsByTagName( "SPAN" );//get all span elements in an array
//for each span element
for (var i = 0; i < inputArr.length; i++)
{
var hiddenField = document.createElement("input");//create an input elemet
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", i);
hiddenField.setAttribute("value", inputArr[i].innerText);
form.appendChild(hiddenField);//append the input element
}
document.body.appendChild(form);//append the form
form.submit();//submit the form
}//func
}//class
formEditor = new formEditorCls( );
</script>
</head>
<body onclick="rt();">
Double click any value to change it..<br><br>
<div id="fieldsDiv">
Name:<font id="nameField">
<span ondblclick="formEditor.edit('nameField');" >Mark</span>
</font><br>
Surname:<font id="surnameField" >
<span ondblclick="formEditor.edit('surnameField');">Smith</span>
</font><br>
</div>
<input type=submit name="submit"
onclick="formEditor.submit('http://localhost/temp/run.php');" value="Submit">
</body>
</html>