div inside form not being 'seen' - javascript

I have a div inside my form which is filled with a field based on the value of the select box above it. This field always comes back as 'null' when submitted, I put a div around other parts of the form to test if it was in fact the div itself and each field with a div around it kept coming back as 'null'.
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
So the code above works fine its when i add a div inside i get 'null' like below;
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<!--This div below is called every time I want to add a new 'instance' of this form
this div works fine, its when i add a div inside that one I get 'null'-->
<div id="readnode" style="display: none">
<select name="rank">
<option disabled="disabled" selected="selected">Rating</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
<div id='testdiv'>
<select name="time">
<option disabled="disabled" selected="selected">Time</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
<option value="0">0</option>
</select>
</div>
<input type="button" value="X"
onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
Whats my best way around this? and how would I go about doing it?
EDIT: The Div 'readnode' is called and placed inside the form when needed, replacing the div 'writenode' which is seen inside the form above. This div works perfectly fine. When i add another div (testdiv) inside the 'readnode' any fields placed inside the new div (testdiv) always come back as null when using $_get.
EDIT2:
Function that puts the readnode in place of the writenode,
<script type="text/javascript">
/* Set the counter that will increase every time
the user adds a new language*/
var counter = 0;
function addlanguage()
{
// Ask the user for input
var language = prompt("Language Name","");
if (language == "" || language == null)
{
alert("Please enter a language.");
}
else
{
counter++;
// Find the element to be copied
var newNode = document.getElementById('readnode').cloneNode(true);
newNode.id = '';
newNode.style.display = 'block';
var newField = newNode.childNodes;
// Give all fields a unique value
for (var i=0;i<newField.length;i++)
{
var theName = newField[i].name;
var theId = newField[i].id;
if (theName)
{
newField[i].name = theName + counter;
}
if (theId == "languagename")
{
// Change the field to the user input
newField[i].innerHTML = language;
}
if (theName == "lang")
{
// Replace the hidden field with the correct language
newField[i].value = language;
}
}
// Insert the elements
var insertHere = document.getElementById('writenode');
insertHere.parentNode.insertBefore(newNode,insertHere);
}
}
</script>
and this is the php;
<?php
if ($_GET["time1"] == null)
{ ?>
<form>
<span id="writenode"></span>
<input type="button" value="Add language" onClick="addlanguage()" >
<input type="submit" value="Submit" >
</form>
<?php
}
else
{
$final = 0;
$i = 1;
while($final == 0)
{
$gettime = "time" . $i;
$getRank = "rank" . $i;
$time = $_GET[$gettime];
$rank = $_GET[$getRank];
if ($language == "")
{
$final = 1;
}
if ($final == 0)
{
// Show the user the input
echo("<p>Your <strong>$time</strong> is <strong>$rank</strong>.</p>");
}
$i++;
}
} ?>

When you put it inside a div, it's no longer part of newNode.childNodes, so you never get to set the name properly. You'll have to check childs of childs or use jQuery to simplify things.
for (var i=0;i<newField.length;i++)
{
var subField = newField.childNodes;
for (var i=0;i<subField.length;i++) {
var theName = subField[i].name;
var theId = subField[i].id;
// ...
}
}

Related

textarea stays empty despite setting its .innerHTML

I have 2 fields from which i select some values to be concatenated and posted in a div from which, on submit, i save into a database.
So i select values from 'tags1' and 'tags2' and after i push the button 'adauga' the concatendated values show in the textarea with id 'd11'. Up untill now everythign works fine, untill i press the button 'Clear' to clear the div from values. After that if i try to add values again it does not work, nothing is displayed in the 'd11' div.
Below is the html and the script:
<select name="tehnologie[]" id="tags2" size="13" multiple = "multiple">
<option value="GSM">GSM</option>
<option value="UMTS">UMTS</option>
<option value="LTE">LTE</option>
<option value="NR (5G)">NR (5G)</option>
<option value="Radiodifuziune AM">Radiodifuziune AM</option>
<option value="Radiodifuziune FM">Radiodifuziune FM</option>
<option value="TV digital">TV digital</option>
<option value="TV analogic">TV analogic</option>
<option value="PMR/PAMR">PMR/PAMR</option>
<option value="Satelit">Satelit</option>
<option value="Aero">Aero</option>
<option value="RAmator">RAmator</option>
<option value="Alte aplicatii radio">Alte aplicatii radio</option>
</select>
<input name="banda_buffer" type="number" list="frecvente" id="tags1" >
<datalist id="frecvente">
<option value="800">800</option>
<option value="900">900</option>
<option value="1800">1800</option>
<option value="2100">2100</option>
<option value="2600">2600</option>
</datalist>
<input hidden type="text" id="tags3" >
<input type="button" id="adauga" onClick="myFunction1();" name="adauga" value="+" />
<textarea id="d11" name="banda" rows="5" cols="300" readonly class="form-control input-md"></textarea>
<button type="button" onclick="ClearFields();">Clear</button>
<input type="submit" id="submit" name="submit" onClick="alerta();" value="Salveaza" class="btn btn-primary">
And the js:
var cpvuri1=[];
var AreaToDisplay1=document.getElementById('d11');
function myFunction1(){
var text1=document.getElementById('tags1').value;
var text2=document.getElementById('tags2').value;
var text3= text2 +' - '+ text1;
cpvuri1.push(text3);
AreaToDisplay1.innerHTML=cpvuri1;
}
function ClearFields() {
document.getElementById("d11").value = "";
document.getElementById("tags1").value = "";
document.getElementById("tags2").value = "";
document.getElementById("tags3").value = "";
cpvuri1=[];
}
function alerta() {
document.getElementById("tags3").value = cpvuri1;
}
You can use value rather than innerHTML
function myFunction1(){
var text1=document.getElementById('tags1').value;
var text2=document.getElementById('tags2').value;
var text3= text2 +' - '+ text1;
cpvuri1.push(text3);
AreaToDisplay1.value=cpvuri1;
}

