How do I get all radio buttons and their textbox values? - php

Description: On the form appears radio buttons with textboxes. Their count = count that you entered in textbox. In test.php file I need get all radio buttons and their textbox values, it does not matter - checked, unchecked radio buttons state.
Error is that I get only the most recent values of radiobutton and textbox. I do not see values of previous radiobuttons and textboxes.
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function getnewElementID()
{
var elementID = 0;
if($(".form-element").length > 0)
elementID = $(".form-element").length;
return elementID;
}
$(document).ready(function() {
$('#ok1').click(function () {
var n = $('#box1').val();
var index = 0;
var newElementID = getnewElementID();
if($(".RadioDiv").length > 0)
index = $(".RadioDiv").length;
var newElement = "<div class='RadioDiv form-element'><input type='hidden' name='RadioElements["+newElementID+"]' value='radiogroup'/>\n<input type='text' size='50' name='RadioElementsQueations["+newElementID+"]' placeholder='question...' >";
for (var i=1;i<=n;i++)
{
newElement+="<ol><input type='radio' name='RadioElementsValues["+newElementID+"]' value='radio_"+index+"' for='RadioElementsValuesText["+newElementID+"]'>\n\<input type='text' id='radtext' name='RadioElementsValuesText["+newElementID+"]' size='30' value='choice.."+index+"' ></ol>";
index++;
}
newElement+="</div>";
$("#myForm").append(newElement);
});});
$(document).ready(function() {
$('#submit').click(function () {
var data = $("#myForm").serialize();
if($('input[type="radio"]:checked').length == "0") {
alert("Select any value");
} else {
$.post (
"test.php",
data,
function (response) {
$('#message').html(response);
}
);
}
return false;
});
});
</script>
</head>
<body>
<form id ="myForm" action="test.php">
<label>Select your favourite Activities:</label><br/>
<input type="button" name="ok" value="ok" id="ok1">
<input type="text" value="" id="box1" name="count" size="1"><br/>
<input type="submit" id="submit"/> <br/>
</form>
<div id="message"></div>
</body>
</html>
test.php
<?php
var_dump($_POST);
$elements = $_POST['RadioElementsValuesText'];
if(is_array($elements));
for ($index = 0; $index<sizeof($elements);$index++)
{
$astring = implode("<br/>", $elements);
echo "Choices: ". $astring."<br/>";
}
?>

You should use checkboxes instead of radio button.
In a post request, only one radio button value will be send for the group name (here 'RadioElementsValuesText').
Use javascript to reproduce the radio button behavior on your checkboxes (only one checked at a time).

Related

Submit form checkbox value without page refresh Ajax php

Still learning ajax.
Now i go stuck at this point.
Am trying to get the value of the checkbox on my form.
Below is my HTML code
<form method="post">
<input type="text" name="mytext" id="text">
<br>
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<input type="submit" id="form4" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax Script
$(document).ready(function() {
$("#form4").click(function(event) {
var action = 'another_test';
var text = $("#text").val();
var agreed = $("#agreed").val();
event.preventDefault();
$.ajax({
type: "POST",
url: "test3.php",
data: {
mytext:text,
test:agreed,
action:action
},
success: function (response)
{
$(".form-message").html(response);
}
});
});
});
Then this is my PHP code below which is on a different page
<?php
if (isset($_POST['action']))
{
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$mytext = $_POST["mytext"];
$errorEmpty = false;
if (empty($mytext)) {
echo "<p>enter your text</p>";
$errorEmpty = true;
}
elseif (empty($test)) {
echo "<p>Click the checkbox</p>";
$errorEmpty = true;
}
else {
echo "<p>Correct</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
It works for text, textarea input but not for checkbox. I know am wrong. Am still learning though.
Please help me. Thanks in advance.
Using $("#agreed").val() you only receive the value you setted in the "value" attribute on your input checkbox tag. To get a boolean value of checkbox's state you have to do use .is() function
$("#agreed").is(":checked");

Checkbox values getting without page loading using AJAX

I have a problem getting checkbox value in the following code(without page loading).
If I click on checkboxes the values can be passed through the array variable check. But whenever I click checkbox I get " Array ( [0] => undefined )".
Here is my code:
index.html
<script src="create_ajax_object.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function display() {
var ajax = create_ajax_object();
if (ajax) {
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("target").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "fetchdata.php", true);
var check = new Array();
var "check[]=" + encodeURIComponent(document.myForm.user.value);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(check[]);
} else {
alert("Your browser doesnt support AJAX!");
}
} </script>
<br>
<form name='myForm'>
<input type="checkbox" name="user" value="First" onclick="display();">1
<br>
<input type="checkbox" name="user" value="Second" onclick="display();">2
<br>
<input type="checkbox" name="user" value="Third" onclick="display();">3
<br>
</form>
</html>
fetchdata.php
<?php
$no=array($_POST['check']);
foreach($no as $n)
{
print_r($n);
}
?>
The variable document.myForm.user is array of checkbox objects, you have to iterate over it and check checked property of each element.

Adding a "REMOVE" link beside a textbox result by an array

