How to insert javascript array data into a database? - javascript

I'm trying to make an ecommerce site. So what I'm trying to do here is that I have two select tag, the value of the second tag should automatically be listed after selecting a particular data on the first select tag. Meaning suppose, the first tag is for 'Department' whereas the second tag is for categories. So if I select 'Electronics' in the first tag only(not all) categories which are inside Electronics(eg. laptop, smartphone, etc) should appear automatically, same case for cloth which should appear only(top wear, bottom wear, etc). And what I did is that I made the department in a select tag whereas I stored the categories in a javascript array. The following is the code for html...
<select class="products" id="department_select" name="department" onchange="categoryChange(this);">
<option value="empty">Select</option>
<option value="Electronics">Electronics</option>
<option value="Men's clothes">Men's clothes</option>
<option vlaue="Women's clothes">Women's clothes</option>
<option vlaue="Home & Kitchen">Home & Kitchen</option>
<option vlaue="Sports & Fitness">Sports & Fitness</option>
</select><br>
Below is the code where I stored the categories in javascript array..
<script>
// array of possible countries in the same order as they appear in the country selection list
var categoryLists = new Array(5)
categoryLists["empty"] = ["Select"];
categoryLists["Electronics"] = ["Select","Camera", "Desktop", "Laptop", "Mobile", "Smart watch"];
categoryLists["Men's clothes"] = ["Select","Foot wear", "Bottom wear", "Top wear", "Summer clothes", "Winter clothes"];
categoryLists["Women's clothes"] = ["Select","Clothing", "Foot wear", "Saree", "Top wear", "Bottom wear"];
categoryLists["Home & Kitchen"] = ["Select","Living Room Furniture", "Bedroom Furniture", "Office & Study", "Kitchen needs"];
categoryLists["Sports & Fitness"] = ["Select","Cricket", "Football", "Gym Accessories"];
/* CountryChange() is called from the onchange event of a select element.
* param selectObj - the select object which fired the on change event.
*/
function categoryChange(selectObj){
// get the index of the selected option
var idx = selectObj.selectedIndex;
// get the value of the selected option
var which = selectObj.options[idx].value;
// use the selected option value to retrieve the list of items from the countryLists array
cList = categoryLists[which];
// get the country select element via its known id
var cSelect = document.getElementById("category_select");
// remove the current options from the country select
var len = cSelect.options.length;
while(cSelect.options.length > 0){
cSelect.remove(0);
}
var newOption;
// create new options
for(var i=0; i<cList.length; i++){
newOption = document.createElement("option");
newOption.value = cList[i];// assumes option string and value are the same
newOption.text = cList[i];
// add the new option
try{
cSelect.add(newOption);
}
catch(e){
cSelect.appendChild(newOption);
}
}
}
So normally when i stored data from php i used the $categories = $_POST['categories'] and all. But the problem here is that I can't seem to find a way to store the javascript array data into the database. Especially since i'm storing one select tag using php and the second select tag using javascript.
So, guys if you could please help me out here. THANK YOU SO MUCHH...

To store an array into a database, you need to convert it to a string first.
//Convert to string
$categories = json_encode($categories);
//You now use $categories in your mysql queries

Related

select drop down option based on associated text