How to have access inside div element?

i am trying to create simple Rock,paper, scissor game,
but i have some case, i want to have access on div which id is firstplayer, also this div has increment function, which increases value by 1... if in form field i choose 12, an when i press "firstplayer" and it value will increase to 12, i want to console.log("you win"), i tried a lot, but it's not works, what can i do, to solve this problem?
<!-----my html---->
<form action="#">
<label for="numbers">Game up to:</label>
<select id="form" >
<option value="7" >7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="submit" id="submit">
</form>
<div>
<h4 onclick="increment()">Firstplayer</h4>
<div id="firstplayer">
</div>
</div>
///my js
const firsPlayer = document.getElementById("firstplayer");
const Form = document.getElementById("submit");
form.addEventListener("input", function(event){
event.preventDefault();
if (event.target.value==="12"){
return playerwin()
}
})
var x=0;
function increment(){
return firsPlayer.innerHTML = ++x;
}
// i tried this but it's not working
function playerwin(){
if(firsPlayer.childNodes[0].nodeValue == 12){
console.log("you win")
}
}
my code here https://codepen.io/kafka2001/pen/LYpmexe
Not exactly sure what the final result should be but please check the code below that illustrates how it could basically work. Just adapt it to your needs to obtain the desired result.
const firsPlayer = document.getElementById("firstplayer");
const select = document.getElementById("select");
var x = 0;
function increment() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + 1;
}
function addSelected() {
firsPlayer.innerHTML = Number(firsPlayer.innerHTML) + Number(select.value);
}
function playerwin() {
if (firsPlayer.childNodes[0].nodeValue == 12) {
console.log("you win")
}
}
<select id="select">
<option value="7">7</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<input type="button" onClick="increment();" value="Increment">
<div>
<h4 onclick="addSelected()">Firstplayer</h4>
<div id="firstplayer"></div>
</div>

Trigger Button Click on Enter in HTML

