Automatically creating the desirable number of radio button questions - javascript

I try to make web app for creating radio button questions (like survey). The problem is defining the array of radio button options in order to call it on php page and display it in the desirable order.
In my example below, I only got one radio button of each question, and I want to display all radio buttons input on the index.html page.
This should work like this: User opens index.html, there he add the first question (button Add Question) and the proposal of answers (for example 3, which he will get by pressing the Add option button and inserting text of it). The same he should do and for the question number 2, etc...
After that, by clicking PROCEED, it should lead him to the process.php page where the survey will display radio buttons questions. But there is a mistake, please see it on the link or in the code below:
LINK FOR TESTING
index.html
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
script.js
n=1;
var m = 1;
var moreradio = '<br/><input type="button" onclick="addmoreradio()" value="Add option">';
function addradio() {
m = 1;
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = n + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + moreradio + '<br/><div id="opid' + n + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
n++;
r = n-1;
}
function addmoreradio() {
var radio = '<input type="text" name="tag' + r + m + '"><br/>';
document.getElementById("opid"+r).innerHTML += radio;
m++
}
process.php
<?php
$question = $_POST['question'];
$length = count($_POST['question']);
$r=1;
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
$radioarray = $_POST['tag'];
$area = '<input type="radio" name="'.$r.'" value="'.$r.'">'.$radioarray$j$r.'<br/>';
$bla .= $j.') '.$question[$j].'<br/>'.$area.'<br/><br/>';
$r++;
}}
$content = $bla;
echo $content;
?>

You can did a mistake on form side while naming elements. Also you did mistake on backend while iterating. You can use following;
JS:
<script>
var m = 0;
function addradio() {
var textarea = document.createElement("textarea");
textarea.name = "question[]";
textarea.rows = 1;
textarea.cols = 60;
var div = document.createElement("div");
div.innerHTML = m + '. Question: ' + '<br />' + 'Que: ' + textarea.outerHTML + '<br/><input type="button" onclick="addmoreradio(' + m + ')" value="Add option">' + '<br/><div id="opid' + m + '"' + '></div><br /><br/>';
document.getElementById("mydiv").appendChild(div);
m++;
}
function addmoreradio(question_id) {
var radio = '<input type="text" name="tag' + question_id + '[]"><br/>';
document.getElementById("opid" + question_id).innerHTML += radio;
}
</script>
HTML:
<script src="script.js"></script>
<form action="http://www.balkanex.info/atest/radio/process.php" method="post">
Here is the page with which you can add your new radio button questions for survey.
<input type="button" value="ADD NEW QUESTION" onclick="addradio();">
<div id="mydiv"></div>
<br/>
<input type="submit" name="submit" value="PROCEED"><br/>
</form>
PHP:
<?php
$question = $_POST['question'];
$content = '';
foreach ($question as $k => $v) {
$area = '';
$options = $_POST["tag" . $k];
foreach ($options as $key => $val) {
$area .= '<input type="radio" name="tag[]" value="'. $key .'">' . $val . '<br/>';
}
$content .= $k + 1 . ') ' . $question[$k].'<br/>'.$area.'<br/><br/>';
}
echo $content;
?>

Related

How to disable value in select option when it already selected by another select option

