HTML code not loading the data in list box - javascript

I am creating two combo boxes the first one gets loaded initially and up on selecting the text in the combo the second combo box should get filtered. The issue is combo box is not getting loaded.
<html> <head>
<title> text conversion </title> <script type="text/javascript">
function PrepopulateProductName() { alert("Hello! I am an alert box!!");
var selectHTML = "";
var DEV = ["GTXD", "SFGD", "ITXD", "ETXD","CTXD"];
var SYS = ["GTXS", "ITXS", "ETXS", "CTXS"];
var ACC = ["GTXA", "ITXA", "ETXA", "CTXA", "SFGA"];
alert("Hello! I am an alert box!!");
if (document.getElementById("selProductName").value == "DEV") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < DEV.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + DEV[i] + "'>" + DEV[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
PrepopulateProductName();
</script> </head> <body>
Product Name: <select id="selProductName" name="selProductName"
onchange="changeProductName(this.value);"> <option>--Choose Product
Name--</option> </select>
</body> </html>

There were few issues in your code:
You didn't define the category select box
Called an undefined function changeProductName()
This is what you can do:
With the onchange attribute, call the PrepopulateProductName() function. Then, it will check for the selected option and populate the category select box with the values defined.
Example:
function PrepopulateProductName() {
//alert("Hello! I am an alert box!!");
var selectHTML = "";
var DEV = ["GTXD", "SFGD", "ITXD", "ETXD","CTXD"];
var SYS = ["GTXS", "ITXS", "ETXS", "CTXS"];
var ACC = ["GTXA", "ITXA", "ETXA", "CTXA", "SFGA"];
//alert("Hello! I am an alert box!!");
if (document.getElementById("selProductName").value == "DEV") {
var select = document.getElementById('category').options.length;
for (var i = 0; i < select; i++) {
document.getElementById('category').options.remove(i);
}
for (var i = 0; i < DEV.length; i++) {
var newSelect = document.createElement('option');
selectHTML = "<option value='" + DEV[i] + "'>" + DEV[i] + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('category').add(newSelect);
}
}
}
<html> <head>
<title> text conversion </title>
</head>
<body>
Product Name: <select id="selProductName" name="selProductName"
onchange="PrepopulateProductName();"> <option>--Choose Product
Name--</option> <option value="DEV">DEV</option> </select>
<select id="category" name="category"> </select>
</body> </html>

Related

fill a select with javascript subtracting a value from the select before

I have a form with two inputs where the user has to select a number from two different sets. The first one is from 1 to 100. The second one is from 1 to 500, but I need to show only the remaining values above the number selected in the first input. Let's say I have a script like this:
<?php
echo "<form action='process.php' method='post'>";
echo "<select id='first_set' name='first_set'>";
echo "<option value='' disabled selected hidden>select how many</option>";
for ($i = 1; $i <= 100; $i ++) {
echo "<option value='" . $i . "'>" . $i . "</option>";
}
echo "</select>";
echo "<select id='second_set' name='second_set'>";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var numFirstSet = $(this).val();
if(numFirstSet){
var topSecondSet = 500;
var numRemaining = topSecondSet - numFirstSet;
for (var a = numRemaining; a < topSecondSet; a ++) {
var numToDisplay = a;
$('#second_set').html('<option value="numToDisplay">numToDisplay</option>');
}
}else{
$('#second_set').html('<option value="">Select first a value from the set before!</option>');
}
});
});
</script>
<?php
// the submit button
echo "</form>";
?>
But it doesn't work. The second_set select sadly displays the word "numToDisplay", not the calculated value (var numToDisplay) nor the text "Select first a value from the set before!".
Edit: after some suggestions, I've tried with
$('#second_set').html('<option value="' + numToDisplay + '">' + numToDisplay + '</option>');
but got a strange result: after a select done in first_set, the numToDisplay value is shown but it's always 499. That is topSecondSet - 1 ! And no set of values.
I've tried to figure out a solution and wrote this code:
<script type="text/javascript">
$(document).ready(function(){
$('#first_set').on('change',function(){
var sel_box = document.getElementById("second_set");
var numFirstSet = $(this).val();
sel_box.selectedIndex = 0;
if(numFirstSet){
var topSecondSet = 100;
var startNum = numFirstSet + 1;
for (var a = startNum; a <= topSecondSet; a ++) {
var numToDisplay = a;
var option = document.createElement("option");
option.text = numToDisplay;
sel_box.add(option);
}
}else{
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
}
});
});
</script>
Now second_set is populated after the change in first_set , but got two problems:
1) the items in second_set start from numFirstSet*10 instead of numFirstSet+1;
2) each time a change is made in first_set selection, a new set of options is added instead of substitute the previous set, despite the row
sel_box.selectedIndex = 0;
that has the goal of resetting the options before adding the new ones.
3) the code
var selectfirstText = "Select first a value from the set before!";
sel_box.html = '<option value="">' + selectfirstText + '</option>';
gives no output, it simply does not work.
Any idea to solve the three problems as above?
Here is a solution that appends a child not using Jquery. Look at Emiel Zuurbiers comments as well. I would also be careful using if(numFirstSet) becuase if the value is 0 it will evaluate as false. I think your intended result should have a check after document.ready and not in the onchange function. That way your "Select first value" option is there at runtime.
let firstSet = document.getElementById("first_set");
$(document).ready(function() {
if (firstSet.value === "null") {
$("#second_set").html(
'<option value="">Select first a value from the set before!</option>'
);
}
$("#first_set").on("change", function() {
var numFirstSet = parseInt($(this).val());
// console.log(numFirstSet);
$("#second_set").html("");
var topSecondSet = 50;
var numRemaining = topSecondSet - numFirstSet;
for (var a = numRemaining; a < topSecondSet; a++) {
let opt = document.createElement("option");
opt.innerHTML = a;
opt.value = a;
document.getElementById("second_set").append(opt);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="first_set">
<option selected disabled value="null">Nothing</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>
</select>
<br /><br />
<select id="second_set"> </select>

Conditional Fields on HTML form

I hope you can help me on this one.
This code below is supposed to show a number of field if people select more than 0 and up to 3.
But nothing is happening when selecting 1 2 or 3. Could you have a look and let me know how can i fix?
Thanks
<select name="children" id="childOccupants">
<option value="0" selected>0</option>
<?php
for ($j = 1; $j <= 3; $j++) {
echo "<option value='$j'>$j</option>";
}
?>
</select>
<!-- Dynamic children boxes -->
<span id='childAges'>
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
$("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />").appendTo("#childAges");
s++;
}
})
</script>
</span>
<!-- End of dynamic child age boxes -->
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
("#childAges").append("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />");
s++;
}
})
</script>
Have you included javascript and checked the console logs?
The below is working fine for me.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select name="children" id="childOccupants">
<option value="0" selected>0</option>
<?php
for ($j = 1; $j <= 3; $j++) {
echo "<option value='$j'>$j</option>";
}
?>
</select>
<!-- Dynamic children boxes -->
<span id='childAges'>
<script>
$("#childOccupants").bind('change', function () {
$("#childAges").empty();
var children = $("#childOccupants").val();
var s = 1;
for (i=0; i < children; i++) {
$("<label for='child" + s + "'>Child " + s + " age</label><input type='text' name='child" + s + "' id='child" + s + "' />").appendTo("#childAges");
s++;
}
})
</script>
</span>
</body>
</html>

