Remove specific value in Javascript Array dynamically - javascript

I want to remove a specific value from an array.
For example:
var categories = ["Lenovo","Large","100"];
I displayed it like this
HTML CODE:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
How can I achieve this?
I tried it so many times but I failed because I cant get the value. You can check my code:
jQuery("#filter").val()
jQuery(function() {
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories = [];
if (brand) {
categories.push(brand);
}
if (screen_size) {
categories.push(screen_size);
}
if (cpu) {
categories.push(cpu);
}
if (memory) {
categories.push(memory);
}
if (price) {
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
var categories3 = "";
for (var i = 0; i < length; i++) {
var cat_id = "cat" + i;
categories3 += "<div class='filter_style'>" + categories[i] + "<a href='" + cat_id + "' id='" + cat_id + "' onclick='removeCat(event)'><span style='margin-left:15px;color:gray;' >x</span></a></div>";
jQuery("#filter").html(categories3);
}   
});
});
function removeCat(evt) {
evt.preventDefault();
var catid = jQuery(this).attr('href');
var cat = jQuery(this).data("id");
//jQuery.grep(); maybe or indexOf first then slice() but I do not get the value
alert(catid);
}

You can simply remove element from array using below method
categories .splice( $.inArray(removeItem, categories), 1 );//removeItem is name of item which you want to remove from array

If you want to remove, for example, "Lenovo" from:
var categories = ["Lenovo","Large","100"];
do:
categories.splice(0)

Related

Having trouble with Javascript ordering form not calculating

So I'm getting a null error with my order form when I'm trying to calculate the total using javascript. I believe I have everything done. I get an error on line 13 below that starts with .innerHTML
<script type="text/javascript">
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var price = document.getElementById(strains[i] + priceStr).value;
var quantity = document.getElementById(strains[i] + quantityStr).value;
document.getElementById(strains[i] + subtotalStr)
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
document.getElementById("finaltotal").innerHTML = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
</script>
Here is the HTML that is associated just one example they are all the same with unique id and names.
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<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>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Full Example:
https://jsfiddle.net/dg260zxf/
Also if I could just make this work without the subtotal since I don't think it's necessary that would be awesome.
the problem is the array contains many Divs than not in HTML,
the first item 'guptakush_' only exist in html
so if you check if div exists before settings value it will resolve the problem
+
the finaltotal is input not html so put new value with .value not .inerHTML
Working demo:
function doTotals() {
var strains = ['guptakush_', 'headbandguptakush_', 'purplejuicyfruitguptakush_', 'hibiscussunrise_', 'criticalkushguptakush_', 'columbiagoldguptakush_', 'grapeapeguptakush_', 'krishnakush_', 'durbinpoisonguptakush_', 'purpleeurkleguptakush_', 'columbiagoldafgani_', 'kandykushguptakush_', 'hibiscussunriseafgani_', 'afgani_', 'grapeapeafgani_', 'krishnaafgani_', 'hashplantafgani_', 'durbinpoisonafgani_'];
var priceStr = 'price';
var quantityStr = 'quantity';
var subtotalStr = 'subtotal';
var total = 0.00;
for (var i = 0; i < strains.length; i++) {
var priceInput = document.getElementById(strains[i] + priceStr);
var quantityInput = document.getElementById(strains[i] + quantityStr);
var subTotalDiv = document.getElementById(strains[i] + subtotalStr);
if(subTotalDiv) {
var price = priceInput.value;
var quantity = quantityInput.value;
subTotalDiv
.innerHTML = parseInt(price) * parseInt(quantity);
total += price * quantity;
}
}
document.getElementById("finaltotal").value = total;
}
function setup() {
var lastCol = document.getElementById("subtotal_header");
var theForm = document.getElementById("orderform");
var amounts = document.getElementsByTagName("select");
for(var i = 0; i < amounts.length; i++){
amounts[i].onchange = doTotals;
}
}
window.onload = setup;
<div class="form-group mb-3">
<label class="form-control-label" for="guptakush_quantity">Gupta Kush</label>
<input type="hidden" id="guptakush_price" value="1.00">
<select class="form-control-inline form-control-sm" id="guptakush_quantity" name="guptakush_quantity" size="1">
<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>
<input type="hidden" id="guptakush_subtotal">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input type="text" class="form-control-inline col-sm-1" id="finaltotal" name="finaltotal" placeholder="$0.00" readonly>
</div>
Plenty of issues:
You hadn't defined subtotalStr, so that was null
You weren't executing your setup function because you didn't include parentheses
Your <strong> element doesn't seem to be populatable when selecting it by ID (not sure what was up w/that, but changing it to a div worked).
Check this: https://jsfiddle.net/mj1z9bvq/
In my version, I fixed the first two problems. And then for the first <strong> element, I replaced it with a <div> so you could see the output. You'll have to go through and do something similar for the others.