So, i have a simple form like this:
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
<script type="text/javascript">
var count = 0;
$(function(){
$('#add_field').click(function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv"><?php $noInv = $this->modelku->select_inv() ?> <?php foreach($noInv->result() as $inv){ ?> <option value="<?php echo $inv->no_inv ?>"><?php echo $inv->no_inv ?></option><?php } ?></select><br>' );
});
});
</script>
</div>
When i click the button the field will regenerate select option, and the value is from database
select_inv function:
public function select_inv()
{
$this->db->select("no_inv");
$this->db->from('detail_barang');
$this->db->where("kondisi = 'Ada' ");
$query = $this->db->get();
return $query;
}
My Question: How can i disable value in select option when it already selected by another select option?
Try this if this is what you need.
i just created a sample dropdown and in my jquery i trigger the event change using the class of all select option then i will get the value of the select and id. after getting the value i check the val if it is empty or not if not empty then i will use the each function for all the select and get their id attribute so i can compare it with the id of the select and if their id is not the same then i will disabled the option with the same value of the selected dropdown.
and i use focus event for getting the previous value so i can reset whether the user change the value of the selected option.
$( document ).ready(function() {
$('body').on('click','#add_field',function(){
count += 1;
$('#container').append(
'<strong >No Inv Barang Ke ' + count + '</strong><br />'
+ '<select id="field_' + count + '" name="fields[]' + '" class="form-control no_inv select_alternate"> <option value="">select</option><option value="test1">test1</option><option value="test2">test2</option><option value="test3">test3</option></select><br></select><br>' );
});
var count =0;
var previous;
var selectedData = [];
$('body').on('click','.select_alternate',function(){
previous = this.value;
});
$('body').on('change','.select_alternate',function(){
var val = this.value;
var id = $(this).attr('id');
if(val != ''){
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + val + '"]').prop('disabled',true);
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
selectedData.splice($.inArray(val, selectedData),1);
}else{
selectedData.push(val);
}
});
}else{
$(".select_alternate").each(function(){
var newID = $(this).attr('id');
if(id != newID){
$('#'+newID).children('option[value="' + previous + '"]').prop('disabled',false);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="">No Inventaris</label>
<div id="container">
<input type="button" name="noInv" class="form-control" id="add_field" value="Klik untuk membuat text field baru"><br>
</div>

Trouble looping through data in HTML using JavaScript

I am using javaScript to go through 149 input type number fields and I am having problems getting it to work. I have conditions set that if the value of those number fields are negative, float, or 0 it will return an error message using
alert(" Error Message");
I am iterating through my input type's through a for loop like the following
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var i; var x = 0; var s; var val; var test;
for (i = 1; i < 150; i++) {
s = '' + i; //converts i into string
val = document.getElementById(s).value; //Puts string value into val
test = +val; //Converts val into number
//Error Checking
}
I have tried this code on smaller input type = number fields (such as 10), and all of my error flags work, but whenever I use my needed number 149 (set to 150 because I want it to do one less than 150) I do not receive any error messages or activity from my funciton.
Check the following example .
//For Demo Puropse
for(i=1;i<300;i++){
var node = document.createElement("input");
node.id=i
node.value=i
document.getElementById("stage").appendChild(node)
}
function checkValues(){
for(i=1;i<300;i++){
elemValue = document.getElementById(i).value
if(! isInteger(elemValue) || ! elemValue){
alert("Error ! : " + elemValue + "#" + i)
return;
}
}
alert("Passed")
}
function isInteger(x) {
return x % 1 === 0;
}
<button onclick="checkValues()">Check</button>
<br/>
<div id="stage"></div>
So here is my code. I am reading from a data base that I did not want to display the credentials too. In my code you will see a comment that has the comment question. Is there a way that I can just use php to get the product number and the quantity so that I can use it in form.php. It is a post method, but as the question says I am fairly new to this coding language. Hopefully this code snippet will tell you more about what I am actually trying to accomplish.
<form action="form.php" method="post">
<table cellpadding="6">
<tr>
<th>Description</th>
<th>Price</th>
<th>Weight</th>
<th>Image</th>
<th>Quantity</th>
</tr>
<!-- PHP LANGUAGE -->
<?PHP
$sql = "SELECT * FROM parts";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorIndo()));
while( $row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>' .
'<td>' . $row['description'] . '</td>' .
'<td>' . $row['price'] . '</td>' .
'<td>' . $row['weight'] . '</td>' .
'<td> <img src="' . $row[pictureURL] .'" alt="' . $row[number] . '" style="width:50px;height:50px;">' .
'<td> <input type="number" id= "'. $row[number] . '" value="0">' .
'</td>' . '</tr>';
}
echo "</table>";
?>
</table> <br>
<input type="button" id="submit" value="Submit" />
</form>
<script>
var i; var x = 0; var s; var val; var test; var array = [];
$('form').submit(function(){{
var value = $(this).val();
for (i = 1; i < 5; i++) {
s = '' + i; //stores i as string
//getsElement id val string and stores into val
val = document.getElementById(s).value;
test = +val; //Converts string into tester int for error checking
if tester < 0 { alert("Must enter in one product!"); return;}
//CHECKS FOR FLOATS IN Quantity FIELD
else if (Math.floor(test) != Math.ceil(test)) { alert("Cannot have float quantities!"); return; }
else {
//My attempt at coding a block that captures the product
//Number, and the quantity selected. Is there a way
/* QUESTION */
array.push(i); array.push(x)
}
}
if (x == 0) { alert("Must have at least one product quantity to continue!"); return; }
else { alert("good!"); }
}}
</script>
</body>
</html>

Codeigniter and javascript-add dynamic input and radio fields

hi guys I am pretty newbish in javascript and php for that matter. I am making a page where user will choose either to create a radio or input fields for others to solve.
Everything works fine except, when I save the form, fields are not in the order I added them because I first loop over the 'input' fields and then over the 'radio' fields. I know this is probably not the way to do it, feel free to give me an alternative.
Any help would be appreciated, thanks in advance.
VIEW
<h1>Add questions</h1>
<form action="" method="post">
<div id='pit'>
<span id="add_input"><a href="#" class='button' style='font-size:1.5em;'><span>» add input </span></a></span><br>
<span id="add_radio"><a href="#" class='button'style='font-size:1.5em;'><span>» Dodaj yes/no question</span></a></span>
</div>
<input type="hidden" name="id" value="<?= $this->uri->segment(3); ?>" />
<input id="go" class="button" name="submit" type="submit" value="Save" />
</form>
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input id="field_' + count + '" name="fields[]' + '" type="text" /></p>' );
a=count;
document.write(a);
});
});</script>
<script type="text/javascript">
var count = 0;
$(function(){
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input id="radio_' + count + '" name="radios[]' + '" type="text" /></p>' );
});
});</script>
CONTROLLER
$id=$this->input->post('id');
if($_POST['fields']){
foreach ( $_POST['fields'] as $key=>$value ) {
$tip='input';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
if($_POST['radios']){
foreach ( $_POST['radios'] as $key=>$value ) {
$tip='radio';
if($value!=''){
$this->page_model->add_questions($id,$value,$tip);
}
}
}
Something like this might work.
Maintain the same count variable in the JavaScript to keep track of which input is created.
Instead of using name="fields[]", use name="field_' + count + '" so you can iterate with a loop in the controller.
VIEW
<script type="text/javascript">
var count = 0;
var a=0;
$(function(){
$('span#add_input').click(function(){
count += 1;
$('#pit').append('<p><strong>Pitanje #' + count + '</strong>'+ '<input name="field_' + count + '" type="text" /></p>' );
a=count;
document.write(a);
});
$('span#add_radio').click(function(){
count += 1;
$('#pit').append('<p><strong>DA/NE #' + count + '</strong>'+ '<input name="radio_' + count + '" type="text" /></p>' );
});
});
</script>
CONTROLLER
Use a regular expression to extract the necessary values.
$inputs = array();
$id=$this->input->post('id');
foreach($_POST as $key => $value) {
$matches = array();
if (preg_match('/(field|radio)_([\d]+)', $key, $matches)) {
$tip = $matches[1];
$count = $matches[2];
$inputs[$count] = array($id, $value, $tip);
}
}
Loop through the new $inputs array to call your add_questions method.
ksort($inputs);
foreach($inputs as $array) {
$id = $array[0];
$value = $array[1];
$tip = $array[2];
$this->page_model->add_questions($id,$value,$tip);
}

Text Box not saving in wordpress theme settings

I am creating a wordpress theme with theme options in wordpress. I like to add a dynamic add and remove textbox using jquery inside the theme settings page. My query is,
theme_settings.php
<?php
function theme_settings_init(){
register_setting( 'theme_settings', 'theme_settings' );
}
function add_settings_page() {
add_menu_page( __( 'Theme Settings' ), __( 'Theme Settings' ), 'manage_options', 'settings', 'theme_settings_page');
}
//add actions
add_action( 'admin_init', 'theme_settings_init' );
add_action( 'admin_menu', 'add_settings_page' );
//start settings page
function theme_settings_page() {
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false;
?>
<div>
<div id="icon-options-general"></div>
<h2><?php _e( 'Theme Settings' ) //your admin panel title ?></h2>
<?php
//show saved options message
if ( false !== $_REQUEST['updated'] ) : ?>
<div><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; ?>
<form method="post" action="options.php">
<?php settings_fields( 'theme_settings' ); ?>
<?php $options = get_option( 'theme_settings' ); ?>
<div id='TextBoxesGroup'>
<?php
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
?>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<p><input name="submit" id="submit" value="Save Changes" type="submit"></p>
</form>
</div><!-- END wrap -->
<?php
}
and my javascript file is:
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
Now my question is, In the theme settings page, the add action and remove action works very fine but while saving the theme setting options the added textbox dissappears. It happens while refreshing the page too.
Please anyone help me how to keep those added textbox remains same if saving the theme options page.
Use .append() instead of .after().html(). This way your code goes inside the corresponding div element. I made use of jQuery also.
newTextBoxDiv.after().html(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >');
should be
$('<div id="TextBoxDiv'+counter+'"></div>').append(
'<input type="text" name="theme_settings[textbox' + counter +
']" id="theme_settings[textbox' + counter + ']" value="" >').appendTo('#TextBoxesGroup');
To make the text boxes appear you need a while loop like this:
$counter = 1;
while (get_option('textbox'.$counter) && $counter <= 10) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" >
</div>';
$counter++;
}
When you save them you could do this:
$counter = 0;
while (isset($_POST['theme_settings']['textbox'.$counter']) && $counter <= 10) {
update_option('textbox'.$counter, $_POST['theme_settings']['textbox'.$counter']);
$counter++;
}
// now remove the rest of them if they were previously set
// for example we now set only 5 of them and there were 10 before
// continue with counter from where we left in the previous while loop
while ($counter <= 10) {
update_option('textbox'.$counter, false);
$counter++;
}
EDIT:
function theme_settings_page() {
$updated = false;
if (isset($_REQUEST['updated'])) {
update_option('theme_settings', $_POST['theme_settings']);
$updated = true;
}
// ....
if ($updated) {
echo '<div><p><strong>';
_e( 'Options saved' );
echo '</strong></p></div>';
}
$counter = 1;
$options = get_option('theme_settings');
while (isset($options['textbox'.$counter])) {
echo '<div id="TextBoxDiv'.$counter.'">
<input type="textbox" id="theme_settings[textbox'.$counter.'] name="theme_settings[textbox'.$counter.']" value="'.$options['textbox'.$counter].'" />
</div>';
$counter++;
}
echo '<input type="hidden" name="updated" value="1" />';
// the rest of your form
}

How get the textbox values in array.....to store in database

this is my code...
How get the textbox array value to store in database...
<html>
<head>
<script type="text/javascript">
var max = 4; //highest number to go to
var currentIndex = 0;
function btnClick() {
if(currentIndex < max){
currentIndex++;
postClick();
}
}
function Previous(){
if(currentIndex>0){
currentIndex--;
postClick();
}
}
function postClick() {//whatever you want to happen goes here
var sahans = new Array();
sahans[currentIndex] == d;
var d = document.getElementById("div");
d.innerHTML = "<p><input type='text' name='name"+currentIndex+"[]'>";
d.innerHTML += "<p><input type='text' name='topic"+currentIndex+"[]'>";
document.getElementById("div").style.display = "";
}
</script>
</head>
<body>
<form id="form1">
<div>
<input type="button" value="Previous" onclick="Previous();" />
<input type="button" value="Next" onclick="btnClick();" />
<div id="div"></div>
</div>
</form>
</body>
</html>
JavaScript:
function store(form) {
var input = form.getElementsByTagName('input');
var myarray = Array();
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text') {
myarray[input[i].getAttribute('name')] = input[i].value;
}
}
for (var i in myarray) {
alert(i + ': ' + myarray[i]);
}
}
HTML:
<form onsubmit="store(this); return false">
<p>
<input type="text" name="name" /><br />
<input type="text" name="topic" />
</p>
<p>
<input type="submit" value="Store in database" />
</p>
</form>
Edit:
Ok, now I made a full example with AJAX and the actual saving to the database. The AJAX call uses 'POST'. Simply fill in the number of fields that you want in the max variable.
JavaScript:
var max = 10;
var current = 0;
function goto(form, pos) {
current += pos;
form.prev.disabled = current <= 0;
form.next.disabled = current >= max - 1;
var fields = form.getElementsByTagName('fieldset');
for (var i = 0; i < fields.length; i++) fields[i].style.display = 'none';
fields[current].style.display = 'block';
form['name' + current].focus();
}
function store(form) {
var input = form.getElementsByTagName('input');
var data = '';
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') == 'text')
data += '&' + input[i].getAttribute('name') + '=' + input[i].value;
}
data = encodeURI('n=' + max + data);
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('POST', 'store.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', data.length);
xhr.setRequestHeader('Connection', 'close');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != '')
alert(this.responseText);
else {
form.submit.value = 'Saved!';
setTimeout(function() { form.submit.value = 'Save to database' }, 500);
}
}
}
xhr.send(data);
}
window.onload = function() {
var form = document.forms[0];
var container = form.getElementsByTagName('div')[0];
container.innerHTML = '';
for (var i = 0; i < max; i++)
container.innerHTML += '<fieldset><legend>Entry ' + (i + 1) + ' / ' + max + '</legend><input type="text" name="name' + i + '" /><br /><input type="text" name="topic' + i + '" /></fieldset>';
goto(form, 0);
}
HTML:
<form action="submit.php" method="post" onsubmit="store(this); return false">
<p>
<input type="button" name="prev" onclick="goto(this.form, -1)" value="Previous" />
<input type="button" name="next" onclick="goto(this.form, +1)" value="Next" />
</p>
<div>
<noscript>Please enable JavaScript to see this form correctly.</noscript>
</div>
<p>
<input type="submit" name="submit" value="Store in database" />
</p>
</form>
Users who have JS disabled will see what's in the <noscript> tag, otherwise it's replaced with the fieldsets. Also it's good to make an alternative submit page (submit.php) for users who have JS disabled. Below is store.php, the AJAX submit script.
PHP (store.php):
<?php
if (empty($_POST['n']) || $_POST['n'] < 1) die('Invalid request!');
$fields = array('name', 'topic');
$errors = '';
for ($i = 0; $i < $_POST['n']; $i++) {
foreach ($fields as $field) {
if (empty($_POST[$field . $i]))
$errors .= '- ' . $field . ' ' . ($i + 1) . "\n";
}
}
if ($errors != '')
die("Please fill in the following fields:\n" . $errors);
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('mydb', $db);
for ($i = 0; $i < $_POST['n']; $i++) {
$name = mysql_real_escape_string($_POST['name' . $i]);
$topic = mysql_real_escape_string($_POST['topic' . $i]);
mysql_query(' INSERT INTO entries (id, name, topic) VALUES (' . $i . ', "' . $name . '", "' . $topic . '")
ON DUPLICATE KEY UPDATE name = "' . $name . '", topic = "' . $topic . '"
') or die('Database error!');
}
mysql_close($db);
?>
The output text of this script (if there is an error) is displayed in the JavaScript alert.
I hope it's working for you now.
This would be help ful for you
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<input type="textbox" name="Tue[]" />
<script type="text/javascript">
function validateText(event){
var tar_ele = $(event.target);
if(tar_ele.val() is not valid)
tar_ele.focus();
}
</script>
<input type="text" name="Tue[]" onblur="validateText(event)"/>
javascript text box array and get values and focus on particular field

Categories

Resources