jQuery .val() doesnt return the value of an option tag

I have some JavaScript-generated html code. The JavaScript generates the elements (option) in a drop down list (select). I then want to get the value of the selected option '1', however instead 'test' is returned.
The html is generated using:
var newSelect = document.createElement('option');
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
I have then tried the following methods to get the value of the selected option:
var siteId = $('#siteID').val(); // returns 'test'
var siteId2 = $('#siteID').data("value"); // returns undefined
var siteId3 = $('#siteID').attr("value"); // returns undefined
var siteId4 = $('#siteID').prop("value"); // returns 'test'
You are using a very strange way to create your option - you create an option and then insert an option string as innerHTML
Fixed code (see example later)
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
Also you do not actually select the option, so the value will be whatever the browser thinks is selected
Why not use jQuery?
$("<option />", { value: 1, text: "test" }).appendTo('#siteID1')
$('#siteID1').prop("selectedIndex", 1); // NOW the value is 1
console.log(
$('#siteID1').val()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID1">
<option value="">Please select</option>
</select>
Your code:
var test ="Test";
var newSelect = document.createElement('option'),
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
newSelect.innerHTML = selectHTML;
document.getElementById('siteID').add(newSelect);
console.log(document.getElementById('siteID').outerHTML)
<select id="siteID">
</select>
Your FIXED code
var opt = document.createElement('option');
opt.value=1;
opt.text="test"
document.getElementById('siteID').appendChild(opt);
console.log(document.getElementById('siteID').value, $('#siteID').val())
console.log(document.getElementById('siteID').outerHTML)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID">
</select>
You created the option newSelect then you try to insert an option inside of it with innerHTML which is where you went wrong.
This is what you should have done.
var newSelect = document.createElement('option');
newSelect.innerHTML = 'test';
newSelect.value= '1';
document.getElementById('siteID').add(newSelect);
You need remove //selectHTML = "<option value=" + 1 + ">" + test + "</option>";
And change to newSelect.value = 1; for add value to option by javascript
newSelect.innerHTML = test;
newSelect.value = 1;
var newSelect = document.createElement('option');
var test = 'test';
//selectHTML = "<option value=" + 1 + ">" + test + "</option>";
newSelect.innerHTML = test;
newSelect.value = 1;
document.getElementById('siteID').appendChild(newSelect);
$(document).ready(function(){
var siteId = $('#siteID').val(); // r
console.log(siteId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='siteID'>
</select>
Please try this
var test = 'test';
selectHTML = "<option value=\"" + 1 + "\">" + test + "</option>";
$("#siteID").append(selectHTML);
var siteId = $('#siteID').val();
console.log(siteId);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="siteID"></select>
You can first create the Select tag and after that try to append the option tag. I have attached the code as below:
// create the select tag and append with the main div tag
var string = '<select id="dropdown_tag"></select>';
$("#test").append(string);
// create as many option you want and append with the select tag
var newSelect = document.createElement('option');
selectHTML = "<option>---select---</option>";
selectHTML += "<option value='1'>1</option>";
selectHTML += "<option value='2'>2</option>";
$("#dropdown_tag").append(selectHTML);
// Onchange event of dropdown tag
$(document).on('change',"#dropdown_tag", function()
{
alert($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Dropdowm:<div id='test'></div>

Javascript: Javascript ignores the elements generated by itself

I have this javascript function that generates new selects with IDs:
function generateChild(root, categories){
++counter;
var appendid = "id='selectCategory_".concat(counter);
var coma = "'";
var mayorque = "'>";
var appendcoma = appendid.concat(coma);
var select ="<div class='selectContainer'".concat(appendcoma);
var close = "><select ";
var cerrar = select.concat(close);
var appendidselect = cerrar.concat(appendid);
var html = appendidselect.concat(mayorque);
for (var i = 0; i < categories.length; i++) {
html += "<option value='" + categories[i] + "'>" + categories[i] + "</option>";
}
html += '</select></div>';
// ---------------------------
// ---------------------------
// create an element from the html string
// ---------------------------
var tplt = root.createElement('template');
tplt.innerHTML = html;
var el = tplt.content.firstChild;
// ---------------------------
// ---------------------------
// attach the change handler
// ---------------------------
el.firstChild.addEventListener("change", handle_onChange);
// ---------------------------
return el;
}
}
And then this function to search for the last dropdown that didn't have a blank space on it, and save it in a hidden input for later use:
if(this.value == ' '){
for (var i = counter - 1 ; i >= 0 ; --i){
var string = i.toString();
var selectid = "selectCategory_".concat(string);
if(document.getElementById(selectid)){
document.getElementById("category").value = document.getElementById(selectid).value;
break;
}
}
}
else{
var lastselectedvalue = this.value;
document.getElementById("category").value = this.value;
}
This works well with the first dropdown, which is already in the code:
<input type ="hidden" name="category" id = "category" value="">
<div id="category0" class="selectContainer">
<select id="selectCategory_0">
<option>something</option>
<option>something else</option>
</select>
</div>
But never works with the other dropdowns, it always returns undefined.

Create a new dropdown with javascript

I am trying to create a dropdown after I choose an option in an original dropdown.
This is the HTML code:
<br>
<select id ="select-container" onchange="addSelect('select-container');">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<br>
This is the javascript.
function categorygenerate() {
//for testing purposes
var categoryarray = new Array(),
i;
for (i = 0; i < 3; i++) {
categoryarray[i] = Math.random();
}
return categoryarray;
}
function addSelect(divname) {
var newDiv = document.createElement('div');
var html = '<select>',
dates = categorygenerate(),
i;
for (i = 0; i < dates.length; i++) {
html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
console.log($("#" + divname).html());
console.log(newDiv);
}
The debugger mode shows me no error.
It is because you are trying to append your code in the "original select": look at the id of your select.
You have to add a div tag with the id="select-container" and remove it from the "original select"
Here is a working snippet:
function categorygenerate() {
//for testing purposes
var categoryarray = new Array(),
i;
for (i = 0; i < 3; i++) {
categoryarray[i] = Math.random();
}
return categoryarray;
}
function addSelect(divname) {
var newDiv = document.createElement('div');
var html = '<select>',
dates = categorygenerate(),
i;
for (i = 0; i < dates.length; i++) {
html += "<option value='" + dates[i] + "'>" + dates[i] + "</option>";
}
html += '</select>';
newDiv.innerHTML = html;
document.getElementById(divname).appendChild(newDiv);
console.log($("#" + divname).html());
console.log(newDiv);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br>
<select onchange="addSelect('select-container');">
<option>test1</option>
<option>test2</option>
<option>test3</option>
</select>
<br>
<div id="select-container"></div>
Put your select in a div with the id select-container. Ofcourse, give your select an other ID. Then your code should work. It's because you try to append a new select to the original one in your HTML.
https://jsfiddle.net/b248a4k1/

Categories