function needs to wait until select tag's value selected

I have a function in my main.js needs to wait until some options selected on select tag. According to that, I will update the element. I tried to do it with addlistenerevent, but I could not succeed it. Any suggestions? Am I doing wrong?
var test = function() {
const langOptions = {
dummy: 0,
one: 5,
two: 8,
three: 2
};
var unit_1 = 1;
var selectSource ="";
var selectTarget = "";
var section = document.getElementById("unit");
var span_1 = '<span>Unit : </span>';
section.insertAdjacentHTML("beforeend", span_1);
var span_2 = '<span id= "span_2">' + unit_1 +'</span>';
section.insertAdjacentHTML("beforeend", span_2);
document.getElementById('source-lang').addEventListener('change', function() {
selectSource = $('source-lang').find('select').val();
for (const key of Object.keys(langOptions)) {
if (key === selectSource || key === selectTarget) { unitPrice *= langOptions[key];}
}
var element = document.getElementById('span_2').innerHTML = unit_1;
});
};
test();
<div id="langs">
<section class="container">
<div class="dropdown">
<select id="source-lang" style="background-color:#5e3080" name="source-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang">
<option value="">Select</option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
</div>
<div class="dropdown">
<div id="unit"></div>
</div>
</section>
</div>
I think that what you are looking for, is the onchange Event
function selectOne() {
const id = 'selectOne';
console.log(id, document.getElementById(id).value);
}
document.getElementById('selectTwo').addEventListener("change", function() {
console.log(this.id, this.value)
});
<p>Select One</p>
<select id="selectOne" type="text" onchange="selectOne()">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<!-- Or using addEventListener -->
<p>Select Two</p>
<select id="selectTwo" type="text">
<option value=a>a</option>
<option value=b>b</option>
<option value=c>c</option>
</select>
Use onchange Event
<select id="source-lang" style="background-color:#5e3080" name="source-lang" onchange="test()">
<select id ="target-lang" style="background-color:#5e3080" name="target-lang" onchange="test()">

javascript/typescript: find index value of an input group

I have the following code
<div id="select_group">
<div id=“attr_1”>
<label>One</label>
<select class="form-control" id=“1” (change)="NextAttr($event)” name="selectProd">
<option value="0">Select</option>
<option *ngFor = "let prod of selectProduct.values" value="{{prod}}">{{prod}}</option>
</select>
</div>
<div id=“attr_2”>
<label>One</label>
<select class="form-control" id=“2” (change)="NextAttr($event)” name="selectProd">
<option value="0">Select</option>
<option *ngFor = "let prod of selectProduct.values" value="{{prod}}">{{prod}}</option>
</select>
</div>
<div id=“attr_3”>
<label>One</label>
<select class="form-control" id=“3” (change)="NextAttr($event)” name="selectProd">
<option value="0">Select</option>
<option *ngFor = "let prod of selectProduct.values" value="{{prod}}">{{prod}}</option>
</select>
</div>
</div>
atrCount:number = 1;
selectNextAttr(id,attr){
var atr = document.getElementById("attr_"+attr) as HTMLSelectElement;
var attrDetails = document.getElementById(attr) as HTMLSelectElement;
var index = atr.ATTRIBUTE_NODE;
let attr_count = this.atrCount++;
let attribute = attrDetails.id; //eg: color
let attribute_val = attrDetails.value;
let queryString:Array<any> =[];
let q = id + "&attribute_set_count=" + attr_count + "&attribute"+attr_count+"="+attribute+"&attribute"+attr_count+"_value="+attribute_val;
queryString.push(q);
this.selNextAttr(q);
}
Dynamic select box:
<div id="attr_{{selectProduct.attribute}}">
<label>{{selectProduct.attribute | uppercase}}</label>
<select class="form-control" id="{{selectProduct.attribute}}" (change)="selectNextAttr(selectProduct.product_id, selectProduct.attribute)" name="selectProd">
<option value="0">Select</option>
<option *ngFor = "let prod of selectProduct.values" value="{{prod}}">{{prod}}</option>
</select>
</div>
How do I get the index value of these select boxes using javascript or typescript? For example; if an items from the first select box is chosen I would like to return an index of 1. Thanks for the help.
A

