Unique Name For Dynamically Created Form Element - php

A few questions on here touch on similar subjects, but none I could find addressed my specific case.
I have a script that dynamically creates an input[type="text"] field and an input[type="radio"] field. I would like the created fields to generate unique names up to the max of 6 added fields. How can I do this with jQuery? How can i reference these newly created unique names in the PHP for my form?
jQuery:
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('
<input type="text" name="name" id="name"/>
<input type="radio" name="attend" id="attendC" value="cere" />
<input type="radio" name="attend" id="attendR" value="rece" />
<input type="radio" name="attend" id="attendB" value="both" />
<input type="radio" name="attend" id="attendN" value="neit" />
');
}
});

Actually there is so many options for that. But the best thing you will do is :
Your unique id must be timestamp you can get it like this :
var uniqueId = Date.now() | 0;
So you should generate an array for all of these what i mean is :
var insertedIds = [];
That array will keep your inserted ids and should be passed to PHP in POST operation, so your code will be :
var x = 1;
var insertedIds = [];
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
uniqueId = Date.now() | 0;
$(wrapper).append('
<input type="text" name="name" id="name"/>
<input type="radio" name="'+uniqueId+'_col0" id="attendC" value="cere" />
<input type="radio" name="'+uniqueId+'_col1" id="attendR" value="rece" />
<input type="radio" name="'+uniqueId+'_col2" id="attendB" value="both" />
<input type="radio" name="'+uniqueId+'_col3" id="attendN" value="neit" />
');
insertedIds.push(uniqueId);
}
});
If you are not using AJAX for posting variables to PHP you can use it like this :
$("yourSubmitButton").click(function(){
$("yourForm").append("<input type='hidden' name='insertedIds' value='"+JSON.stringify(insertedIds)+"'/>");
});
If you are using AJAX you can use this like this :
$.ajax({
//url,type staff etc.
data:"insertedIds="+JSON.stringify(insertedIds) // and other data
});
So that means you can fetch id_col0,id_col1... in PHP safely.

You may use the same variable x or another global one:
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('\
<input type="text" name="name_0_"' + x + 'id="name"/>\
<input type="radio" name="attend_1_"' + x + 'id="attendC" value="cere" />\
<input type="radio" name="attend_2_"' + x + 'id="attendR" value="rece" />\
<input type="radio" name="attend_3_"' + x + 'id="attendB" value="both" />\
<input type="radio" name="attend_4_"' + x + 'id="attendN" value="neit" />\
');
}
});
In this way in PHP you have only to check the first part of the name while the last part (from _number_number) is for grouping.

Related

Is there a better way to multiply input values then what I have?

