I am a beginner in javascript and I am looking at the following piece of code.
var type_select = '<select id="type_select" style="margin-bottom:0px;">';
var i;
var customer_group = <?php echo json_encode($customer_group);?>;
for (i = 0; i < customer_group.length; ++i) {
//console.log(customer_group[i].group_id);
if (customer_group[i].group_name == table_column_1){
type_select = type_select+'<option value='+customer_group[i].group_id+' selected>'+customer_group[i].group_name+'</option>';
}else{
type_select = type_select+'<option value='+customer_group[i].group_id+'>'+customer_group[i].group_name+'</option>';
}
}
type_select = type_select+'</select>';
//not allow to click header
if ( col == 0 ) {
return;
}
Please help to give me some idea of what it might be doing. Maybe some direction. I am not sure if this code is enough,Please try your best to help me and explain to me as much as possible. Your help will be very much appreciated.
It's building a select dropdown box with some options
<select id="type_select" style="margin-bottom:0px;">
<option value="some-value">Some text</option>
<option value="some-other-value">Some other text</option>
<option value="yet-another-value" selected>More text this one is selected on load</option>
</select>
Looking at the snippet of code you posted, it then does absolutely nothing with it
Hope that helps
var type_select = '<select id="type_select" style="margin-bottom:0px;">';
var i;
// this part of code will be interpreted by PHP Engine, on client side you will find an JSON representation of
// "Customer_group", probably gotten from database, or file
var customer_group = <?php echo json_encode($customer_group);?>;
for (i = 0; i < customer_group.length; ++i) {
// here, you are building a HTML string, this will be attached to DOM using
// ex : document.getElementById('YOUR_DOM_ID').innerHTML = type_select;
if (customer_group[i].group_name == table_column_1){
type_select = type_select+'<option value='+customer_group[i].group_id+' selected>'+customer_group[i].group_name+'</option>';
}else{
type_select = type_select+'<option value='+customer_group[i].group_id+'>'+customer_group[i].group_name+'</option>';
}
}
type_select = type_select+'</select>';
//not allow to click header
if ( col == 0 ) {
return;
}
Related
I have an array which store some data. I want to create a option list by using javascript for loops. But I meet a problem, how do I insert the php code into the open tag? For example,
<option value="none">Please select your state</option>
<option value="Johor" <?php if($row['state'] === 'Johor') echo 'selected="selected"';?>>Johor</option>
<option value="Kedah" <?php if($row['state'] === 'Kedah') echo 'selected="selected"';?>>Kedah</option>
As you can see, there is php code included inside open tag. Below is the code that I am using.
function php_dropdown_state(){
let select = document.getElementById("state");
let options = ["Johor", "Kedah"];
for(let i = 0; i < options.length; i++) {
let opt = options[i];
let elements = document.createElement("option");
elements.innerHTML = "<?php if($row['state'] === '" + opt + "') echo 'selected=" + "selected" + "';?>";
elements.textContent = opt;
elements.value = opt;
select.appendChild(elements);
}
}
But this code will give me this result.
<option value="Johor">Johor</option>
<option value="Kedah">Kedah</option>
the best is to transmit it in json, on an MVC architecture its must pass from the controller to the view, if we do this on a single page its must give :
let data = JSON.parse("<?= empty($row) ? "[]" : json_encode($row) ?>");
So I've been working on trying to populate a select tag options with JavaScript. I can't seem to figure out why my function isn't working any help would be greatly appreciated.
My HTML code:
<select name="options" id="options" style="width: 100px;" onchange="chooseOption(this);">
</select>
And my JavaScript function:
function chooseOption(){
var choices = {"Gym","Pool","Sports"};
var myChoice = "";
for(i=0; i<=choices.length; i++){
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
Thanks again
I would go with something like.
Is not really tested but am pretty sure is more reliable.
var option = document.createElement("option");
for(i=0; i<=choices.length; i++){
option.text = choices[i];
option.value = choices[i];
document.getElementById("options").appendChild = myChoice;
}
You're attempting to create an object instead of an array here:
var choices = {"Gym","Pool","Sports"}; // change {} to [] to create an array
Curly braces - {} are used to denote that you are creating an object.
Brackets - [] are used to denote an array.
Try populating your select element as it's being created with something like this:
<select name="options" id="options" style="width: 100px;">
<script>
var choices = ["Gym","Pool","Sports"];
var myChoice = "";
for(var i=0; i < choices.length; i++) {
myChoice += "<option value='"+choices[i]+"'>"+choices[i]+"</option>";
document.getElementById("options").innerHTML = myChoice;
}
</script>
</select>
Firstly, you have a huge error.
You don't use { and } in javascript to create arrays.
Use:
var choices = ["Gym","Pool","Sports"];
Here is your final code:
<script>
function chooseOption() {
var choices = ["Gym", "Pool", "Sports"];
var myChoice = "";
for (i = 0; i <= choices.length; i++) {
myChoice += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
document.getElementById("options").innerHTML = myChoice;
}
}
</script>
<select name="options" id="options" style="width: 100px;" onclick="javascript:chooseOption(this);">
</select>
Update
If you want it to work on JSFiddle firstly you need to make your function globally available because JSFiddle runs it at domready. To make it globally available just write it like this: window.choseOption = function() { /* code here */ };.
You should read a bit on DOM events. The change event on that select won't fire up until you have selected something. And since you have nothing to select the event will not fire.
You can run the function at onclick or just run it when the DOM is ready.
I have updated your fiddle.
I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.
How can i take a value when a user choose an option from a drop down menu(select) and add it with another choice of another drop down menu and output the total of a mark? I want this total to change automatically with on-change method. I have wrote my code in JavaScript using DOM to write the form! Can you help me please?
I would personally recommend doing this with AngularJs. If you are using Angular, simply assigning the DOM element with a model (ng-model) name and you can dynamically change the items inside of your dropdown in your javascript. Check out this very simple example:
http://plnkr.co/edit/?p=preview
and here is documentation on how to use the ng-change utility that comes with AngularJs:
http://docs.angularjs.org/api/ng.directive:ngChange
(edit: I guess I should describe what is happening in the example in more detail. Basically, what is inside of <div ng-controller="Controller"> will be tied to the controller called "Controller" in the script.js. By assigning ng-model="confirmed" to the checkbox, it ties a variable of the same name to the checkbox. As you can see a couple lines down, simply calling {{confirmed}} can call the value from html. Also, assigning ng-change="change()" to the element basically tells the controller to call the function, change(), whenever there is changes made to the element in question. Hope this helps)
This is using regular javascript.
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
And just add this to your select objects.
<Select id = "ObjectsIDValue1" onchange="Total();">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<!-- more option objects -->
</Select>
<Select id = "ObjectsIDValue2" onchange="Total();">
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<!-- more option objects -->
</Select>
Note: This doesn't validate whats in your select is a number.
Edit: As you appear to be new here on Stack Overflow I'd like to mention that if you found this solved your problem please mark it as the accepted answer by giving it a check mark. Also if you found this helpful and have enough points to up-vote please do that too.
Hope this helps.
Edit2: From the OP's comment I think you're looking for this,
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
just add that after you define Total();
Edit3: I want to be forthcoming and explain that what you're looking to do is VERY ugly in regular Javascript to do. I would recommend a JS library such as JQuery where doing this is much cleaner and easier to code.
Anyway here is ALL the code needed to do this.
<script type = "text/javascript">
//Create Selects from an Array
function CreateSelectFromArray (SelectID, ArrayOfValues)
{
var Code="";
Code += "<Select id='"+SelectID+"'>";
for(var x = 0; x < ArrayOfValues.length; x++)
{
Code += "<option>";
Code += ArrayOfValues[x];
Code += "</option>";
}
Code += "</Select>";
return Code;
};
//Repopulate a select from a start and end value
function ChangeSelectFromValues (SelectID, StartValue,EndValue)
{
var Code="";
var SelectObject = document.getElementById(SelectID);
for(var x = StartValue; x <= EndValue; x++)
{
Code += "<option>";
Code += x;
Code += "</option>";
}
SelectObject.innerHTML = Code;
};
//Add up the values of 2 Selects (currently hardcoded)
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
var yourArray = [5,10,15];
var SelectCode="";
SelectCode += CreateSelectFromArray ('FirstSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('SecondSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('ObjectsIDValue1', [1,2,3,4,5]);//create select with default array
SelectCode += CreateSelectFromArray ('ObjectsIDValue2', [1,2,3,4,5]);//create select with default array
SelectCode += "<input id='TotalsIDValue'/>";
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
//Add events to the Selects for desired functionality
document.getElementById("FirstSelect").onchange = function(){
var e0 = document.getElementById("FirstSelect");
ChangeSelectFromValues('ObjectsIDValue1',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("SecondSelect").onchange = function(){
var e0 = document.getElementById("SecondSelect");
ChangeSelectFromValues('ObjectsIDValue2',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
</script>
That's about as clean as you can get this in regular JavaScript
Note:
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
Can be replace with,
document.getElementById("PlaceYouWantTheSelects").innerHTML =SelectCode;
If you have a specific place in mind to put the selects.
I have a piece of software that I am working on that allows you to select locations and this shows on a map. I want to add functionality to select all the locations with a button and show the information on the map.
I'm new to coding and therefore haven't really written any code. I have been searching the web but to no avail which is why I came to ask you lovely people on here.
Any advice or links you provide will be greatly appreciated.
function checkAddAllName(mode){
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].text;
var Name = document.getElementById('select_'+mode+'_ID').options[document.getElementById('select_'+mode+'_ID').selectedIndex].value;
var errorCount = 0;
var Name = 0;
var allStations = document.getElementsByTagName('input');
for (var i=0; i<allNames.length; i++){
if (allNames[i].id.substring(0,10) == 'StationNo_'){
var splitID = allNames[i].id.split("_");
if (splitID[1] == mode){
if (allNames[i].value == addedNameNo){
errorCount = 1;
}
}
}
}
if (errorCount == 0){
addNAme(mode);
} else {
alert(addedName+' has already been added!');
}
}
You are better off doing this using a library like jQuery. It'll take you some time in the beginning to learn, but it'll pay off for the rest of your web programming days.
Assuming your locations are an unordered list of checkboxes like:
<ul id='listId'>
<li><input type="checkbox value="London">London</li>
<li><input type="checkbox value="Paris">Paris</li>
<li><input type="checkbox value="Buenos Aires">Buenos Aires</li>
</ul>
<button id="selectAll">Select all</button>
In jQuery you'd do something like:
$('button#selectAll').on("click",function(){
$('ul#listId > li > input').prop('checked',true);
});
Assuming you mean ordinary single selection drop down like this:
<select id="ddlSelectCountry" onchange="SelectCountry(this);">
<option value="">Please select..</option>
<option value="USA">USA</option>
<option value="France">France</option>
<option value="Spain">Spain</option>
</select>
You can have such button to auto select all non empty items:
<button type="button" onclick="SelectAll('ddlSelectCountry');">Select All</button>
And the JavaScript for that would be:
function SelectAll(strDropDownId) {
var oDDL = document.getElementById(strDropDownId);
if (!oDDL) {
alert("No such element: " + strDropDownId);
return;
}
for (var i = 0; i < oDDL.options.length; i++) {
if (oDDL.options[i].value.length > 0) {
oDDL.selectedIndex = i;
if (oDDL.change)
oDDL.change();
else if (oDDL.onchange)
oDDL.onchange();
}
}
}
Using jQuery the code can be greatly reduced in length and made more elegant, but that's your choice.
Live test case.