I have radio inputs, if I click on an input, then after post, all the other inputs go to "checked", I don't understand why, here is my code:
foreach ($tab_stickers_stored as $key => $value) {
<input class="form-check-input switch_sticker" type="checkbox" id="switch_sticker_<?=$key?>" name="switch_sticker" value="<?= $key ?>"
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>>
}
$(".switch_sticker").on('change', function() {
var index = $(this).val();
$("input[name='switch_sticker']:checked").each(function(){
if ($("#switch_sticker_" + index).is(':checked')) {
var temp = document.getElementById('largeur_sticker_' + index).value;
document.getElementById('largeur_sticker_' + index).value = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = temp;
} else {
var temp = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = document.getElementById('largeur_sticker_' + index).value;;
document.getElementById('largeur_sticker_' + index).value = temp;
}
index = "";
});
});
Thank you
Your inputs have different id attributes, but they all have the same name. It is the name that determines what gets submitted, as you have already discovered without realising it when you wrote this line:
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>
That if statement has nothing in it which varies around the loop; it looks at the same value $_POST['switch_sticker'] every time.
The JavaScript code, meanwhile, is essentially irrelevant to the question, because it only changes the value of various elements. Those will show up as the value of the $_POST['switch_sticker'] variable, but because there's only one variable and lots of values, it will just end up with the last one in the list.
The solution is to give each of your checkboxes their own name, like you give them their own value: name="switch_sticker_<?=$key?>". Then look for that name in the PHP: <?php if (isset($_POST['switch_sticker_' . $key])){echo 'checked="checked"';}?>.
You can also use names in the form something[something_else], e.g. name="switch_sticker[<?=$key?>]" and <?php if (isset($_POST['switch_sticker'][$key])){echo 'checked="checked"';}?>. That will cause PHP to create an array when they're submitted, which is a bit nicer to work with - you can write things like foreach ( $_POST['switch_sticker'] as $submittedKey => $submittedValue ) { ... }.
Related
I have a list of songs. I'm trying to determine whether or not a song on the list has been checked or not. If so I need to know the value of the checkbox.
my html looks like this... the value $song_id is pulled from the list in the database.
<input type='checkbox' name='song[]' value='$song_id' />
There could be 10 songs... there could 100.
I need to know which ones have been checked and how to get the value.
On click save item ID of item to array; (js)
On click search was such ID already checked; (in array)
ADDED
You should use jQuery (or raw javascript) to do logic you want. jQuery is http://jquery.com/ using it you can do you want on front-end. Do this on back-end is bad idea.
Once you submit the form the $_POST['song'] variable will contain an array of all the $song_id's that were selected.
You can do something like this:
<input type='checkbox' name='song[]' class='songItem' value='$song_id' />
<input type='hidden' id='selectSongsHidden' />
In JavaScript,
var selectedSongValues = [];
var selectedSongsString = ""; // for comma-separated values
function GetSelectedSongs()
{
var songs = $('.songItem');
var selectedSongs = [];
for(var i=0; i<songs.length; i++)
{
var checked = $(songs[i]).is(':checked');
if(checked)
{
selectedSongs.push(songs[i]);
}
}
for(var j=0; j<selectedSongs.length; j++)
{
selectedSongValues.push($(selectedSongs[j]).val());
selectedSongsString += $(selectedSongs[j]).val() + ",";
}
$('#selectSongsHidden').val(selectedSongsString);
}
When you press submit, in the onclick event you can call this function and set the value to a hidden field.
You can see this in a working http://jsfiddle.net/A3e3y
foreach ( $_POST['song'] AS $song_id ) {
// do smth with $song_id ...
}
I have couple of input field and values in them. This is projected to the user.
The user can modify these values and submit them.
When submitted, I need to check which input field is modified.
I can compare the previous fields and current fields and check. But I am trying to find more optimized way to do this.
I can use javascript, php, jquery and html tricks
<input id="input1" value="someValue" type="text">
<input id="input2" value="someValue" type="text">
Script:
$('input').on('change',function(){
var id = $(this).attr('id');
alert("input field is modified : ID = " + id);
});
You can create 2 different input, 1 hidden with a class like originalVal and 1 visible for every input.
Then on submit you do something like that :
$('input').each(function(){
var currentVal = $(this).val();
var originalVal = $(this).closest('.originalVal').val()
if(currentVal != originalVal){
//This input has changed
}
})
Since no code was given, you could compare what was in the input compared to what is now in it.
HTML Input:
<input type="text" id="testInput" value="DB Value"/>
jQuery
var modifiedInputs = [];
var oldVal = "";
$("#testInput").focus(function() {
oldVal = this.value;
}).blur(function() {
console.log("Old value: " + oldVal + ". New value: " + this.value);
//If different value, add to array:
if (this.value != oldVal) {
modifiedInputs.push(this.id);
}
});
Fiddle: http://jsfiddle.net/tymeJV/tfmVk/1/
Edit: Took it a step further, on modification of an input, if the changed value is different from the original, it pushes the elements ID to the array.
I would say your best bet would be to get the initial values from the input fields, and then compare them later on. Then, just do a comparison once the submit button is clicked. For instance, put this somewhere in your $(document).ready() that way it will retrieve the initial value.
var oldValue=[];
$('input').each(function(){
oldValue.push($(this).val());
});
Then you can compare later on when you hit the submit.
you could compare with default value like this
for(var i in formObj)
if('value' in formObj[i] && formObj[i].value!=formObj[i].defaultValue){
//do what ever here ...
}
I am experiencing some issues with a form I am making. I have the code to post a form to my PHP script that is meant to handle the data with this code:
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
var q1 = $("#q1").val();
var q2 = $("#q2").val();
var answers = "page=1&q1="+q1+"&q2="+q2;
$.ajax({
type:'POST',
url:'add.php',
data:answers,
success:function(response)
{
$("#answers").html(response);
}
});
});
});
</script>
This form is then received in my PHP script like this:
$page = $_POST['page'];
$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
echo "Page: " .$page . "<br/>Question 1: " . $q1 . "<br/>Question 2: " . $q2;
The issue of it all is that I want this form to be able to handle X amount of inputs and also handle input I do not know the name of. Like I can get 5 textboxes, or 2 textboxes + a string of radiobuttons and so on. Is there a way to collect ALL $_POST data and then explode it or something similar so I can get it ready for the database? I wish to recover all question id's(values) and all answer values(could be a string or an int representing a radiobutton id).
You can iterate through all POST and GET request parameters by simply treating POST and GET as an array. For an example:
print_r($_POST);
Alternatively:
foreach ($_POST as $key => $value) {
echo $key." = ".$value."<br>";
}
If you want to handle a variating amount of input fields, you can define an incrementing naming convention and use loops to gather them all to an array.
with print_r($_POST); you can look at all values.
or something like this:
foreach ( $_POST AS $key => $value) {
echo $key." => ".$value."<br>";
}
First: Let jQuery build your data string, your current method requires you to know each field in advance and can't handle data with special characters in it.
url:'add.php',
data: $('#myForm').serialize(),
success:function(response)
Second: Name your fields using the PHP multiple fields with the same name convention:
<input type="radio" name="answer[1]" value="foo">
<input type="radio" name="answer[1]" value="bar">
You can then access them as:
$_POST['answer'][]
It is an array, so you can get the '1' and the 'foo' or the 'bar' in a loop.
I am using jQuery to create as many input textboxes as the user needs like so:
<script type="text/javascript">
$(document).ready(function() {
$('#names').on({
blur: function() {
var name = $("<p><input class='input' type='text' /></p>")
var nullFields = 0;
$(this).closest('div#names').find('input.input').each(function(){
if($(this).val() == ""){
nullFields++;
}
});
console.log(nullFields);
if(nullFields <= 1){
$('#names').append(name.fadeIn(500));
}
}
}, 'input');
});
</script>
Inserting a static textbox into a database isn't a problem using $_POST['blah'] andmysql_query("INSERT INTO ..."), but how do I insert the values of the dynamically created textboxes? I know I'll have to give the textboxes different names as they're created and I presume the MySQL query will be by way of some sort of loop.
EDIT
The website in question is here, specifically at step 4. As mentioned above, step 3 was quite straightforward.
This is an example to get you started, not the complete solution.
You create an array for the names then have the php insert each array item
var currentArrayNum = 1;
$('#someClickable').click(function(){
$('#td').append('<input name="arrayName['+currentArrayNum+']" value="" />');
currentArrayNum += 1;
});
php:
foreach ($_POST as $key){
if (is_array($key)){
foreach ($key as $key2 => $value){
//$key2 will equal arrayName[currentArrayNum]
//$value will equal the user input for the text field
do some stuff
}
You can create arrays out of name, simply try this:
<input type="text" name="post_input[input_1]" value="">
<input type="text" name="post_input[input_2]" value="">
After Submit, you would get an Array out of $_POST["post_input"] with the keys input_1 and input_2 and their assigned values. Then you just loop them as a normal array, for example
$aTextFields = $_POST["post_input"];
foreach( $aTextFields as $sValue ) {
...
}
Im creating a dynamic form with a button called "Add more rows" when this is clicked a JavaScript function creates a new row of textboxes with the appropriate id.
The problem is, how do I pass a counter variable from my JavaScript function to my next php page so it nows how many rows of textboxes to receive $_POST.
Ive got my JavaScript function however I'm missing data from the rows it creates itself.
any ideas?
Thanks
This is my js function
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
inp[c].onclick=function()
{
n=15;
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='time'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='event'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='supplies'+n;
document.getElementById('txtara').appendChild(x)
var sel = document.createElement('select');
y = document.createElement('option');
y.value = 'Yes';
y.name = 'success' + n;
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.name = 'success' + n;
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='comment'+n;
document.getElementById('txtara').appendChild(x)
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
//-->
}
You should add an <input type="hidden" name="num_rows" value="0"> to your form and update its value to be the row count when the form is submitted.
Assuming you want the number for easing the way you fetch the data on the server side.
There is a very simple way of doing this.
Let's say you have many input's of the same logical data type you want to handle, like:
<input type="text" name="names" value=""> And you create more of it dynamically.
Of course, you want them individual names to fetch the data, so you do like:
<input type="text" name="names[]" value=""> OR if you have more input for one entity, to make it consistent: <input type="text" name="names[1]" value=""><input type="text" name="eye_colours[1]" value=""> , so you can add a number in the brackets.
What do you do on the PHP side?
if( isset($_POST['names']))
foreach($_POST['names'] as $key => $val){ ... }
PHP parses it as an array, hurray! :)
You can add a name attribute to your form elements. As your form contains multiples elements (and you don't know how much elements), this name attribute must be in the form "my_name[]". The [] chars indicates a collection of elements. So your HTML code could look like this:
<form method="POST" action="mypage.php">
<input type="text" name="whatever[]" value="first" />
<input type="text" name="whatever[]" value="second" />
<input type="text" name="whatever[]" value="third" />
<input type="submit" />
</form>
Then, when the form will be submitted, you can get the values using the PHP variable $_POST['whatever']. This variable is an array and contains all the values of the "whatever" inputs like this:
$myValues = $_POST['whatever'];
// $myValues = array( 0 => "first", 1 => "second", 2 => "third" );
Then, if you want to do some actions with each rows, do a for each loop. If you want to know how many lines were submitted, you can simply do a count.
Since javascript is a client-side language, this is not possible :(
but, you can use AJAX to send a local javascript var to the server by GET, or POST
You can use PHP to output javascript code. If you have a value you can output it directly in javascript, or if you have a more complex value, you can encode it using json_encode.
You don't need to. POST will carry the number of rows for you without a problem. Simply do count($_POST) to get the number of values posted. Or, if you use my suggested version below, use count($_POST['time']) to get the number of time values.
var types = ['time', 'event', 'supplies'];
function createInput( i, n )
{
var base = isNaN( i )? i: types[ i ];
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name= base + "[" + n + "]"; // this will make $_POST[<base>] an array with n as the index.
document.getElementById('txtara').appendChild(x)
}
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
var n = 15; // move n out here. Otherwise n will always = 15.
inp[c].onclick=function()
{
for( var i = 0; i < types.length; i++ )
{
// passing both variables in will avoid any possible collisions.
createInput( i, n );
}
var sel = document.createElement('select');
sel.name = 'success[' + n + ']';
y = document.createElement('option');
// option has no name attribute (http://www.w3schools.com/tags/tag_option.asp)
y.value = 'Yes';
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
// you had this three times... why?
document.getElementById('txtara').appendChild(sel);
createInput( 'comment', n );
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
}