I have a drop down with a value and associated text as such:
echo '<option value="'.$row['company_id'].'">'.$row['company_name'].'</option>';
Eventually, the output of the selected option is put into a table, row by row. By each row, there is an edit button to edit that particular row and select a new drop down option. I'm trying to use JavaScript to select the text and when they hit the edit button, the option that is currently set will be the default choice.
So for instance, if the row says the company_name is: ABC Company, when they hit the edit button, the drop down will populate with that option. Since the value and text are different, I need to choose the drop down option based on text. I have tried these 2 options so far with no luck.
To get the row text:
var d = document.getElementById("itable").rows[id].cells[3].innerText;
I have tried the following to pass back the text of the row, and to select the drop down by text.
document.querySelector('#editinsurancepolicymodal select[name=editicompanydropdown]').value = d;
This option just populates the drop down, but no choice is selected.
document.querySelector('#editinsurancepolicymodal').find('option[text="InsuranceB"]').val;
This option selects the first option in the drop down, but doesn't change based on what the 'text' is.
Thank you for your help in advance.
One way will be to iterate over the option elements, selecting the one that has the same text as the text from the row, and un-selecting all the others. This is illustrated in the snippet below (I have inserted a 3 second timeout, so that you can see that the initially selected option (Two) is changed to the option with the text "Three" from the JavaScript code.
window.setTimeout(function () {
var sampleWord = "Three";
var options = document.querySelectorAll("option");
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.innerText === sampleWord) {
option.selected = true;
} else {
option.selected = false;
}
}
}, 3000);
<select id="selector">
<option id="option-1" value="1">One</option>
<option id="option-2" value="2" selected>Two</option>
<option id="option-3" value="3">Three</option>
<option id="option-4" value="4">Four</option>
</select>
Alternately, you could store the id for the company as a data-attr attribute on the row. For example (in PHP):
echo "<td data-attr-company-id=".$row['company_id'].">".$row['company_name']."</td>"
Then, you can read the attribute from the table row, and query for the option that has the same value as your attribute value.
var options = document.querySelectorAll("option");
This will select all options from the page. If you want to get the options for a specific drop down, use the following:
var options = document.querySelector('#specificform select[name=specific_drop_down_in_the_specific_form]');
To select the option based on the text and not the value, use this loop:
for (var i=0; i<options.length; i++){
var option = options[i];
if (option.innerText === d){
option.selected = true;
}
}

How to target a select option based on data attribute?