I'm trying to add or multiply input values to come to two total, this was working without trying to use a for loop. My intention was to match the selectors with the various iterations of i that are at the end of each string. I have a fiddle example here : https://jsfiddle.net/shiataz12/Lo1yek2g/69/
I've tried to copy and paste the function while manually inputting names for each iteration, however it doesnt quite work either as only the first two and last two checkbox do anything if clicked.
HTML :
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<<----Assume checkbox --> id --> is $qri and $qri = "qr"."$i";
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr1" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr1"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr1"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr1"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr1" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr1"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot" name="pricef2" value="">
<input type="text" value="2" id="countrows"><br><br>
<label for="checkbox1">Standard</label>
<input type="checkbox" name="checkbox1" class="quip" value="125" id="qr2" checked><br><br>
<label for="checkbox1">Equipped</label>
<input type="checkbox" name="checkbox1" class="quip" value="225" id="qr2"><br><br>
<label for="checkbox3">GPS</label>
<input type="checkbox" name="checkbox3" value="20" id="qr2"><br><br>
<label for="checkbox4">booster</label>
<input type="checkbox" name="checkbox4" value="20" id="qr2"><br><br>
<label for="checkbox5">One tent</label>
<input type="checkbox" name="checkbox5" class="tents" value="60" id="qr2" checked><br><br>
<label for="checkbox6">Two tents :</label>
<input type="checkbox" name="checkbox6" class="tents" value="80" id="qr2"><br><br>
Daily :<span id="dailytotal2"> </span><br><br>
Total :<span id="lengthtotal2"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot2" name="pricef1" value="">
<br>
// Hidden element for length rate to use in $_POST, shown for now
<input tyep="text" id="lengthtot2" name="pricef2" value="">
$(function() {
$("input.quip").change(function() {
$("input.quip").not(this).prop("checked", false);
});
$("input.tent").change(function() {
$("input.tent").not(this).prop("checked", false);
});
$(function() {
//get the values of the selected options
var counter = ("#countrows").val();
var i = 0;
for (i = 1; i <= counter; i++){
let v = $.map($('#qr' + i).is("checked"), function(i) {
return parseFloat($(i).val());
});
let s = v.reduce((a, b) => a + b); //sum them up to a daily total
console.log(v);
$('#dailytotal' + i).text('R' + s + '/day');
$('#lengthtotal' + i).text('R' + s * parseFloat($("#nosday").val()) + '/day');
$('#dailytot' + i).val(s);
$('#lengthtot' + i).val(s * parseFloat($("#nosday").val()));
}
});
});
The example provided assumes that there are two rows of a database and so i = 2 so id's should change to qr2 for i=2. I expected this to work by using the number of rows as a base to use a for in Jquery, limited to the number of rows so that each section can act independently, however they continue to react to the function together and do not show any values.
I thought perhaps if i could get it working for now and copy/paste code with individual id's that'd give me time to work on a better solution however it doesn't work as i'd expected. with map would it be better to declare an array prior and can i use the same id across inputs as an array? It makes calculation easier, although i guess i could use the name selector.
Hopefully someone can guide me to the correct answer, this is driving me up the wall.
Trimmed it down a little. There are other issues. The "Labels for" are suppose to refer to the id of the labelled element. The "Standard" and "Equipped" options are really radio buttons, not checkboxes, since presumably you can have one of the others. I renamed some of the classes and id's, although you may not need all of those. I am presuming that maybe you are generating the HTML dynamically and just add the value of "i" for a suffix, depending upon how many row you have. I actually just made changes to the first row and rewrote the JS to give you a total for the items form the values in the input elements for that row. Not sure exactly how you are calculating those totals, since $("#multiplier") I do not think is even in your code. You will have to look that over and see what you want, but the totals look like it is working.
<--- HTML SECTION --->>
// obtained from $nosday = $_POST['nosday'];
<br>
// value is normally $nosday
<br>
<input type="hidden" value = "1.5" id = "multiplier">
<input type="text" value="5" id="nosday"><br><br>
// obtained from $count = mysqli_num_rows($result);
<br>
// value is normally $count;
<br>
<input type="hidden" value="2" id="countrows"><br><br>
// Assume checkbox is $qri and $qri = "qr"."$i";<br>
<label for="standard1">Standard</label>
<input type="radio" name="equipment" id ="standard1" class="quip qr1" value="125" checked><br><br>
<label for="equipped1">Equipped</label>
<input type="radio" name="equipment" id ="equipped1" class="quip qr1" value="225" ><br><br>
<label for="gps1">GPS</label>
<input type="checkbox" name="gps" id ="gps1" value="20" class ="qr1"><br><br>
<label for="booster1">booster</label>
<input type="checkbox" name="booster" id ="booster1" value="20" class ="qr1"><br><br>
<label for="tents1">One tent</label>
<input type="checkbox" name="tents" id ="tents1" class="tents qr1" value="60" checked><br><br>
<label for="twotents1">Two tents :</label>
<input type="checkbox" name="twotents" id ="twotents1" class="tent qr1" value="80"><br><br>
// assume id="#dailytotal" where dailytotal = "dailytotal"."$i";
<br>
Daily :<span id="dailytotal1"> </span><br><br>
// Assume id = "$lengthtotal" where $lengthtotal = "lengthtotal"."$i";
<br>
Total :<span id="lengthtotal1"> </span><br><br>
// Hidden element for daily rate to use in $_POST, shown for now
<br>
<input tyep="text" id="dailytot1" name="pricef1" value="">
<br>
The JS probably needs to be tweaked since I do not know how you are generating the HTML. As it is, it should calculate the totals for all "i" rows on load, and it would not be hard to add something to have it calculate the total for the "ith" row. That should give you something to work with.
function Calc() {
//get the values of the selected options
var counter = $("#countrows").val();
let totals = [];
for (i = 1; i <= counter; i++) {
totals[i] = 0;
$.each($('.qr' + i + ':checked'), function() {
totals[i] += parseInt($(this).val());
});
console.log(totals[i]);
$('#dailytotal' + i).text('R' + totals[i] + '/day');
$('#lengthtotal' + i).text('R' + totals[i] * parseFloat($("#multiplier").val()) + '/day');
$('#dailytot' + i).val(totals[i]);
$('#lengthtot' + i).val(totals[i] * parseFloat($("#multiplier").val()));
}
}
Calc();
$("[class*=qr]").on("change", function(e) {
e.preventDefault();
Calc();
});
"[class*=qr]" isn't the best really because *=qr is not that specific really, depending upon your markup. Also, not clear that you are using form tags anywhere either.

