Adding to array with specified index in javascript - javascript

I am new to javascript, I have created 2 functions, createInput() which creates input boxes with a name parameter when called and appends them to a tag, newTwo() which calls createInput() twice with two different names.
I cannot seem to provide a index for the two name elements and make it increment each time the newTwo() is called. I need this so that I can trace the field values as a pair.
function createInput(name)
{
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", name);
var form = document.getElementById("foobar");
form.appendChild(input);
}
function newTwo()
{
var $i = 0;
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
When I call newTwo(), input fields are created with the array index as follows.
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
If I call it again, the next two fields will be
<input type="text" name="first_name[0]" />
<input type="text" name="last_name[0]" />
my desired output for the previous second call would be
<input type="text" name="first_name[1]" />
<input type="text" name="last_name[1]" />
Any suggestions? Thanks in advance.

Because you have var $i = 0; inside the function, you're creating a new variable and initializing it to 0 every time you run the function. If you want to use a variable that maintains its value between function calls, you need to declare it outside the function. For example:
var $i = 0;
function newTwo()
{
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
}
Or if you really want to avoid making $i global you could create a IIFE around it like this:
var newTwo = (function() {
var $i = 0;
return function() {
createInput("first_name[" + $i + "]");
createInput("last_name[" + $i + "]");
$i++;
};
})();
Note that there are subtle differences between this and the previous version. See these questions for more details:
How do JavaScript closures work?
var functionName = function() {} vs function functionName() {}

Related

HTML Dynamic Form empty array value

I have some dynamic inputs that are supposed to insert into an array value then passed to my PHP forloop so I can insert into my MYSQL DB.
I am having an issue where my array is coming up empty.
At first, I was getting an error saying invalid object passed to the array. I added
if (is_array($faqQuestions) || is_object($faqQuestions)) {
}
arround my foreach loop to figure out that is not getting the correct values.
So I know my issue has to be in my form.
So the first visible input is as follows...
<div id="dynamicInput">
<input name="faqQuestions[]" type="name" class="form-control seller input" placeholder="Question" value="<?php echo $question ?>">
<textarea class="about-textarea" name="faqAnswers[]" rows="3" placeholder="Answer"><?php echo $answer; ?></textarea>
</div>
<input class="add-another-button" type="button" value="Add Another +" onClick="addInput('dynamicInput');">
So the two input names are faqQuestions[] and faqAnswers[].
If the user click adds another, the same form inputs should appear with the same name as an array.
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Faq " + (counter + 1) + " <br><input name='faqQuestions[]' type=\"name\" class=\"form-control seller-input\" placeholder=\"Question\"\n" +
" value=\"<?php echo $question ?>\">\n" +
" <textarea class=\"about-textarea\" name='faqAnswers[]' rows=\"3\"\n" +
" placeholder=\"Answer\"><?php echo $answer; ?></textarea>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
And the PHP that is capturing the array
$faqQuestions = $_POST["faqQuestions"];
if (is_array($faqQuestions) || is_object($faqQuestions)) {
foreach ($faqQuestions as $question) {
//I have tried assigning each variable like $q1 = $question[0]
}
}
I have been trying to figure out why my array is empty but I just dont see it.
Hope someone out there can help! Thanks

Storing / passing a variable to another function

I have a simple problem storing and passing a variable from one function to another. My script should work like this:
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="write()">
<p id="ag"></p>
If somebody enters a value in the input field "ip1" and presses the "check_button", the value should be stored in a variable. This variable should be written in the innerHTML of "ag" when the "write_button" is clicked.
This is my JS. I am aware that this cannot work, I just don't know how to do it properly. I found similar problems but the solution always seems to complex for a beginner like myself to understand. A very easy solution would be very much appreciated!
function check_text() {
var ui = document.getElementById('ip1').value;
}
function write() {
document.getElementById('ag').innerHTML = ui;
}
You should declare variable outside the function:
it must work
var ui = 0;
function check_text() {
ui = document.getElementById('ip1').value;
}
function writeL() {
document.getElementById('ag').innerHTML = ui;
}
<input type="text" id="ip1" >
<input type="button" id="check_button" value="checking" onclick="check_text()">
<input type="button" id="write_button" value="write" onclick="writeL()">
<p id="ag"></p>
There are of course more than one way to process your value. The Snippet below uses the HTMLFormControlsCollection. Details are commented in the Snippet. BTW, I had to get rid of one of the buttons, it would probably hinder your understanding rather than aid it. It's better to visualize what's happening by watching the console.
SNIPPET
/***NOTE: Any comment having a pencil icon: ✎
|| means that the expression/statement is there...
||...to show an alternate way. Although they...
||...aren't used in the functions, they can be...
||...used instead of it's counterpart.
*/
function processData() {
// Reference the <form> by id or...
var form1 = document.getElementById('form1');
// ✎
/*1*/
console.log('1. This is ' + form1.id + '\n');
/*...or by HTMLFormControlsCollection...
||...reference <form> as the first <form>...
||...the .forms is an array-like object...
||...the [0] is the index indicating which...
||...<form> it's referring to. This is easily...
||...determined since there's only one <form>...
||...on the page.
*/
var formA = document.forms[0];
/*2*/
console.log('2. This is ' + formA.id + '\n');
// We'll continue using the HTMLFormControlsCollection
/* This is using previously declared formA to...
||...reference it's .elements property. The...
||...elements property is like the .forms...
||...except that it refers to a <form>'s...
||...field form elements like <input> and ...
||...<output>
*/
var formUI = formA.elements;
/*3*/
console.log('3. This is an ' + formUI + '\n');
// We can get the number of form control elements
var qty = formUI.length;
// ✎
/*4*/
console.log('4. form1 has ' + qty + ' form control elements\n');
/* Get the value of text1 by using the object formUI...
||...the name of <input>, and the .value property.
*/
var TXT1 = formUI.text1.value;
/*5*/
console.log('5. The value of text1 is ' + TXT1 + '\n');
/* We can get the same result by referencing <input>...
|| ...by it's index position in the formUI object...
|| This expression is getting the value of the first...
||...form field element of the <form> or formUI object
*/
var TXTA = formUI[0].value;
// ✎
/*6*/
console.log('6. The value of Text1 is still ' + TXTA + '\n');
/* Return the value of TXT1
|| This function returns a value, so it can be...
||...assigned to a var as a value and it can be...
||...passed through another function like a...
||...parameter.
*/
return TXT1;
}
/* This will pass a value...
||...reference the <output>...
||...and set <output> value to...
||...given value
*/
function displayData(value) {
var output1 = document.getElementById('output1');
output1.value = value;
}
/* When button1 is clicked...
||...store the return of processData() in a var...
||...then pass that var to displayData() function
*/
document.getElementById('button1').onclick = function(event) {
var VAL = processData();
displayData(VAL);
}
input {
font: inherit
}
<form id='form1' name='form1'>
<input type="text" id="text1" name='text1'>
<input type="button" value="display" id='button1'>
<br/>
<output id="output1" name='output1'></output>
</form>
You can do it easily with jQuery like this:
var enteredValue = "";
$("#check_button").on("click", function() {
enteredValue = $("#ip1").val();
});
$("#write_button").on("click", function() {
$('#store_value').html(enteredValue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ip1" />
<input type="button" id="check_button" value="checking" />
<input type="button" id="write_button" value="write" />
<p id="store_value"></p>

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

Value of checkbox is [object HTMLInputElement]

I have two forms right next to each other.
This right here is Form one
<form>
<input type="radio" id="genderOne" name="genderOne" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
Form 2 is simply the same, with the difference that the IDs of the checkboxes are genderThree and genderFour and the name is genderTwo. The checkbox has also another name "ageCheckTwo".
Now I want, if everything is filled in correctly to open up a php.site with the parameters the user typed in.
Everything works, except for the second form, but only the gender.
This is the JavaScript-code for that part
if(document.getElementById('genderOne').checked || document.getElementById('genderTwo').checked)
{
if(document.getElementById('genderOne').checked)
{
var genderOne = $('#genderOne').val();
urlString += "&genderOne=" + genderOne;
}
if(document.getElementById('genderTwo').checked)
{
var genderTwo = $('#genderTwo').val();
urlString += "&genderOne=" + genderTwo;
}
}
if(document.getElementById('genderThree').checked || document.getElementById('genderFour').checked)
{
if(document.getElementById('genderThree').checked)
{
var genderOne = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderTwo = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
}
And just to be sure, this is the second form
<form>
<input type="radio" id="genderThree" name="genderTwo" value="Mann"><label for="genderThree">Maennlich</label>
<input type="radio" id="genderFour" name="genderTwo" value="Frau"><label for="genderFour">Weiblich</label><br><br>
<input type="checkbox" id="ageCheckTwo" id="ageCheckTwo" name="ageCheckTwo"><label for="ageCheckTwo">Ist er/sie ueber 18?</label>
</form>
But, the URL is now, when I checked all parameters like this:
http://localhost/mojoGerman/questions.php?nameOne=fdgh&nameTwo=hj&genderOne=Mann&genderTwo=[object HTMLInputElement]
While it should display the gender of the second person at the end. What am I doing wrong?
Simple typographic errors here:
if(document.getElementById('genderThree').checked)
{
var genderThree = $('#genderThree').val();
urlString += "&genderThree=" + genderThree;
}
if(document.getElementById('genderFour').checked)
{
var genderFour = $('#genderFour').val();
urlString += "&genderFour=" + genderFour;
}
This is why cutting and pasting is a bad idea. Make yourself a simple function:
function addIfChecked(name) {
var val = $('#' + name).val();
return val ? "&" + name + "=" + encodeURIComponent(val) : '';
}
urlString += addIfChecked("genderOne") +
addIfChecked("genderTwo") +
addIfChecked("genderThree") +
addIfChecked("genderFour");
or something like that. Better yet, give the checkboxes a class so that you can find them with a selector and iterate over them via jQuery.
var genderOne = $('#genderThree').val(); // get value in genderThree here
urlString += "&genderTwo=" + genderThree;
Try this -
if(document.getElementById('genderThree').checked) {
var genderThree = $('#genderThree').val();
urlString += "&genderTwo=" + genderThree;
}
if(document.getElementById('genderFour').checked) {
var genderFour = $('#genderFour').val();
urlString += "&genderTwo=" + genderFour;
}
The issue is using the wrong variable names for genderThree and genderFour
But you could simplify the whole thing to
$('input[type="radio"][name^="gender"]:checked').each(function(){
urlString += '&' + this.name + '=' + this.value;
});
I have not understood completely what are you trying to do , but seeing at your code, I think It can be optimised by using different practice
<form>
<input type="radio" id="genderOne" name="genderOne[]" value="Mann"><label for="genderOne">Maennlich</label>
<input type="radio" id="genderTwo" name="genderOne[]" value="Frau"><label for="genderTwo">Weiblich</label><br><br>
<input type="checkbox" id="ageCheck" id="ageCheck" name="ageCheck"><label for="ageCheck">Bist du ueber 18?</label>
</form>
If you want to have same key on your query string genderOne , you can explicity declare your name as array in the name attribute. On your php script you can get this value using GET method to obtain those values
//php
echo $_GET['genderOne'][0];//returns first checked gender value
echo $_GET['genderOne'][1];//returns 2nd checked gender value
You don't even need the javascript for this if I understood what you are trying to achieve.

Add a checkbox for the innerHTML in javascript

I have a page which contains a 10 items(formatted list).Here in this page I need to add check box for each item and add the item as the value to each check box.when the user click on the check box the selected value should be passed to a new page.Can anyone help me how to add a check box for the innerHTML in java script.
Code:
var newsletter=document.getElementById("block-system-main");
var districolumn=getElementsByClassName('view-id-_create_a_news_letter_',newsletter,'div');
if(districolumn!=null)
{
var newsletterall=newsletter.getElementsByTagName('li');
alert(newsletterall[0].innerHTML);
var all=newsletter.innerHTML;
newsletter.innerHTML="<input type='button' onclick='changeText()' value='Change Text'/>";
}
function changeText()
{
alert("dfgsdg");
}
I don't exactly understand what each part of your code is doing, but i'll try and give a general answer:
In your HTML, do something like this:
<form id="myForm" action="nextPage.com">
<div id="Boxes"></div>
</form>
Change the above names to wherever you want your checkboxes to be written.
And your function:
function changeText()
{
for(var i=0 ; i < newsletterall.length ; i++)
{
var inner = document.getElementById("Boxes").innerHTML;
var newBox = ('<input type="checkbox" name="item[]" value="' + newsletter[i] + '>' + newsletterall[i]);
document.getElementById("Boxes").innerHTML = inner + newBox;
}
document.getElementById("myForm").submit();
}
The last line of code submits the checkboxes automatically. If you don't want that, remove that line, and add a submit button to the form myForm.
​
$('ul​​​#list li').each(
function() {
var me = $(this),
val = me.html(),
ckb = $('<input type="checkbox" />');
ckb.click(function() {
var where=val;
window.location.href='http://google.com/?'+where;
});
me.html('');
me.append(ckb).append($('<span>'+val+'</span>'));
}
);​​​​

Categories