Product Filtering PHP

Hello guys I'm doing a product filtering and I don't know how could I achieve it.
I used Javascript by getting the value of the selected values then alert it but the problem is that how could I display it also how can I remove the categories selected by clicking the x button. Here the sample page. Thank you very much for your help.
Here is my script code:
<script>
jQuery("#filter").val()
jQuery(function(){
jQuery( ".product-line" ).each(function( index ) {
var url = '<?php echo $upload_url; ?>';
var desc_id = jQuery(this).eq(0).find('.prod-desc').attr('id');
if(desc_id){
var file_url = url + desc_id + '/description.html';
jQuery('#'+desc_id).eq(0).load( file_url );
}
});
jQuery("#brand,#screen_size,#cpu,#memory,#price").change(function() {
        var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
var cpu = jQuery("#cpu").val();
var memory = jQuery("#memory").val();
var price = jQuery("#price").val();
var categories =[];
if(brand)
{
categories.push(brand);
}
if(screen_size)
{
categories.push(screen_size);
}
if(cpu)
{
categories.push(cpu);
}
if(memory)
{
categories.push(memory);
}
if(price)
{
categories.push(price);
}
length = categories.length;
categories2 = categories.toString();
alert(categories2);
var categories3="";
for(var i = 0; i < length; i++){
categories3 += "<div class='filter_style'>"+categories[i]+"<span style='margin-left:15px;color:gray;'>x</span></div>";
jQuery("#filter").html(categories3);
}
      });
});
</script>
 My HTML Code:
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="brand" >
<option value="">Select a Brand</option>
<option value="Lenovo">Lenovo</option>
<option value="Acer">Acer</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="screen_size" style="margin-top:0px;">
<option value="">Select a Screen Size</option>
<option value="Small">Small</option>
<option value="Large">Large</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="cpu">
<option value="">Select a CPU</option>
<option value="Intel">Intel</option>
<option value="Amd">Amd</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="memory">
<option value="">Select a Memory</option>
<option value="500mb">500mb</option>
<option value="1tb">1tb</option>
</select>
</div>
<div style="margin-bottom:5px;">
<select class="form-control product-type" id="price">
<option value="">Filter by Price</option>
<option value="10000">10000</option>
<option value="20000">20000</option>
</select>
</div>
</div>
There is possibilities, I will UPDATE the answer if it wasn't correct.
But first can you help what will you get after you run this code?
jQuery("#brand,#screen_size").change(function() {
var brand = jQuery("#brand").val();
var screen_size = jQuery("#screen_size").val();
console.log(brand);
console.log(screen_size);
});

A selected value of a <select> can modify another <select>?