I have researched this through Stack, W3, and others but the solutions that I fiond there don't work. Below is part of my html code, I did my best to try and keep it neat (not an expert by any means).
<select name="ctl00$ContentPlaceHolder1$ddlSearchCriteria" id="ctl00_ContentPlaceHolder1_ddlSearchCriteria" style="width:150px;">
<option value="LastName">Last Name</option>
<option value="FirstName">First Name</option>
<option value="Phone">Phone Number</option>
<option value="Department">Department</option>
<option value="Division">Division</option>
<option value="Location">Location</option>
<option value="Title">Title</option>
<option value="Email">Email Address</option>
<option value="Keywords">Keywords</option>
</select>
<div style="height:10px"></div>
<input name="ctl00$ContentPlaceHolder1$txtSearchString" type="text" id="ctl00_ContentPlaceHolder1_txtSearchString" style="width:160px;">
<button type="button" name="ctl00$ContentPlaceHolder1$Button1" id="ctl00_ContentPlaceHolder1_Button1" style="position: absolute; height:22px; " onclick="myFunction()">Go</button>
<div style="height:5px;"></div>
</td>
<td style="width:48%; height: 27px;"> </td>
</tr>
</tbody>
</table>
</div>
<script>
var GoToURL = 'http://bccportal01/webapps/agency/epdsearch/Search.aspx?op=' + dropDownChoice + '&str=' + inputText;
function myFunction()
{
var dropDownChoice = document.getElementById("ctl00_ContentPlaceHolder1_ddlSearchCriteria").value;
var inputText = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchString").value;
var GoToURL = 'http://bccportal01/webapps/agency/epdsearch/Search.aspx?op=' + dropDownChoice + '&str=' + inputText;
window.open(GoToURL);
}
</script>
I'm trying to make it so that when you click enter the submit button activates. I have tried https://www.w3schools.com/howto/howto_js_trigger_button_enter.asp and Trigger function on Enter keypress as examples.
But this isn't working, all it does is break my code. Not sure if I'm putting it in the wrong spot. I added it right below var inputText in the Function.
You need to add keyup event listener on the input textfield
Add this to your javascript
var input = document.getElementById("ctl00_ContentPlaceHolder1_txtSearchString");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("ctl00_ContentPlaceHolder1_Button1").click();
}
});
Working Example
Replace type="button" with type="submit"
Add a <form onsubmit="myFunction">
Wrap your <select> with the <form>:
<form onsubmit="myFunction">
<select>...</select>
</form>
Here's what your function should do to prevent the form from submitting (we didn't include an "action" so it will submit to itself)
function myFunction(event){
// Stop the form from submitting (default functionality)
event.preventDefault();
...
}
Your code should look similar to this (added a fix for obtaining the select list value the proper way)
<form onsubmit="myFunction">
<select id="mySelect">
<option value="LastName">Last Name</option>
<option value="FirstName">First Name</option>
<option value="Phone">Phone Number</option>
<option value="Department">Department</option>
<option value="Division">Division</option>
<option value="Location">Location</option>
<option value="Title">Title</option>
<option value="Email">Email Address</option>
<option value="Keywords">Keywords</option>
</select>
<input type="text" id="myInput">
</form>
<script type="text/javascript">
function myFunction(event){
// Prevent the form from submitting (default functionality)
event.preventDefault();
var myUrl = "http://bccportal01/webapps/agency/epdsearch/Search.aspx?",
selectEl = document.getElementById('mySelect'),
inputEl = document.getElementById('myInput');
// Append the selected value
myUrl += "op=" + selectEl.options[selectEl.selectedIndex].value;
myUrl += "&str=" + inputEl.value;
window.open(myURL);
}
</script>

Get input values of a form hidden in Jquery with PHP

