Jquery - How to get current input value from a repeating from - php

I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.

To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.

You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();

try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)

Related

Sequential Order of Checkboxes Selected PHP

At the moment, my html code is:
<form id = "query" method = "post" action = "search.php">
<input type = "checkbox" name = "col_list[]" value = "host">host</input>
<input type = "checkbox" name = "col_list[]" value = "atom_name>atom_name</input>
…
<input type = "submit">Submit</input>
</form>
And my php code:
$columns = $_POST["col_list"];
Is there any way is which I can get the sequence in which the checkboxes where checked?
you'd need to add a some javascript to get that info.
<input type="hidden" name="order"/> <!-- goes inside the form -->
Here is an examply using jQuery:
$('[name*="col_list"]').change(function(){
if ($(this).prop('checked')){
$('[name="order"]').val($('[name="order"]').val()+','+$(this).val())
}
});
This should work fairly well with one caveat:
If the user un-checks then re-ckecks a checkbox it will be added to order twice.
order should result in something like:
,host,atom_name
Edit
Fixed some typos and here is a fiddle
If the order is important you will have to implement some form of JavaScript or AJAX and call it when the check boxes are checked. Forms do not track the order in which fields are filled. JavaScript is well suited to this because it can trigger at the time of the click.
An alternative to AJAX could be adding a hidden field element and using JS to store the order clicked. Then it would be passed when the form is clicked.

Sending SCROLLTOP javascript via Submit

I'm trying to submit a form after updating the value of a hidden field from a javascript variable.
This is the code:
<form name=form1 id=form1 method=get action=gestionale.php>
...
...
<input type=hidden name=scrolltop id=scrolltop value=''>
<input type=button name=update value=Update onClick=vai('form1');>
</form>
<script>
function vai(formid) {
document.getElementById('scrolltop').value=document.getElementById('offerte').scrollTop;
document.getElementById(formid).submit();
}
</script>
The form submit works correctly but $_GET[scrolltop] after form submission, is empty even if it was filled with javascript. And testing it with alert before submit shows the correct value.
Anyone knows why?
Thanks a lot.
In your script...
The line document.getElementById('scrolltop').value = document.getElementById('offerte').scrollTop;
What exactly do you intend to do with the last bit (('offerte').scrollTop)?
As far as I understand, you want to return a text value, however setting the value to this will not return anything.
You will need to parse the query string ($_GET variable) and assign that to a variable which you will then pass as the value for the hidden field.
If I'm being completely in the dark here, I'm sorry. You should include a bit more of your code or additional information if my answer seems far fetched.
Anyway, I hope this helps!
I found this:
function submit_form(formid) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "theName";
hidden.value = document.getElementById('offerte').scrollTop;
var f = document.getElementById("form2");
f.appendChild(hidden);
f.submit();
}
I submit the form using a javascript function instead of submit button.
Here I can set a hidden filed to a value I need in my action page.

Javascript to check for form data does not work

I have the following code to check for form data and I can't figure out why its not working.
<script type="text/javascript">
function checkStuff() {
// By default, we plan to submit the form.
var formOkay = 1;
// Check to see if field_1 has a value. If not, we note that by changing our variable.
if(document.getElementById('requestorfirstname').value == '')
formOkay = 0;
// Let the user know something is wrong somehow. An alert is easiest.
alert('Requestor Name Required!');
// If you return true the form will submit. If you return false it will not.
if(formOkay == 1) {
return true;
} else {
return false;
}
}
</script>
Now here is the html form piece its checking onsubmit.
<input type="text" name="requestorfirstname" />
Thanks for the help!
document.getElementById looks for elements by ID. Your field doesn't have an ID, it has a NAME.
document.getElementById selects an element by id, not by name.
Some ways to solve the problem:
Add id="requestorfirstname" to the input element.
Use document.getElementsByName('requestorfirstname')[0]. getElementsByName returns a list, hence [0].
Use the document.querySelector('[name="requestorfirstname"]') method.
Get a reference to the form, and access the element using the .elements collection.For example, if your page has only one form:
document.forms[0].elements['requestorfirstname']
A name attribute on an HTML element is NOT the same as an id. You have no id on your input field, so there's no way for getElementById to find it. Change the element to:
<input type="text" name="requestorfirstname" id="requestorfirstname" />
^^^^^^^^^^^^^^^^^^^^^^^^ - add this

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

Use jQuery to add form fields and PHP Sessions to remember the fields were added

I am creating a multi-paged form and now i am consulting the Stack guru's for some assistance;
On this page the user can add more input fields [type=text] onto the page
So basically there is a singular input for "CHILD NAME" then a Add button to allow the user to add more children if they have more than one.
My form allows you to go backwards and forwards, the form remembers what was input, how would i get jQuery and php to remember that the form fields were added so they are not hidden when the user re-vists the page ?
well with adding inputs you can do:
$('form').append('<input>',{type: 'text', name: 'input_name'})
and you can save previous parts of the form data with php $_SESSIONs
example of a form:
in php you will get all the post (or get) values:
$_POST = array ('name1' => 'me', 'name2' => 'you' )...
and then you can save those in a session with:
$_SESSION['lastpostedvalues'] = $_POST;
or something like that.
remember to have session_start() at the top of the php file
try this if it helps
html code
<span>
<span id="childs"></span>
<input type="text" id="testid" />
<input type="submit" id="submit" value="Add" />
</span>
jQuery ---
$(document).ready(function(){
$('#submit').click(function(){
$('#childs').append(''+$('#testid').val()+'<br />');
$value=$('#testid').val();
$.get('somePHPCodewhichaddsToSession.php',{
data:$values
},function(data){
//some staff after the session is add
});
});
});
/*PHP code to add the sessions*/
if(isset($_GET['data'])){
$_SESSION['AnyName']=$_GET['data']; //this could be an array to hold all the childern names
if(isset($_SESSION['AnyName']))
echo true; //handle this return in your ajax call oncomplete callback
else
echo false;
}
/* PHP code to dispaly the childrens*/
//get the array from the session
if(isset($_SESSION['AnyName']){
get the values and display or do something with them
$values= $_SESSION['AnyName']
}
** Make sure to format the html to fit your needs
http://jsfiddle.net/tsegay/5VhVp/

Categories