I have 2 selects and what i wanna do is (without refreshing the page): the moment the user selects a value from the first select (value1 or value2) changes the second select: if he choosed value1, then he have a select with values a, b, c, d; if he choosed value2, then he can choose on second select e, f, g, h.
Is this possible without refreshing the page?
Edit: I know you all are not here to write code for others; just wanted to keep it simple instead of posting all my messy code :). So, what i want to do, is to modify the second select id=selectAccessiblePaths with the onchange function applyGroupSelection()
function initDivWithConfig () {
divWithInfo = document.createElement('div');
divWithInfo.class = 'divWithInfoControls';
divWithInfo.style.position = 'absolute';
divWithInfo.style.top = '10px';
divWithInfo.style.width = '100%';
divWithInfo.style.textAlign = 'center';
var groupToDisplay = '<p id="pSelectGroup" style="display: block;">Select the user group: ';
groupToDisplay += '<select id="selectGroup" onchange="applyGroupSelection()">';
groupToDisplay += '<option selected>Nothing selected</option>';
for ( var g in userGroups ) {
groupToDisplay += '<option>' + g + '</option>';
}
groupToDisplay += '</select></p>';
divWithInfo.innerHTML += groupToDisplay;
groupSelected = 'group1';
var accessiblePathsToDisplay = '<p id="pSelectAccessiblePaths" style="display: none;">Select the accessible paths: ';
accessiblePathsToDisplay += '<select id="selectAccessiblePaths" onchange="applyAccessiblePathsSelection()">';
accessiblePathsToDisplay += '<option selected>Nothing selected</option>';
for ( var ap=0; ap<userGroups[ groupSelected ].accessiblePaths.length; ap++ ) {
var pathsForThisGroup = userGroups[ groupSelected ].accessiblePaths[ ap ][ "ns0:svg" ][ "groupPathsName" ];
accessiblePathsToDisplay += '<option>' + pathsForThisGroup + '</option>';
}
accessiblePathsToDisplay += '</select></p>';
divWithInfo.innerHTML += accessiblePathsToDisplay;
document.body.appendChild( divWithInfo );
}
function applyGroupSelection () {
groupSelected = "group2";
hideUnhideObject( "pSelectGroup" );
hideUnhideObject( "pSelectAccessiblePaths" );
}
Easy with HTML, CSS and a JavaScript line:
HTML:
<select id='firstselect' onchange="document.getElementById('secondselect').className=this.value">
<option value='select'>Select a value</option>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<select id='secondselect'>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
<option value='d'>d</option>
<option value='e'>e</option>
<option value='f'>f</option>
<option value='g'>g</option>
<option value='h'>h</option>
</select>
CSS:
#secondselect, #secondselect option {
display: none;
}
#secondselect.value1, #secondselect.value2 {
display: block;
}
.value1 option[value="a"], .value1 option[value="b"], .value1 option[value="c"], .value1 option[value="d"] {
display: block !important;
}
.value2 option[value="e"], .value2 option[value="f"], .value2 option[value="g"], .value2 option[value="h"] {
display: block !important;
}
See in action: http://jsfiddle.net/nukz3ns3/
UPDATED:
Also you can do a function for change to default value when firstselect change:
function setSecondSelect( select ){
var secondselect = document.getElementById('secondselect');
secondselect.className=select.value;
secondselect.selectedIndex = (select.value === 'value1')?0:4;
}
See how it works: http://jsfiddle.net/nukz3ns3/1/
Yes this is possible by using ajax post method.
Yes its possible if you used ajax.
http://api.jquery.com/jquery.ajax/
try this:
<script type="text/javascript">
$(document).ready(function () {
$("#select1").change(function() {
if($(this).data('options') == undefined){
$(this).data('options',$('#select2 option').clone());}
var id = $(this).val();
// alert(id);
var options = $(this).data('options').filter('[value=' + id + ']');
if(options.val() == undefined){
//$('#select2').hide();
$('#select2').prop("disabled",true);
}else{
//$('#select2').show();
$('#select2').prop("disabled",false);
$('#select2').html(options);
}
});
});
</script>
<div class="pageCol1">
<div class="panel">
<div class="templateTitle">Request for Items</div>
<table class="grid" border="0" cellspacing="0" cellpadding="0">
<tr class="gridAlternateRow">
<td><b>Item to be Request</b></td>
<td>
<select name="select1" id="select1">
<option value="1">--Select--</option>
<option value="2">Stationaries</option>
<option value="3">Computer Accessories</option>
<option value="4">Bottle</option>
<option value="5">Chair</option>
<option value="6">Office File</option>
<option value="7">Phone Facility</option>
<option value="8">Other Facilities</option>
</select>
</td></tr>
<tr><td>
<b>Category</b>
</td>
<td>
<select name="select2" id="select2" >
<option value="1">--Select--</option>
<option value="2">Note Books</option>
<option value="2">Books</option>
<option value="2">Pen</option>
<option value="2">Pencil</option>
<option value="2">Eraser</option>
<option value="2">Drawing sheets</option>
<option value="2">Others</option>
<option value="3">Laptop</option>
<option value="3">PC</option>
<option value="3">CPU</option>
<option value="3">Monitor</option>
<option value="3">Mouse</option>
<option value="3">Keyboard</option>
<option value="3">Mouse Pad</option>
<option value="3">Hard Disk</option>
<option value="3">Pendrive</option>
<option value="3">CD/DVD Writer</option>
<option value="3">RAM</option>
<option value="3">Mother Board</option>
<option value="3">SMPS</option>
<option value="3">Network Cables</option>
<option value="3">Connectors</option>
<option value="7">Land Line</option>
<option value="7">BlackBerry </option>
<option value="7">Other</option>
</select>
</td>
</tr>
</table>
</div>
</div>
</div>
your html can be of your required format.
If you are trying to populate the second select from existing options,
Try using filter() on a change handler
$("firstselect").change(function() {
var options = $("secondselect").filter(function() {
//return the options you want to display
});
$("secondselect").html(options);
});
Or if you want to retrieve options from server, use AJAX and form the options
and do an innerHTML as above.

Categories