[+] //each time I click this button the textbox will generate and I want to have a link beside each textbox, link is "remove" when I click "REMOVE" the textbox will remove..
[hello1] Remove
[hello2] Remove
[hello3] Remove
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var i=0,j=0;
var t1= new Array();
function createtext(){
i++;
t1[i]=document.createElement('input');
t1[i].type='text';
t1[i].name='text'+i;
t1[i].value = "hello"+i;
t1[i].size = 10;
document.forms[0].appendChild(t1[i]);
var mybr=document.createElement("br");
document.forms[0].appendChild(mybr);
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="f1">
<input name="b1" type="button" onClick="createtext()" value="+">
<input name="b1" type="Submit"><br>
</form>
</BODY>
</HTML>
Well this is simple.
Just add a id attribute with your text field array that will be assigned to each newly created textarea like this:
t1[i].id='some_unique_suffix'+i
t1[i].onClick='remove("some_unique_suffix"'+i+')'
Then you can go on creating a remove link after each textfield via your loop and pass the id of that particular textfield to a remove function that will be called upon clicking on the remove link like this:
function remove(id)
{
$('#some_unique_suffix'+id).remove();
}
Hope you get the idea.
You can add a remove button along with the input tag like this:
var i=0,j=0;
var t1= [];
function add(){
i++;
var parent = document.forms[0];
var div = document.createElement('div');
var input = document.createElement('input');
input.type='text';
input.name='text'+i;
input.value = "hello"+i;
input.size = 10;
t1.push(input);
div.appendChild(input);
var removeButton = document.createElement("button");
removeButton.innerHTML = "Remove";
removeButton.onclick = function(e) {
this.parentNode.parentNode.removeChild(this.parentNode);
return(false);
};
div.appendChild(removeButton);
parent.appendChild(div);
}
Working demo: http://jsfiddle.net/jfriend00/ky9nv/
This code makes it easier to remove an input element and it's associated button by enclosing them in a containing div. A clicked button can then just get it's parent container and remove that.
And, since your question is tagged with jQuery (thought it doesn't save you a lot here), here's a version that uses jQuery:
var i=0,j=0;
var t1= [];
function add(){
i++;
var div = $('<div>');
var input = $('<input>')
.attr({
size: '10',
type: 'text',
name: 'text' + i,
value: 'hello' + i
}).appendTo(div).get(0);
t1.push(input);
$('<button>Remove</button>')
.click(function() {
$(this).parent().remove();
}).appendTo(div);
$("#myForm").append(div);
}
add();
add();
$("#add").click(add);
Working example: http://jsfiddle.net/jfriend00/nbXak/
<script type="text/javascript">
var i=0;
function createtext() {
i++;
$('<div id="field'+i+'">​<input type="text" name="text'+i+'" value="Hello'+i+'" size="10" /> Remove</div>').appendTo('#inputsPlaceholder');
}
function removeField (id) {
$('#'+id).remove();
}
</script>
HTML:
<form action="" method="get" name="f1" id="f1">
<input name="b1" type="button" onclick="createtext();" value="+" />
<div id="inputsPlaceholder"></div>
<input name="b1" type="submit" />
</form>
Try it: http://jsfiddle.net/Z3L5C/

displaying radio button values on different textbox

<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.4.0");
</script>
<script type="text/javascript">
$(function()
{
$('input[type=button]').click(function ()
{
var txtbox = $('#buttoncheck1').attr('name');
var var_name = $("input[name='radio1']:checked").val();
$('#btn_get').val(var_name);
});
});
</script>
<html>
<body>
<?php
for($i = 0; $i < 2; $i++)
{
echo "
<div id = 'div1' name = 'div1'>
<input type='radio' value='Blue' name='radio1'>Blue</input>
<input type='radio' value='White' name='radio1'>White</input>
<input type='radio' value='Red' name='radio1'>Red</input>
<input id='buttoncheck1' type='button' name='btn' value='Click'></input>
<br />
<input type='text' id='btn_get' name='get_btn_value'></input>
</div>
";
}
?>
</body>
</html>
I can clearly get all the values of the radio buttons in this code but the only problem I've been solving for almost 3 days is that I cant display the value on other textbox. all the values from all the radio button groups are only displayed on the first textbox produced by the loop. please help me . thanks!
id values should always be unique. You can change your duplicated ids to class values and do the following:
$('input[type=button]').click(function ()
{
var $parent = $(this).parent();
var var_name = $parent.find("input[name='radio1']:checked").val();
$parent.find('.btn_get').val(var_name);
});

Echo value of checkbox checked element in HTML form

I've created an HTML form that has checkboxes that are checked dynamically due to a variable from a previous page (there is only one checkbox checked each time).
What I'd like is to echo the value of this checkbox out (to make the main title of the page so javascript alert is not adapted).
Example :
<html>
<body>
<h1>Here I'd like to echo the value of the checkbox that is checked<h1>
<form id="myform" name="myform">
<p>
<input type="checkbox" name="car" id="porsche" /> <label for="porsche">porsche</label><br />
<input type="checkbox" name="car" id="ferrari" /> <label for="ferrari">ferrari</label><br />
</p>
<script type="text/javascript">
function loopForm(form,car) {
var cbResults = 'Checkboxes: ';
var radioResults = 'Radio buttons: ';
for (var i = 0; i < form.elements.length; i++ ) {
if (form.elements[i].type == 'checkbox') {
if (form.elements[i].id == car) {
form.elements[i].checked = true ;
}
}
}
}
...
// This function will check one of the two checkboxes
loopForm(document.myform,car);
</script>
</body>
</html>
The best I can do, I'm afraid, is the following:
var inputs = document.getElementsByTagName('input');
var checkboxes = [];
for (i=0; i<inputs.length; i++){
if (inputs[i].type == 'checkbox' && inputs[i].getAttribute('checked') == 'checked'){
checkboxes.push(inputs[i].value);
}
}
document.getElementsByTagName('h1')[0].innerHTML = checkboxes;
JS Fiddle demo.
This is slightly clunky, but does, at least, use plain JavaScript; albeit it does seem to require that the checked checkboxes be marked up as following: checked="checked".
You can use jQuery to achieve this. Listen for the change() event on the checkboxes and change the text() of the h1 when this happens.

Categories