JQuery get attributes of radio input inside a group

Here is my PHP code to generate dynamic form inputs
echo '<div class="radio" id="'.$questionID.'">';
foreach ($options as $key => $opt_value) {
$option_text = $opt_value->option_text;
$question_id = $opt_value->question_id;
$is_correct = $opt_value->is_correct;
$option_id = $opt_value->id;
echo '<label>
<input type="radio" class="optionChecked" name="optionCheck'.$questionID.'" id="'.$option_id.'" value="'.$option_id.'" data-id="'.$option_id.'" data-title="optionCheck'.$questionID.'"><p>
'.$option_text.'</p>
</label>';
}
echo '</div>';
I am generating radio buttons inside div. Each div for a question and the radio inputs are its variable options.
JQuery to get data for each question:
function fetchAttempt(){
var jsonArr = [];
$('.radio').each(function() {
var selected_option = -1;
var is_skipped = 1;
var correct_option = 0;
var quesId = $(this).attr('id');
var quesOptns = "optionCheck"+quesId;
$('.'+questOptns).each(function() {
if(($(this).val()) == 1){
correct_option = $(this).attr("id");
}else{
correct_option = -1;
}
});
jsonArr.push({
correct_option: correct_option,
is_skipped: is_skipped,
correct_option: is_right,
selected_option: selected_option,
temp_id: temp_id,
question_id: quesId
});
});
return JSON.stringify(jsonArr);
}
I struggled for more than 5 hours ... still unable to get the access the checked radio value inside a group.
I tried all possible ways... to get the value of checked radio inside a div by a name ... but it never worked.
I don't have your $options variable, so I created my own questions
form to simulate your situation.
To select a radio button we have only to use this jQuery $("input[type=radio]:checked") then we must check everyone of these checked radio buttons using the function .each().
Here is a full example of what you should do:
$("#submit").on("click",function(){
$("input[type=radio]:checked").each(function(){
console.log($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio" id="form1">
<label>Question 1
<input type="radio" class="optionChecked" name="name1" id="'id1" value="value1" data-id="option1" data-title="question1"></label><br>
<label>Question 2
<input type="radio" class="optionChecked" name="name2" id="'id2" value="value2" data-id="option2" data-title="question2"></label><br>
<label>Question 3
<input type="radio" class="optionChecked" name="name3" id="'id3" value="value3" data-id="option3" data-title="question3"></label><br>
<label>Question 4
<input type="radio" class="optionChecked" name="name4" id="'id4" value="value4" data-id="option4" data-title="question4"></label><br>
<label>Question 5
<input type="radio" class="optionChecked" name="name5" id="'id5" value="value5" data-id="option5" data-title="question5"></label><br>
<button type="button" id="submit"> Submit</button>
</div>

Jquery split variable back from PHP json (checkbox:checked)

In this code jquery get the data back from php and i would like to get jquery explode one of the variable where multiple auto are stored and finally get the specific checkbox checked
json_reponse_from_PHP: "auto1; auto3; auto4".
$(document).on("click", "#update", function(e) {
e.preventDefault();
var datas = 'pg/post.php';
$.getJSON(datas, function(data) {
$.each(data, function( key, value ) {
$('input[name=' + key + '], select[name=' + key + '], textarea[name=' + key + ']').val(value);
});
});
});
<div>
<input type="text" name="name" value="" />
<input type="text" name="name" value="" />
</div>
See example:
<input type="checkbox" name="auto[]" checked="checked" value="auto1" />
<input type="checkbox" name="auto[]" value="auto2" />
<input type="checkbox" name="auto[]" checked="checked" value="auto3" />
<input type="checkbox" name="auto[]" checked="checked" value="auto4" />
<input type="checkbox" name="auto[]" value="auto5" />
<input type="checkbox" name="auto[]" value="auto6" />
Can you help me to find
If you want to check a checkbox you don't use val() you use prop('checked', true)
Since you have array naming on elements you can't match the specific name so you will need to use the returned value to help target the checkboxes.
Also what you are sending from server doesn't match the names anyway.
$.each(data.split(';'), function(_, val ) {
$(':input[value=' + val +']').prop('checked',true);
});
It makes no sense either not to send array from server instead of json_encoding a delimited string in your php

PHP link with Input boxes but no from [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Combine $_GET variables before Submit
I am not really sure if this is possible but here is the problem I cant figure out.
I need a way to have two boxes with a price min and max and a button that send the user to a link like this. where A is min price and B is max price.
End result Link.
domain/index.php?a=price_range_A_B
I can not use a from but i can use Input fields. Any ideas?
You will need to do this with javascript. In the "Submit" button/link/whatever click action, fetch the values of the fields and construct the url. Then either send the browser there, or do an ajax request, depending on your needs.
eg.
<script>
function doSubmit() {
var fieldA = document.getElementById('fieldA'),
fieldB = document.getElementById('fieldB'),
valA = fieldA.value,
valB = fieldB.value,
url = "/index.php?a=price_range_" + valA + "_" + valB;
window.location = url;
}
</script>
<input id="fieldA" />
<input id="fieldB" />
<input type="button" onclick="doSubmit();" />
use this function onclick of button
function value_change(){
var a=document.getElementById('box1').value();
var b=document.getElementById('box2').value();
document.getElementById('linkdiv').innerHTML()="domain/index.php?a=price_range_"+A+"_"+B;
}
where box1 and box2 are ids of max and min price respectively and linkdiv is id od di that shows the link
<input id="one" type="text" />
<input id="two" type="text" />
<input id="go" type="button" value="button"/>
$("#go").click(function(){
window.location = "http://google.com/a=price_range_" + $("#one").val() + '_' + $("#two").val();
});​
http://jsfiddle.net/kTUu5/
Try this code,
HTML
<div>
Max: <input type="textbox" id="max" name="max" value="" />
<br />
Min: <input type="textbox" id="min" name="min" value="" />
<br />
<input type="button" name="btn" value="Submit" onclick="sendData()"/>
</div>
Javascript
function sendData(){
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
if(!max || !min){
alert('Enter max and min value');
return false;
}
window.location = "http://domain/index.php?a=price_range_"+min+"_"+max;
}​
Demo: http://jsfiddle.net/muthkum/FhY5a/
Yes. You can do it if you can use any client side scripting Like javascript or 'Jquery'. You have to bind a click event fubnction on that Submit button. So once you click on that button it will call a function which take the value of those inputbox and prepared a url and send you to that location.
Example:
<input type="text" name="minPrice" id="min" value="" />
<input type="text" name="maxPrice" id="max" value="" />
<button type="button" name="Submit" onClick="doSubmit()">Submit</button>
Now Your doSubmit() function.
function doSubmit(){
var minPrice=document.getElementById('min').value;
var maxPrice=document.getElementById('max').value;
var location='domain/index.php?a=price_range_'+minPrice+'_'+maxprice+'';
window.location=location;
}
Now on the index page you can easily explode $_REQUEST['a'] variable like this way
$var=$_REQUEST['a'];
$explodedVar=explode('_',$var);
//print_r($explodedVar);
$minPrice=$explodedVar[2];
$maxPrice=$explodedvar[3];

how to count all check boxes in a form (Javascript)

I have number of check boxes that gets generated dynamically. So i do not know how many check boxes gets generated each time. I need to have some JavaScript ways to count the total numbers of check boxes in a form.
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
I can not change the name of the check boxes as i need to send the values to serverside PHP script as an array.
Since all other answers are jquery based, I'll offer a pure javascript solution. Assuming the following form:
<form id="myform">
<input type="checkbox" value="username1" name="check[0]" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" /><br/>
</form>
You could compute the number of checkbox elements with the following logic:
<script type="text/javascript">
var myform = document.getElementById('myform');
var inputTags = myform.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
BTW: As others have noted, the id attribute in any HTML tag should be unique within the document. I've omitted your id="1" attributes in my sample HTML above.
Update:
If you simply want to count all checkbox elements on the entire page without using a containing form element, this should work:
<script type="text/javascript">
var inputTags = document.getElementsByTagName('input');
var checkboxCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
alert(checkboxCount);
</script>
In Plain JavaScript:
var myForm = document.forms[nameOrIndex];
var inputs = myForm.getElementsByTagName('input');
var checkboxes = [];
for(var i=0;i<inputs.length;i++){
if(inputs[i].getAttribute('type').toLowerCase() == 'checkbox'){
checkboxes.push(inputs[i]);
}
}
alert(checkboxes.length);
I would go with:
alert(document.querySelectorAll("input[type=checkbox]").length);
If you wanted a particular form you would need to select the form and use that as a base for your call to querySelectorAll instead of document or change the selector to include the form.
<form id="aForm">
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
<form id="bForm">
<input type="checkbox" value="username1" name="check[0]" id="1" /><br/>
<input type="checkbox" value="userusername2" name="check[1]" id="1" /><br/>
<input type="checkbox" value="userusername3" name="check[2]" id="1" /><br/>
</form>
Then use:
alert(document.querySelectorAll("#aForm > input[type=checkbox]").length); //shows 2
alert(document.querySelectorAll("#bForm > input[type=checkbox]").length); //shows 3
Note: The Selectors API is only available in newer browsers starting with: Internet Explorer 8, Firefox 3.5, Safari 3.1, Chrome 1, and Opera 10.
alert( $("form input[type='checkbox']").length );
Will give you all the checkboxes in a form, using jQuery.
As you tagged your question with php and you seem to use some sort of numbering already for the form fields, you can also just echo that php counter to a javascript variable:
<?php
//
?>
<script language="javascript" type="text/javascript">
var checkbox_counter = <?php echo $your_counter_in_php; ?>
</script>
<?php
//
?>
By the way, in html you can only have one id on a page and it can´t start with a number.
you could use jquery
var len = $('input:checkbox').length;
alert(len);
WORKING DEMO
if you have jQuery you could do something like
alert ($(':checkbox').length ());
If not then you'll have to document.getElementsByTagName ('input'), iterate over the collection you get back and increment a counter every time you encounter one with its type attribute set to checkbox.

Categories