I'm new to JavaScript and jQuery. I'm trying to create something for a website I'm working on, but I can't figure this out.
How can I get jquery to show or hide a select option of a dropdown, based on the selected data attribute of another dropdown?
IE, selecting option 2 in the first dropdown will show only options 1 and 3 in the second menu, and vice versa?
$(document).ready(function() {
$("#make_id").change(function() {
/* basically if data-make is = to selected data-id option, show option,
if it isn't, hide this option. seems, simple, but I can't figure it out... */
})
})
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 1</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>
$("#make-id").change(function(e){
var currentMake = $("#make-id").data("id");
$("#model-id option").not("[data-make='"+currentMake+"']").hide();
$("#model-id option").filter("[data-make='"+currentMake+"']").show();
}
In English:
Whenever make-id changes, get the data-id field from it.
Select all the options under model-id then filter for ones that don't have the same data-make value. Hide those.
Select all the options under model-id then filter for the ones that do have the same data-make value. Show those.
TL;DR
I've changed the way your code works a little to make it work better for the way you want it to. Take a look at this fiddle.
So first of all, you can easily define a callback on the change event which can filter the second select box's option visibility. One problem you may come into if you do this is that "hidden" options will still be in the select's value if they were previously selected (as in Franz's answer).
Here's a slightly different approach in which everything is emptied and loaded dynamically from a JSON object that you define initially:
1. Define your JSON object (data model)
This could come from a database as well of course.
var makesAndModels = {
"makes": [
{"option_id": 1, "id": 18, "name": "make 1"},
{"option_id": 2, "id": 42, "name": "make 2"}
],
"models": [
{"option_id": 1, "make_id": 42, "name": "make 2: model 1"},
{"option_id": 2, "make_id": 18, "name": "make 1: model 1"},
{"option_id": 3, "make_id": 42, "name": "make 2: model 2"}
]
};
2. Define methods to populate each select
Your rules are simple:
To populate the makes, you need no conditions
To populate the models, you need a make ID (foreign key)
function populateMakes() {
var $make = $('#make_id');
// Remove all options before starting
$make.empty();
// Loop the makes from the JSON data object
$.each(makesAndModels.makes, function(key, make) {
// Append new options for each make
$('#make_id')
.append(
$('<option></option>')
.data('id', make.id) // Assign the data-id attribute
.attr('value', 'make option ' + make.option_id) // Give it a value
.text(make.name) // Give it a label
);
});
}
The function above is simply emptying the #make_id select box, then looping the makes in the JSON data object and appending a new option element to the makes select for each result, setting the attributes as it goes.
Then to populate the models, we do the same thing for models as we did for makes, except we'll ignore any models that are for a different make.
function populateModels(makeId) {
// Assign the selector to a variable to repeated use/Don't Repeat Yourself
var $model = $('#model_id');
// Remove all models in the select to start
$model.empty();
// Loop the models in the JSON object
$.each(makesAndModels.models, function(key, model) {
// Ignore any models for other makes
if (model.make_id != makeId) {
return;
}
// Append the new model to the select
$model
.append(
$('<option></option>')
.data('make', model.make_id) // Assign its data-make attribute
.attr('value', 'model option ' + model.option_id) // Give it a value
.text(model.name) // Give it a label
);
});
}
3. Simplified HTML
Once you've got that framework, your HTML and event handlers are going to be very simple.
The HTML select boxes don't need any options since they're populated dynamically, although you may want to leave the ones you have there already in place to help with older browsers or browsers with Javascript turned off (cringe):
<!-- These are populated dynamically now! -->
<select id="make_id"></select>
<select id="model_id"></select>
4. Create your jQuery event handler
...and glue it all together:
$(document).ready(function() {
// Populate the makes select box
populateMakes();
// Define what should happen when you change the make_id select
$("#make_id").change(function() {
// Find the currently selected make's ID from data-id
var selectedMake = $(this).find('option:selected').data('id');
populateModels(selectedMake);
});
// Trigger a change to populate the models the first time
$('#make_id').change();
});
The trick above is that once you've populated the makes and defined your event handler for when the makes select box changes, you can to trigger the change event manually - this will cause populateModels() to be called with the first make in the list, and have the models for that make populated too.
$(document).ready(function() {
$("#make_id").change(function() {
if ($(this).val()=='make option 2') $("#model_id").find("option").eq(1).hide();
else $("#model_id").find("option").eq(1).show();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 2</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>

html select list - get text value by passing in a variable?

I have a select list that displays a list languages.
<select name="language_code" id="id_language_code">
<option value="ar">Arabic - العربية</option>
<option value="bg">Bulgarian - Български</option>
<option value="zh-CN">Chinese (Simplified) - 中文 (简体)‎</option>
<option value="en" selected="selected">English (US)</option>
<option value="fr-CA">French (Canada) - français (Canada)‎</option>
</select>
I am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:
$('#id_language_code option:selected').text()
How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?
This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".
I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!
Here is an example of how you can use CSS selectors to query the value attribute:
function getOptionTextByValue(value) {
return $('#id_language_code option[value=' + value + ']').text();
}
var bgText = getOptionTextByValue('bg');
Here is a working example
http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview
You have some data, and you have the view of this data (html/dom), but it's best if you go data -> view, rather than view -> data.
For example, say you have this array:
var languages = [
{short: "ar", text: "Arabic - العربية"},
{short: "bg", text: "Bulgarian - Български"},
{short: "en", value: "English (US)"}
];
Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"
languages.filter(function(x){ return x.short === 'bg' })[0].text;
Or create DOM nodes from it:
function option(x){
var el = document.createElement('option');
el.value = x.short; el.textContent = el.text;
return el;
}
function select(options){
var el = document.createElement('select');
options.forEach(function(x){ el.appendChild(x); });
return el;
}
var element = select(languages.map(option));
element.id = 'id_language_code';
Hmm, if I understand correctly, you want to retrieve the label associated with a given value of one of the options of the <select> element, which will not necessarily be the currently selected option. Using pure JavaScript approach (aka. No jQuery, since there's already a nice one provided by someone else):
function getOptionLabel(selectId, optionValue){
// Get select element and all options
var sel = document.getElementById(selectId);
var selOpts = sel.options;
// Cycle through each option to compare its value to the desired one
for(var i = 0; i < selOpts.length; i++){
if (selOpts[i].value == optionValue){
return selOpts[i].label;
}
}
// Default return value
return "Option not found.";
}
To get the Bulgarian option from a <select> of the given id, you could call it like so:
getSelectLabel("id_language_code", "bg");
Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

JavaScript to choose droplist value not working in ASP .NET MVC4 with HTMLHelper and "All"

I'm using JavaScript to get the selected value of a drop list in MVC 4 but have an issue I think is caused by the HTMLHelper.
CONTROLLER - to populate droplist
private string PopulateStandard(object selectedValue = null)
{
var query = db.Database
.SqlQuery<StandardModel>(
"SELECT * FROM [DBO].[GetStandards] ('" +
User.Identity.Name + "', '" + DateTime.UtcNow + "')")
.ToList();
ViewBag.Standard = new SelectList(query, "Standard", "Standard", selectedValue);
try { return query[0].Standard; }
catch { return ""; }
}
VIEW
The view has this section for the drop list. Please note the inclusion of "All". I think this is the problem. That puts a first row atop the drop list saying "All" with a null value. I want that. So far so good (so what)
#Html.DisplayNameFor(m => m.Standard)
#Html.DropDownList("Standard", "All")
JAVASCRIPT
It's a long story, but I have other code that requires me to get the value of the drop list using JavaScript, so I'm doing it like this:
var e = document.getElementById("Standard");
var sStandard = e.options[e.selectedIndex].value;
PROBLEM
If no value was chosen, then I should get the first row, which would be "All" for text or "" for value. Instead, I'm getting the second row, which is the first one with data as populated from the database.
Is the HTML helper causing me to not get the first row? Or is my JavaScript off?
EDIT - to show ViewSource on drop list
These are the first few lines of the rendered list
<select id="Standard" name="Standard"><option value="">All</option>
<option value="2S">2S</option>
<option value="Aero">Aero</option>
#Html.DropDownList("Standard", "All")
here "All" is option label. so you do not get this as value.

How to iterate through multiple dropdown lists and access their option values

I'm writing the code for a basic GPA calculator. Basically, it's a 3-column-table, two text areas for the course name/credit hours and a dropdown list that contains letter grades (A+, C, B-) and their corresponding point values as the option value, like this
<td><select name="letterGrades">
<option value="0.7">A+</option>>
<option value="1.3">A-</option>>
<option value="2.7">C+</option>
</option>
</select>
</td>
I need to iterate through the rows, get the option value or "grade" for each course.
var table = document.getElementById(tableID);
for(var i=0; i<rowCount; i++) {
grade = table.rows[i].cells[2].options[letterGrades.selectedIndex].id; //is this allowed?
credits = parseFloat(table.rows[i].cells[1].value);
totalHours += parseFloat(table.rows[i].cells[1].value);
perCourse += grade*credits
}
totalGPA = perCourse/totalHours;
I realize there are other ways to assign the letters to their point values (arrays?) but I still don't know how to iterate through the dropdown lists and get their option values.
Get to the <select> items first. If that's possible, I suggest you use document.getElementsByTagName('select') to get the list of all <select> tags on your page. Then, with each <select> tag, call theSelectTag.getElementsByTagName('option') (where theSelectTag is an object from the returned node list). You can then access their value through the value property (ya rly), and their label through the textContent property.
getElementsByTagName returns a NodeList object, but you can pretty much treat it the same as an Array.
I finally got everything to work thanks to zneak's answer. Here's how.
var select = document.getElementsByTagName('select');
var options = document.getElementsByTagName('option');
var textarea = document.getElementsByTagName('textarea');
for(var i=1; i<rowCount; i++) { //i=1, starts at the second row, assuming you have a header
var grades = select[i].options[select[i].options.selectedIndex].value; //gets the selected item for each select tag from the dropdownlist
credits = parseFloat(textarea[i].value); //same goes for textareas
totalHours += parseFloat(textarea[i].value);
perCourse += grades*credits;
}
totalGPA = perCourse/totalHours;

Categories