I have a bit of a problem here (or big I actually don't know) I'm new with PHP and I want to know if is possible to get the values of a form input field with PHP that are appended with Jquery is an user choose the right option.
The thing is I'm getting all the values in all the input fields that are previously loaded on the page. All the values are required in order to submit the form, but the thing is that the fields that are appended in the form (with Jquery) when the user chooses and option of a select field aren't being processed by PHP and I can't access their values.
So basically: If the user doesn't select any number (0 by default) the fields don't appear and they are not required to fill in, although, if the user select "1 to 10" in the select input the amount of input fields appear and the NEED to be filled in to submit the form.. how can I achieve that?
Here is the code
This is the PHP code I have before the DOCTYPE in the php form page:
$errores = [];
$faltantes = [];
if (($_SERVER['REQUEST_METHOD'] == 'POST') && (isset($_POST['continue']))) :
$expected = ['nombres', 'apellidos', 'cedula_tipo', 'cedula_no', 'fecha_nacimiento', 'sexo', 'edad', 'civil', 'direccion', 'ciudad', 'pais', 'tel_hab', 'tel_cel', 'email', 'plan', 'pago', 'beneficiarios'];
$requeridos = ['nombres', 'apellidos', 'cedula_tipo', 'cedula_no', 'fecha_nacimiento', 'sexo', 'edad', 'civil', 'direccion', 'ciudad', 'pais', 'tel_hab', 'tel_cel', 'email', 'plan', 'pago', 'beneficiarios'];
require './includes/tdaform_process1test.php';
if (!$errores && !$faltantes) :
endif;
endif;
This is the form field where the user selects and based on his selection the other inputs appear:
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" id="planilla_tda" name="planilla_tda">
<div class="bene-select">
<h4>Puedes agregar beneficiarios a tu plan.</h4>
<label for="beneficiarios">Cantidad de beneficiarios</label>
<select name="beneficiarios" id="beneficiariosCount">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<div id="beneficiarios" class="beneficiarios"></div>
<button type="submit" class="btn-contacto" name="continue" value="submit">enviar planilla</button>
</form>
This is the DIV (that contains the input fields) that is appending when the user makes a selection other than "0":
<div class="beneficiario-wrap">
<label for="nombre_bene">Nombre y Apellido</label>
<input type="text" name="nombre_bene[]" value="">
<label for="cedulabene_no">Cedula beneficiario</label>
<div>
<select name="cedulabene_tipo">
<option value="Venezolano" selected>V </option>
<option value="Extranjero">E </option>
</select> <input type="text" name="cedulabene_no[]" value="" maxlength="8">
</div>
<label for="edad_bene">Edad beneficiario</label>
<input type="text" name="edad_bene[]" value="">
</div>
This is how I'm appending the input fields with Jquery:
const divToAppend = '<div class="beneficiario-wrap"><label for="nombre_bene">Nombre y Apellido</label><input type="text" name="nombre_bene" value=""><label for="nombre_bene">Cedula beneficiario</label><div><select name="cedulabene_tipo"><option value="Venezolano" selected>V </option><option value="Extranjero">E </option></select> <input type="text" name="cedulabene_no" value="" maxlength="8"></div><label for="edad_bene">Edad beneficiario</label><input type="text" name="edad_bene" value=""></div>';
let number = $('#beneficiarios').val();
$('#beneficiariosCount').on('change', function () {
$('#beneficiarios').html('');
number = $(this).val();
for (let i = 0; i < number; i++) {
$('#beneficiarios').append(divToAppend);
}
});
and this is how I'm looping through all the the fields and make them require with PHP:
$suspect = false;
$emailPattern = '/Content-type:|Bcc:|Cc:/i';
function isSuspect ($value, $emailPattern, &$suspect) {
if (is_array($value)) :
foreach ($value as $item) {
isSuspect($item, $emailPattern, $suspect);
}
else :
if (preg_match($emailPattern, $value)) {
$suspect = true;
}
endif;
}
isSuspect($_POST, $emailPattern, $suspect);
if (!$suspect) :
foreach ($_POST as $key => $value) {
$value = is_array($value) ? $value : trim($value);
if (empty($value) && in_array($key, $requeridos)) {
$faltantes[] = $key;
$$key = '';
} elseif (in_array($key, $expected)) {
$$key = $value;
}
}
endif;
As I said I'm really new with PHP and I came out with this approach with self-education. So, Please help!

on changing the select option for second time

i am creating a webpage using html,php and javascript.
i have used script for select option. The problem i am encountering on executing the code is that the first input field doesn't disappear on selecting the option again. instead i get the second input box and first input box as well. i.e. i get both even if i use if else condition.
var fil = document.getElementById("filter");
fil.onchange = function filteron() {
var filtertag = document.getElementById("filter");
var tag = filtertag.options[filtertag.selectedIndex].value;
var searchbox = document.createElement("input");
var filter = document.getElementById("criteriain");
searchbox.setAttribute("id", "criteria");
if (tag === 'ed') {
searchbox.setAttribute("type", "date");
searchbox.setAttribute("name", "searchin");
} else if (tag === 'gw') {
searchbox.setAttribute("type", "number");
searchbox.setAttribute("name", "searchin");
}
filter.appendChild(searchbox);
};
<form action="" method="post">
<label for="filter" id="filterin">Filter by</label>
<select id="filter" size="1" name="filter" onchange="filteron()">
<option value='slno' >Sl No</option>
<option value='ed' >Entry Date</option>
<option value='lot' >Lot No</option>
<option value='par' >Party</option>
<option value='var' >Variety</option>
<option value='cst' >Current status</option>
<option value='gw' >Gray width</option>
</select>
<br/>
<label for='criteria' id='criteriain'>Search for</label>
It is because irrespective of your selection you are creating a new element every time and only changing the type in if/else block for new element.
var fil = document.getElementById("filter");
fil.onchange = function filteron() {
var filtertag = document.getElementById("filter");
var tag = filtertag.options[filtertag.selectedIndex].value;
var searchbox = document.getElementById("criteria");
var filter = document.getElementById("criteriain");
if(undefined === searchbox || null === searchbox) {
searchbox = document.createElement("input");
searchbox.setAttribute("id", "criteria");
}
if (tag === 'ed') {
searchbox.setAttribute("type", "date");
searchbox.setAttribute("name", "searchin");
} else if (tag === 'gw') {
searchbox.setAttribute("type", "number");
searchbox.setAttribute("name", "searchin");
}
filter.appendChild(searchbox);
};
<form action="" method="post">
<label for="filter" id="filterin">Filter by</label>
<select id="filter" size="1" name="filter" onchange="filteron()">
<option value='slno' >Sl No</option>
<option value='ed' >Entry Date</option>
<option value='lot' >Lot No</option>
<option value='par' >Party</option>
<option value='var' >Variety</option>
<option value='cst' >Current status</option>
<option value='gw' >Gray width</option>
</select>
<br/>
<label for='criteria' id='criteriain'>Search for</label>

Categories