Get values submitted to php from form - javascript

Consider the following form:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo">
<input type="checkbox" value="1" name="foo">
</form>
When submitting the form, the URL ...?foo=0 will be requested if the checkbox is not checked. If the checkbox is checked, the URL ...?foo=0&foo=1 will be requested. In PHP, query string arguments override any previous arguments with the same name, so foo will have the value 1 in the PHP script handling the latter request.
What is the best way to obtain the value foo would have in the PHP script using JavaScript, when not knowing anything about the form? In theory, there could be an arbitrary number of inputs named foo of different types, and I would like to know the value that foo would have in the PHP script handling the request if the form was submitted.
As I understand it, the answer is the value of the last enabled input element named foo. By enabled, I mean that the input element is not disabled and that it is not a button (the button's name and value are not added to the query string unless the button is used to submit the form) or an unchecked checkbox or radio button.
Maybe there is an easy way to get this value using jQuery?
Edit
Loads of people suggest that I rename the input elements to foo[] or similar. I guess I was not clear enough that I actually want all the input elements named foo, and to only receive one of the values in the php script.
My questions is how to determine which value the php script will receive using JavaScript.

use this:
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
and in PHP, use:
$params = $_GET['foo']; //params would hold array
it would be good to use.

You can do a loop on the global variable $_GET
foreach($_GET as $key=>$val) {
echo "key = $key , val = $val";
}
if you have multiple inputs with the same name you will need to append []to the name so you can get all the values as a array
<form method="get" enctype="multipart/form-data">
<input type="hidden" value="0" name="foo[]">
<input type="checkbox" value="1" name="foo[]">
</form>
to get the values in jquery you do the following:
$('input[name="foo[]"]').each(function(){
console.log($(this).val());
});
if you only want one value of foo but you have multiple elements with that name you will need to change your logic to using radio buttons

This is really bad design. You should check checkbox state in your php (backend) code. Get rid of the hidden input:
<form method="get" enctype="multipart/form-data">
<input type="checkbox" value="1" name="foo">
</form>
and put this in your php code:
if (isset($_GET['foo'])) {
$foo = 1;
} else {
$foo = 0;
}
If you want to use javascript, you can try this on form submit:
var checkboxValue = $("input[name='foo']").prop("checked");
checkboxValue would be true or false depending on checkbox status.

Related

Get checked elements outside of submitted form with HTML

I have a web page, at the top is a set of radio buttons and a submit button. Here is the code for that:
<form action="/batch" method="POST">
With checked selection you may:
<input type="radio" name="bulk" value="broadcast">Broadcast</input>
<input type="radio" name="bulk" value="unbroadcast">Unbroadcast</input>
<input type="radio" name="bulk" value="delete">Delete</input>
<input type="submit" value="Run batch on checked items" />
</form>
Below that i have a table consisting of a bunch of rows with checkboxes at the beginning. Code for that is:
<td><input type="checkbox" name="{{ md5_name }}" class="box"/></td>
Is there a way to have the form submit a list of what the checkboxes are and whether they're checked regardless of the fact that the checkboxes are not within the form? Perhaps naming it the same or shared class?
While searching around before posting i found the following snippet from this page which looked promising, but i don't know how running it alongside my POST method would work, or how i would include the result in my POST method.
function getRadioValue (theRadioGroup)
{
for (var i = 0; i < document.getElementsByName(theRadioGroup).length; i++)
{
if (document.getElementsByName(theRadioGroup)[i].checked)
{
return document.getElementsByName(theRadioGroup)[i].value;
}
}
}
You could, in the HTML 5 doctype, simply associate those form-elements with a specific form, using the form attribute:
<td><input form="formElementID" type="checkbox" name="{{ md5_name }}" class="box"/></td>
This attribute:
Indicates the form that is the owner of the element1
References:
MDN: HTML Attribute reference.
Bibliography:
HTML forms reference.
You could bind a function to the submit method of the form to retrieve the values of the checkboxes, and add them into hidden fields in the form.
Alternately add the default values of the checkboxes to hidden fields, and bind a change method to the checkboxes to update the hidden field.

value is not set after the form is submitted

I m trying to insert user's check in value into db. For this i call the function and set the hidden field's value and than trying to submit the form but here after the form is submiteed hiden field's value is reset .
HTML Code
<form name="checkinout" action="logindetails.php" method="post" enctype="multipart/form-data" id="checkinout">
<table class="login-detaills" width="100%"><thead><th></th><th>Check In</th><th>Check Out</th><th>Hours</th></thead>
<tr><td></td><td></td><td></td><td></td></tr>
</table>
</fieldset>
<table>
<tr><td><input type="button" onClick="call()" value="checkin"></button></td><td><input type="button" id="logout" onclick="call2();" value="Check Out" ></td></tr>
<tr><td><input type="hidden" id="checkin" name="checkin"></td><td><input type="hidden" id="checkout" name="checkout"></td></tr>
</table>
</form>
Javascript
function call(){
$('#checkin').val("checkin");
$('#checkinout').submit();
}
function call2(){
$('#checkout').val("checkout");
$('#checkinout').submit();
}
PHP CODE
if(isset($_POST['checkinout']) ){
if(isset($_POST['checkin']) && $_POST['checkin']=='checkin'){
$sql = "INSERT INTO attend (loginout,log_type,fk_userid) VALUES ('".TODAY_DATETIME."','I','".$_SEESION['user_id']."')";
}elseif(isset($_POST['checkout']) && $_POST['checkout']=='checkout'){
$sql = "INSERT INTO attend (loginout,log_type,fk_userid) VALUES ('".TODAY_DATETIME."','O','".$_SEESION['user_id']."')";
}
$stmt = $class->dbh->prepare($sql);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
}
first of all its not satisfied this if(isset($_POST['checkinout'])
<input type="hidden" id="checkout"> has no name attribute, so even if you give it a value, it won't be a successful control and won't be submitted.
If you want $_POST['checkout'] to be populated, you need an element with name="checkout".
You dont have name attribute defined in you code ..For using $_POST['checkout'] you must have <input type="hidden" id="checkout" name="checkout">
It looks like you're checking if the post value $_POST['checkinout'] is set, but I dont see that form control anywhere. The only controls I see are these:
<input type="button" onClick="call()" value="checkin"></button>
<input type="button" id="logout" onclick="call2();" value="Check Out" >
<input type="hidden" id="checkin" >
<input type="hidden" id="checkout">
Like #Quentin said, they don't have a name attribute so they won't show up in the $_POST array after submission in any event, so that's another thing you must fix.
I think you're most likely assuming that, since the form id is checkinout, that the index $_POST['checkinout'] will be set upon form submission. This is not the case; only form controls (inputs, selects, checkboxes, buttons, etc.) will populate data inside of $_POST and the key inside of the $_POST array will be set equal to the value of the name attribute of the form control.
you really should consider using two submit button with your from, take a look at this question, and remove the hidden input and all the unnecessary js code

Setting the value of multiple inputs with the same id using jQuery?

Considering the following HTML:
<form id="upvoteForm" method="post" action="/post/upvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<form id="downvoteForm" method="post" action="/post/downvote">
<input type="text" name="post_id" id="post_id"/>
</form>
<input type="hidden" id="_postid" value="1"/>
I'm trying to set the two input fields with the name post_id to to value from _postid using this JavaScript and jQuery:
$(document).ready(function() {
$('#post_id').val($('#_postid').val());
});
However, as you can see in this jsFiddle, it's only setting the value of the first one. How do I set the value of both of them? I thought the selector would end up grabbing both.
Now, I realize you might be wondering why I have two forms on this page. The basic reason is I have button inputs that I've styled the way I want but then I use the onclick to call the submit of the appropriate form here. I am ultimately going to be leveraging AJAX here, but that's coming later.
id is always unique. you cannot select 2 elements with same id. select by name
$(document).ready(function() {
$('input[name=post_id]').val($('#_postid').val());
});
Having two HTML elements with the same ID is illegal and will cause undefined behavior such as what you're experiencing. Using the same name is valid, however. Therefore you could use a selector like $('form > input[name=post_id]'), which would look for an input inside of a form with the name attribute set to post_id.

Simplest way to read INPUT outside a FORM

I have a simple form as
<form method="post" action="target.php">
<input class="button" type="submit" value="Submit" />
</form>
I want to read checkboxes from atable. Thus, checkbox input is outside the <form> as
<input type="checkbox" name="tick[]" value="'.$value.'" />
What is the simplest jQuery action to read the values checked and send them via POST by the form?
P.S. Since I have form for each row in the table, I cannot put the entire table within <form> tag.
Try this - I didn't test it though.
$("input[name^=tick]:checked").each(function() {
$(this).val() // this line should contain the value of each checked checkbox, you can use it as you want
});
You can get the entire for in a single object / array by using jQuery serialize() or serializeArray() method :
alert($('#<idOfForm>').serialize()); // will alert all form values in key / value string
or to submit the form using $.post() :
$.post("target.php", $("#<idOfForm>").serialize());

jQuery Selecting the first child with a specific attribute

I have a form in HTML with multiple inputs of type submit:
<form id = "myForm1" action="doSomethingImportant/10" class="postLink" method="post">
<input type="hidden" id="antiCSRF" name="antiCSRF" value="12345"></input>
<input type="submit" value="clickThisLink"></input>
<input type="submit" value="Don'tclickThisLink"></input>
</form>
What I want to do is select only the first input with type submit while ignoring the others, the snippet of code I currently have is as follows, note it is within a for-each loop that goes through all forms on my page, hence (this) to avoid confusion:
var name = $(this).find("input[type='submit']").val();
I'm thinking this already grabs the first input of type submit by default, I'm not sure if that assumption is correct or if there's a more formal way of going about it, thanks.
Try:
$(this).children("input[type='submit']:first").val();
how about the first selector
var name = $("input[type='submit']:first").val();

Categories